Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 2a52a064

History | View | Annotate | Download (81.5 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 2cc6781a Iustin Pop
class RPCFail(Exception):
50 2cc6781a Iustin Pop
  """Class denoting RPC failure.
51 2cc6781a Iustin Pop

52 2cc6781a Iustin Pop
  Its argument is the error message.
53 2cc6781a Iustin Pop

54 2cc6781a Iustin Pop
  """
55 2cc6781a Iustin Pop
56 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
57 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
58 2cc6781a Iustin Pop

59 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
60 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
61 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
62 2cc6781a Iustin Pop
  daemon.
63 2cc6781a Iustin Pop

64 2cc6781a Iustin Pop
  @type msg: string
65 2cc6781a Iustin Pop
  @param msg: the text of the exception
66 2cc6781a Iustin Pop
  @raise RPCFail
67 2cc6781a Iustin Pop

68 2cc6781a Iustin Pop
  """
69 2cc6781a Iustin Pop
  if args:
70 2cc6781a Iustin Pop
    msg = msg % args
71 2cc6781a Iustin Pop
  if "exc" in kwargs and kwargs["exc"]:
72 2cc6781a Iustin Pop
    logging.exception(msg)
73 2cc6781a Iustin Pop
  else:
74 2cc6781a Iustin Pop
    logging.error(msg)
75 2cc6781a Iustin Pop
  raise RPCFail(msg)
76 2cc6781a Iustin Pop
77 2cc6781a Iustin Pop
78 c657dcc9 Michael Hanselmann
def _GetConfig():
79 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
80 10c2650b Iustin Pop

81 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
82 93384844 Iustin Pop
  @return: a SimpleStore instance
83 10c2650b Iustin Pop

84 10c2650b Iustin Pop
  """
85 93384844 Iustin Pop
  return ssconf.SimpleStore()
86 c657dcc9 Michael Hanselmann
87 c657dcc9 Michael Hanselmann
88 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
89 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
90 10c2650b Iustin Pop

91 10c2650b Iustin Pop
  @type cluster_name: str
92 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
93 10c2650b Iustin Pop
      by the SshRunner constructor
94 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
95 10c2650b Iustin Pop
  @return: an SshRunner instance
96 10c2650b Iustin Pop

97 10c2650b Iustin Pop
  """
98 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
99 c92b310a Michael Hanselmann
100 c92b310a Michael Hanselmann
101 12bce260 Michael Hanselmann
def _Decompress(data):
102 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
103 12bce260 Michael Hanselmann

104 12bce260 Michael Hanselmann
  @type data: list or tuple
105 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
106 12bce260 Michael Hanselmann
  @rtype: str
107 12bce260 Michael Hanselmann
  @return: Decompressed data
108 12bce260 Michael Hanselmann

109 12bce260 Michael Hanselmann
  """
110 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
111 12bce260 Michael Hanselmann
  assert len(data) == 2
112 12bce260 Michael Hanselmann
  (encoding, content) = data
113 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
114 12bce260 Michael Hanselmann
    return content
115 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
116 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
117 12bce260 Michael Hanselmann
  else:
118 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
119 12bce260 Michael Hanselmann
120 12bce260 Michael Hanselmann
121 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
122 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
123 76ab5558 Michael Hanselmann

124 10c2650b Iustin Pop
  @type path: str
125 10c2650b Iustin Pop
  @param path: the directory to clean
126 76ab5558 Michael Hanselmann
  @type exclude: list
127 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
128 10c2650b Iustin Pop
      to the empty list
129 76ab5558 Michael Hanselmann

130 76ab5558 Michael Hanselmann
  """
131 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
132 3956cee1 Michael Hanselmann
    return
133 3bc6be5c Iustin Pop
  if exclude is None:
134 3bc6be5c Iustin Pop
    exclude = []
135 3bc6be5c Iustin Pop
  else:
136 3bc6be5c Iustin Pop
    # Normalize excluded paths
137 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
138 76ab5558 Michael Hanselmann
139 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
140 76ab5558 Michael Hanselmann
    full_name = os.path.normpath(os.path.join(path, rel_name))
141 76ab5558 Michael Hanselmann
    if full_name in exclude:
142 76ab5558 Michael Hanselmann
      continue
143 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
144 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
145 3956cee1 Michael Hanselmann
146 3956cee1 Michael Hanselmann
147 1bc59f76 Michael Hanselmann
def JobQueuePurge():
148 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
149 10c2650b Iustin Pop

150 10c2650b Iustin Pop
  @rtype: None
151 24fc781f Michael Hanselmann

152 24fc781f Michael Hanselmann
  """
153 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
154 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
155 24fc781f Michael Hanselmann
156 24fc781f Michael Hanselmann
157 bd1e4562 Iustin Pop
def GetMasterInfo():
158 bd1e4562 Iustin Pop
  """Returns master information.
159 bd1e4562 Iustin Pop

160 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
161 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
162 bd1e4562 Iustin Pop

163 bd1e4562 Iustin Pop
  @rtype: tuple
164 2a52a064 Iustin Pop
  @return: True, (master_netdev, master_ip, master_name) in case of success
165 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
166 b1b6ea87 Iustin Pop

167 b1b6ea87 Iustin Pop
  """
168 b1b6ea87 Iustin Pop
  try:
169 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
170 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
171 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
172 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
173 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
174 2a52a064 Iustin Pop
    _Fail("Cluster configuration incomplete", exc=True)
175 2a52a064 Iustin Pop
  return True, (master_netdev, master_ip, master_node)
176 b1b6ea87 Iustin Pop
177 b1b6ea87 Iustin Pop
178 1c65840b Iustin Pop
def StartMaster(start_daemons):
179 a8083063 Iustin Pop
  """Activate local node as master node.
180 a8083063 Iustin Pop

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

185 10c2650b Iustin Pop
  @type start_daemons: boolean
186 10c2650b Iustin Pop
  @param start_daemons: whther to also start the master
187 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
188 10c2650b Iustin Pop
  @rtype: None
189 a8083063 Iustin Pop

190 a8083063 Iustin Pop
  """
191 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
192 2a52a064 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()[1]
193 a8083063 Iustin Pop
194 b726aff0 Iustin Pop
  payload = []
195 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
196 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
197 b1b6ea87 Iustin Pop
      # we already have the ip:
198 b726aff0 Iustin Pop
      logging.debug("Master IP already configured, doing nothing")
199 b1b6ea87 Iustin Pop
    else:
200 b726aff0 Iustin Pop
      msg = "Someone else has the master ip, not activating"
201 b726aff0 Iustin Pop
      logging.error(msg)
202 b726aff0 Iustin Pop
      payload.append(msg)
203 b1b6ea87 Iustin Pop
  else:
204 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
205 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
206 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
207 b1b6ea87 Iustin Pop
    if result.failed:
208 b726aff0 Iustin Pop
      msg = "Can't activate master IP: %s" % result.output
209 b726aff0 Iustin Pop
      logging.error(msg)
210 b726aff0 Iustin Pop
      payload.append(msg)
211 b1b6ea87 Iustin Pop
212 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
213 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
214 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
215 b1b6ea87 Iustin Pop
216 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
217 b1b6ea87 Iustin Pop
  if start_daemons:
218 b1b6ea87 Iustin Pop
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
219 b1b6ea87 Iustin Pop
      result = utils.RunCmd([daemon])
220 b1b6ea87 Iustin Pop
      if result.failed:
221 b726aff0 Iustin Pop
        msg = "Can't start daemon %s: %s" % (daemon, result.output)
222 b726aff0 Iustin Pop
        logging.error(msg)
223 b726aff0 Iustin Pop
        payload.append(msg)
224 b726aff0 Iustin Pop
225 b726aff0 Iustin Pop
  return not payload, "; ".join(payload)
226 a8083063 Iustin Pop
227 a8083063 Iustin Pop
228 1c65840b Iustin Pop
def StopMaster(stop_daemons):
229 a8083063 Iustin Pop
  """Deactivate this node as master.
230 a8083063 Iustin Pop

231 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
232 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
233 10c2650b Iustin Pop
  stop_daemons parameter.
234 10c2650b Iustin Pop

235 10c2650b Iustin Pop
  @type stop_daemons: boolean
236 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
237 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
238 10c2650b Iustin Pop
  @rtype: None
239 a8083063 Iustin Pop

240 a8083063 Iustin Pop
  """
241 6c00d19a Iustin Pop
  # TODO: log and report back to the caller the error failures; we
242 6c00d19a Iustin Pop
  # need to decide in which case we fail the RPC for this
243 2a52a064 Iustin Pop
244 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
245 2a52a064 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()[1]
246 a8083063 Iustin Pop
247 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
248 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
249 a8083063 Iustin Pop
  if result.failed:
250 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
251 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
252 b1b6ea87 Iustin Pop
253 b1b6ea87 Iustin Pop
  if stop_daemons:
254 b1b6ea87 Iustin Pop
    # stop/kill the rapi and the master daemon
255 b1b6ea87 Iustin Pop
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
256 b1b6ea87 Iustin Pop
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
257 a8083063 Iustin Pop
258 6c00d19a Iustin Pop
  return True, None
259 a8083063 Iustin Pop
260 a8083063 Iustin Pop
261 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
262 7900ed01 Iustin Pop
  """Joins this node to the cluster.
263 a8083063 Iustin Pop

264 7900ed01 Iustin Pop
  This does the following:
265 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
266 7900ed01 Iustin Pop
      - adds the ssh private key to the user
267 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
268 a8083063 Iustin Pop

269 10c2650b Iustin Pop
  @type dsa: str
270 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
271 10c2650b Iustin Pop
  @type dsapub: str
272 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
273 10c2650b Iustin Pop
  @type rsa: str
274 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
275 10c2650b Iustin Pop
  @type rsapub: str
276 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
277 10c2650b Iustin Pop
  @type sshkey: str
278 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
279 10c2650b Iustin Pop
  @type sshpub: str
280 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
281 10c2650b Iustin Pop
  @rtype: boolean
282 10c2650b Iustin Pop
  @return: the success of the operation
283 10c2650b Iustin Pop

284 7900ed01 Iustin Pop
  """
285 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
286 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
287 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
288 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
289 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
290 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
291 a8083063 Iustin Pop
292 70d9e3d8 Iustin Pop
  try:
293 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
294 70d9e3d8 Iustin Pop
                                                    mkdir=True)
295 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
296 2cc6781a Iustin Pop
    _Fail("Error while processing user ssh files: %s", err, exc=True)
297 a8083063 Iustin Pop
298 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
299 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
300 a8083063 Iustin Pop
301 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
302 a8083063 Iustin Pop
303 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
304 a8083063 Iustin Pop
305 a1b805fb Iustin Pop
  return (True, "Node added successfully")
306 a8083063 Iustin Pop
307 a8083063 Iustin Pop
308 a8083063 Iustin Pop
def LeaveCluster():
309 10c2650b Iustin Pop
  """Cleans up and remove the current node.
310 10c2650b Iustin Pop

311 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
312 10c2650b Iustin Pop
  from the cluster.
313 10c2650b Iustin Pop

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

318 a8083063 Iustin Pop
  """
319 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
320 1bc59f76 Michael Hanselmann
  JobQueuePurge()
321 f78346f5 Michael Hanselmann
322 70d9e3d8 Iustin Pop
  try:
323 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
324 7900ed01 Iustin Pop
325 0623d351 Iustin Pop
    f = open(pub_key, 'r')
326 0623d351 Iustin Pop
    try:
327 0623d351 Iustin Pop
      utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
328 0623d351 Iustin Pop
    finally:
329 0623d351 Iustin Pop
      f.close()
330 a8083063 Iustin Pop
331 0623d351 Iustin Pop
    utils.RemoveFile(priv_key)
332 0623d351 Iustin Pop
    utils.RemoveFile(pub_key)
333 0623d351 Iustin Pop
  except errors.OpExecError:
334 0623d351 Iustin Pop
    logging.exception("Error while processing ssh files")
335 a8083063 Iustin Pop
336 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
337 0623d351 Iustin Pop
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
338 6d8b6238 Guido Trotter
339 a8083063 Iustin Pop
340 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
341 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
342 a8083063 Iustin Pop

343 e69d05fd Iustin Pop
  @type vgname: C{string}
344 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
345 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
346 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
347 e69d05fd Iustin Pop
      memory information
348 e69d05fd Iustin Pop
  @rtype: C{dict}
349 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
350 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
351 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
352 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
353 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
354 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
355 a8083063 Iustin Pop

356 098c0958 Michael Hanselmann
  """
357 a8083063 Iustin Pop
  outputarray = {}
358 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
359 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
360 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
361 a8083063 Iustin Pop
362 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
363 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
364 a8083063 Iustin Pop
  if hyp_info is not None:
365 a8083063 Iustin Pop
    outputarray.update(hyp_info)
366 a8083063 Iustin Pop
367 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
368 3ef10550 Michael Hanselmann
  try:
369 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
370 3ef10550 Michael Hanselmann
  finally:
371 3ef10550 Michael Hanselmann
    f.close()
372 3ef10550 Michael Hanselmann
373 070e998b Iustin Pop
  return True, outputarray
374 a8083063 Iustin Pop
375 a8083063 Iustin Pop
376 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
377 a8083063 Iustin Pop
  """Verify the status of the local node.
378 a8083063 Iustin Pop

379 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
380 e69d05fd Iustin Pop
  local node.
381 e69d05fd Iustin Pop

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

385 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
386 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
387 e69d05fd Iustin Pop
  report).
388 a8083063 Iustin Pop

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

393 e69d05fd Iustin Pop
  @type what: C{dict}
394 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
395 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
396 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
397 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
398 e69d05fd Iustin Pop
        connectivity with
399 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
400 10c2650b Iustin Pop
  @rtype: dict
401 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
402 10c2650b Iustin Pop
      values representing the result of the checks
403 a8083063 Iustin Pop

404 a8083063 Iustin Pop
  """
405 a8083063 Iustin Pop
  result = {}
406 a8083063 Iustin Pop
407 25361b9a Iustin Pop
  if constants.NV_HYPERVISOR in what:
408 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
409 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
410 25361b9a Iustin Pop
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
411 25361b9a Iustin Pop
412 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
413 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
414 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
415 25361b9a Iustin Pop
416 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
417 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
418 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
419 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
420 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
421 a8083063 Iustin Pop
      if not success:
422 25361b9a Iustin Pop
        tmp[node] = message
423 25361b9a Iustin Pop
424 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
425 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
426 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
427 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
428 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
429 9d4bfc96 Iustin Pop
      if name == my_name:
430 9d4bfc96 Iustin Pop
        my_pip = pip
431 9d4bfc96 Iustin Pop
        my_sip = sip
432 9d4bfc96 Iustin Pop
        break
433 9d4bfc96 Iustin Pop
    if not my_pip:
434 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
435 25361b9a Iustin Pop
                      " in the node list")
436 9d4bfc96 Iustin Pop
    else:
437 c657dcc9 Michael Hanselmann
      port = utils.GetNodeDaemonPort()
438 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
439 9d4bfc96 Iustin Pop
        fail = []
440 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
441 9d4bfc96 Iustin Pop
          fail.append("primary")
442 9d4bfc96 Iustin Pop
        if sip != pip:
443 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
444 9d4bfc96 Iustin Pop
            fail.append("secondary")
445 9d4bfc96 Iustin Pop
        if fail:
446 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
447 25361b9a Iustin Pop
                       " and ".join(fail))
448 25361b9a Iustin Pop
449 25361b9a Iustin Pop
  if constants.NV_LVLIST in what:
450 25361b9a Iustin Pop
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
451 25361b9a Iustin Pop
452 25361b9a Iustin Pop
  if constants.NV_INSTANCELIST in what:
453 25361b9a Iustin Pop
    result[constants.NV_INSTANCELIST] = GetInstanceList(
454 25361b9a Iustin Pop
      what[constants.NV_INSTANCELIST])
455 25361b9a Iustin Pop
456 25361b9a Iustin Pop
  if constants.NV_VGLIST in what:
457 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
458 25361b9a Iustin Pop
459 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
460 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
461 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
462 25361b9a Iustin Pop
463 25361b9a Iustin Pop
  if constants.NV_HVINFO in what:
464 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
465 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
466 9d4bfc96 Iustin Pop
467 6d2e83d5 Iustin Pop
  if constants.NV_DRBDLIST in what:
468 6d2e83d5 Iustin Pop
    try:
469 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
470 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
471 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
472 f6eaed12 Iustin Pop
      used_minors = str(err)
473 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
474 6d2e83d5 Iustin Pop
475 6f68a739 Iustin Pop
  return True, result
476 a8083063 Iustin Pop
477 a8083063 Iustin Pop
478 a8083063 Iustin Pop
def GetVolumeList(vg_name):
479 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
480 a8083063 Iustin Pop

481 10c2650b Iustin Pop
  @type vg_name: str
482 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
483 10c2650b Iustin Pop
  @rtype: dict
484 10c2650b Iustin Pop
  @return:
485 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
486 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
487 10c2650b Iustin Pop

488 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
489 10c2650b Iustin Pop

490 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
491 10c2650b Iustin Pop
      details.
492 a8083063 Iustin Pop

493 a8083063 Iustin Pop
  """
494 cb2037a2 Iustin Pop
  lvs = {}
495 cb2037a2 Iustin Pop
  sep = '|'
496 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
497 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
498 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
499 a8083063 Iustin Pop
  if result.failed:
500 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
501 cb2037a2 Iustin Pop
502 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
503 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
504 df4c2628 Iustin Pop
    line = line.strip()
505 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
506 df4c2628 Iustin Pop
    if not match:
507 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
508 df4c2628 Iustin Pop
      continue
509 df4c2628 Iustin Pop
    name, size, attr = match.groups()
510 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
511 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
512 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
513 cb2037a2 Iustin Pop
514 cb2037a2 Iustin Pop
  return lvs
515 a8083063 Iustin Pop
516 a8083063 Iustin Pop
517 a8083063 Iustin Pop
def ListVolumeGroups():
518 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
519 a8083063 Iustin Pop

520 10c2650b Iustin Pop
  @rtype: dict
521 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
522 10c2650b Iustin Pop
      size of the volume
523 a8083063 Iustin Pop

524 a8083063 Iustin Pop
  """
525 e480923b Iustin Pop
  return True, utils.ListVolumeGroups()
526 a8083063 Iustin Pop
527 a8083063 Iustin Pop
528 dcb93971 Michael Hanselmann
def NodeVolumes():
529 dcb93971 Michael Hanselmann
  """List all volumes on this node.
530 dcb93971 Michael Hanselmann

531 10c2650b Iustin Pop
  @rtype: list
532 10c2650b Iustin Pop
  @return:
533 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
534 10c2650b Iustin Pop
      - name: the logical volume name,
535 10c2650b Iustin Pop
      - size: the size of the logical volume
536 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
537 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
538 10c2650b Iustin Pop

539 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
540 10c2650b Iustin Pop
    error.
541 10c2650b Iustin Pop

542 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
543 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
544 10c2650b Iustin Pop
    multiple times.
545 10c2650b Iustin Pop

546 dcb93971 Michael Hanselmann
  """
547 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
548 dcb93971 Michael Hanselmann
                         "--separator=|",
549 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
550 dcb93971 Michael Hanselmann
  if result.failed:
551 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
552 10bfe6cb Iustin Pop
          result.output)
553 dcb93971 Michael Hanselmann
554 dcb93971 Michael Hanselmann
  def parse_dev(dev):
555 dcb93971 Michael Hanselmann
    if '(' in dev:
556 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
557 dcb93971 Michael Hanselmann
    else:
558 dcb93971 Michael Hanselmann
      return dev
559 dcb93971 Michael Hanselmann
560 dcb93971 Michael Hanselmann
  def map_line(line):
561 dcb93971 Michael Hanselmann
    return {
562 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
563 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
564 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
565 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
566 dcb93971 Michael Hanselmann
    }
567 dcb93971 Michael Hanselmann
568 10bfe6cb Iustin Pop
  return True, [map_line(line.split('|'))
569 10bfe6cb Iustin Pop
                for line in result.stdout.splitlines()
570 10bfe6cb Iustin Pop
                if line.count('|') >= 3]
571 dcb93971 Michael Hanselmann
572 dcb93971 Michael Hanselmann
573 a8083063 Iustin Pop
def BridgesExist(bridges_list):
574 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
575 a8083063 Iustin Pop

576 b1206984 Iustin Pop
  @rtype: boolean
577 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
578 a8083063 Iustin Pop

579 a8083063 Iustin Pop
  """
580 35c0c8da Iustin Pop
  missing = []
581 a8083063 Iustin Pop
  for bridge in bridges_list:
582 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
583 35c0c8da Iustin Pop
      missing.append(bridge)
584 a8083063 Iustin Pop
585 35c0c8da Iustin Pop
  if missing:
586 35c0c8da Iustin Pop
    return False, "Missing bridges %s" % (", ".join(missing),)
587 35c0c8da Iustin Pop
588 35c0c8da Iustin Pop
  return True, None
589 a8083063 Iustin Pop
590 a8083063 Iustin Pop
591 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
592 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
593 a8083063 Iustin Pop

594 e69d05fd Iustin Pop
  @type hypervisor_list: list
595 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
596 e69d05fd Iustin Pop

597 e69d05fd Iustin Pop
  @rtype: list
598 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
599 10c2650b Iustin Pop
    - instance1.example.com
600 10c2650b Iustin Pop
    - instance2.example.com
601 a8083063 Iustin Pop

602 098c0958 Michael Hanselmann
  """
603 e69d05fd Iustin Pop
  results = []
604 e69d05fd Iustin Pop
  for hname in hypervisor_list:
605 e69d05fd Iustin Pop
    try:
606 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
607 e69d05fd Iustin Pop
      results.extend(names)
608 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
609 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
610 aca13712 Iustin Pop
            hname, err, exc=True)
611 a8083063 Iustin Pop
612 e69d05fd Iustin Pop
  return results
613 a8083063 Iustin Pop
614 a8083063 Iustin Pop
615 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
616 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
617 a8083063 Iustin Pop

618 e69d05fd Iustin Pop
  @type instance: string
619 e69d05fd Iustin Pop
  @param instance: the instance name
620 e69d05fd Iustin Pop
  @type hname: string
621 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
622 a8083063 Iustin Pop

623 e69d05fd Iustin Pop
  @rtype: dict
624 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
625 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
626 e69d05fd Iustin Pop
      - state: xen state of instance (string)
627 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
628 a8083063 Iustin Pop

629 098c0958 Michael Hanselmann
  """
630 a8083063 Iustin Pop
  output = {}
631 a8083063 Iustin Pop
632 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
633 a8083063 Iustin Pop
  if iinfo is not None:
634 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
635 a8083063 Iustin Pop
    output['state'] = iinfo[4]
636 a8083063 Iustin Pop
    output['time'] = iinfo[5]
637 a8083063 Iustin Pop
638 7ad1af4a Iustin Pop
  return True, output
639 a8083063 Iustin Pop
640 a8083063 Iustin Pop
641 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
642 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
643 56e7640c Iustin Pop

644 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
645 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
646 56e7640c Iustin Pop

647 56e7640c Iustin Pop
  @rtype: tuple
648 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
649 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
650 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
651 56e7640c Iustin Pop

652 56e7640c Iustin Pop
  """
653 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
654 56e7640c Iustin Pop
  if instance.name not in hyper.ListInstances():
655 56e7640c Iustin Pop
    return (False, 'not running')
656 56e7640c Iustin Pop
657 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
658 56e7640c Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance.name, idx)
659 56e7640c Iustin Pop
    if not os.path.islink(link_name):
660 56e7640c Iustin Pop
      return (False, 'not restarted since ganeti 1.2.5')
661 56e7640c Iustin Pop
662 56e7640c Iustin Pop
  return (True, '')
663 56e7640c Iustin Pop
664 56e7640c Iustin Pop
665 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
666 a8083063 Iustin Pop
  """Gather data about all instances.
667 a8083063 Iustin Pop

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

672 e69d05fd Iustin Pop
  @type hypervisor_list: list
673 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
674 e69d05fd Iustin Pop

675 955db481 Guido Trotter
  @rtype: dict
676 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
677 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
678 e69d05fd Iustin Pop
      - state: xen state of instance (string)
679 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
680 10c2650b Iustin Pop
      - vcpus: the number of vcpus
681 a8083063 Iustin Pop

682 098c0958 Michael Hanselmann
  """
683 a8083063 Iustin Pop
  output = {}
684 a8083063 Iustin Pop
685 e69d05fd Iustin Pop
  for hname in hypervisor_list:
686 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
687 e69d05fd Iustin Pop
    if iinfo:
688 e69d05fd Iustin Pop
      for name, inst_id, memory, vcpus, state, times in iinfo:
689 f23b5ae8 Iustin Pop
        value = {
690 e69d05fd Iustin Pop
          'memory': memory,
691 e69d05fd Iustin Pop
          'vcpus': vcpus,
692 e69d05fd Iustin Pop
          'state': state,
693 e69d05fd Iustin Pop
          'time': times,
694 e69d05fd Iustin Pop
          }
695 b33b6f55 Iustin Pop
        if name in output:
696 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
697 b33b6f55 Iustin Pop
          # and not state and time which can change between the
698 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
699 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
700 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
701 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
702 2fa74ef4 Iustin Pop
                    " with different parameters", name)
703 f23b5ae8 Iustin Pop
        output[name] = value
704 a8083063 Iustin Pop
705 2fa74ef4 Iustin Pop
  return True, output
706 a8083063 Iustin Pop
707 a8083063 Iustin Pop
708 e557bae9 Guido Trotter
def InstanceOsAdd(instance, reinstall):
709 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
710 a8083063 Iustin Pop

711 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
712 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
713 e557bae9 Guido Trotter
  @type reinstall: boolean
714 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
715 10c2650b Iustin Pop
  @rtype: boolean
716 10c2650b Iustin Pop
  @return: the success of the operation
717 a8083063 Iustin Pop

718 a8083063 Iustin Pop
  """
719 1268d6fd Iustin Pop
  try:
720 1268d6fd Iustin Pop
    inst_os = OSFromDisk(instance.os)
721 1268d6fd Iustin Pop
  except errors.InvalidOS, err:
722 1268d6fd Iustin Pop
    os_name, os_dir, os_err = err.args
723 1268d6fd Iustin Pop
    if os_dir is None:
724 1268d6fd Iustin Pop
      return (False, "Can't find OS '%s': %s" % (os_name, os_err))
725 1268d6fd Iustin Pop
    else:
726 1268d6fd Iustin Pop
      return (False, "Error parsing OS '%s' in directory %s: %s" %
727 1268d6fd Iustin Pop
              (os_name, os_dir, os_err))
728 a8083063 Iustin Pop
729 58f6e5ca Guido Trotter
  create_env = OSEnvironment(instance)
730 e557bae9 Guido Trotter
  if reinstall:
731 e557bae9 Guido Trotter
    create_env['INSTANCE_REINSTALL'] = "1"
732 a8083063 Iustin Pop
733 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
734 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
735 decd5f45 Iustin Pop
736 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
737 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
738 decd5f45 Iustin Pop
  if result.failed:
739 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
740 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
741 18682bca Iustin Pop
                  result.output)
742 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
743 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
744 20e01edd Iustin Pop
    return (False, "OS create script failed (%s), last lines in the"
745 20e01edd Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
746 decd5f45 Iustin Pop
747 20e01edd Iustin Pop
  return (True, "Successfully installed")
748 decd5f45 Iustin Pop
749 decd5f45 Iustin Pop
750 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
751 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
752 decd5f45 Iustin Pop

753 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
754 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
755 d15a9ad3 Guido Trotter
  @type old_name: string
756 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
757 10c2650b Iustin Pop
  @rtype: boolean
758 10c2650b Iustin Pop
  @return: the success of the operation
759 decd5f45 Iustin Pop

760 decd5f45 Iustin Pop
  """
761 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
762 decd5f45 Iustin Pop
763 ff38b6c0 Guido Trotter
  rename_env = OSEnvironment(instance)
764 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
765 decd5f45 Iustin Pop
766 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
767 decd5f45 Iustin Pop
                                           old_name,
768 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
769 a8083063 Iustin Pop
770 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
771 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
772 a8083063 Iustin Pop
773 a8083063 Iustin Pop
  if result.failed:
774 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
775 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
776 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
777 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
778 96841384 Iustin Pop
    return (False, "OS rename script failed (%s), last lines in the"
779 96841384 Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
780 a8083063 Iustin Pop
781 96841384 Iustin Pop
  return (True, "Rename successful")
782 a8083063 Iustin Pop
783 a8083063 Iustin Pop
784 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
785 a8083063 Iustin Pop
  """Get informations about the volume group.
786 a8083063 Iustin Pop

787 10c2650b Iustin Pop
  @type vg_name: str
788 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
789 10c2650b Iustin Pop
  @rtype: dict
790 10c2650b Iustin Pop
  @return:
791 10c2650b Iustin Pop
    A dictionary with the following keys:
792 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
793 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
794 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
795 a8083063 Iustin Pop

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

799 a8083063 Iustin Pop
  """
800 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
801 f4d377e7 Iustin Pop
802 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
803 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
804 a8083063 Iustin Pop
805 a8083063 Iustin Pop
  if retval.failed:
806 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
807 f4d377e7 Iustin Pop
    return retdic
808 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
809 f4d377e7 Iustin Pop
  if len(valarr) == 3:
810 f4d377e7 Iustin Pop
    try:
811 f4d377e7 Iustin Pop
      retdic = {
812 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
813 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
814 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
815 f4d377e7 Iustin Pop
        }
816 f4d377e7 Iustin Pop
    except ValueError, err:
817 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
818 f4d377e7 Iustin Pop
  else:
819 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
820 18682bca Iustin Pop
                  " three): %s", str(valarr))
821 a8083063 Iustin Pop
  return retdic
822 a8083063 Iustin Pop
823 a8083063 Iustin Pop
824 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
825 5282084b Iustin Pop
  return os.path.join(constants.DISK_LINKS_DIR,
826 5282084b Iustin Pop
                      "%s:%d" % (instance_name, idx))
827 5282084b Iustin Pop
828 5282084b Iustin Pop
829 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
830 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
831 9332fd8a Iustin Pop

832 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
833 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
834 9332fd8a Iustin Pop

835 9332fd8a Iustin Pop

836 5282084b Iustin Pop
  @param instance_name: the name of the target instance
837 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
838 5282084b Iustin Pop
  @param idx: the disk index
839 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
840 9332fd8a Iustin Pop

841 9332fd8a Iustin Pop
  """
842 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
843 9332fd8a Iustin Pop
  try:
844 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
845 5282084b Iustin Pop
  except OSError, err:
846 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
847 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
848 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
849 9332fd8a Iustin Pop
        os.remove(link_name)
850 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
851 9332fd8a Iustin Pop
    else:
852 9332fd8a Iustin Pop
      raise
853 9332fd8a Iustin Pop
854 9332fd8a Iustin Pop
  return link_name
855 9332fd8a Iustin Pop
856 9332fd8a Iustin Pop
857 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
858 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
859 3c9c571d Iustin Pop

860 3c9c571d Iustin Pop
  """
861 5282084b Iustin Pop
  for idx, disk in enumerate(disks):
862 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
863 5282084b Iustin Pop
    if os.path.islink(link_name):
864 3c9c571d Iustin Pop
      try:
865 03dfa658 Iustin Pop
        os.remove(link_name)
866 03dfa658 Iustin Pop
      except OSError:
867 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
868 3c9c571d Iustin Pop
869 3c9c571d Iustin Pop
870 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
871 a8083063 Iustin Pop
  """Set up an instance's block device(s).
872 a8083063 Iustin Pop

873 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
874 a8083063 Iustin Pop
  devices must be already assembled.
875 a8083063 Iustin Pop

876 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
877 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
878 069cfbf1 Iustin Pop
  @rtype: list
879 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
880 10c2650b Iustin Pop

881 a8083063 Iustin Pop
  """
882 a8083063 Iustin Pop
  block_devices = []
883 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
884 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
885 a8083063 Iustin Pop
    if device is None:
886 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
887 a8083063 Iustin Pop
                                    str(disk))
888 a8083063 Iustin Pop
    device.Open()
889 9332fd8a Iustin Pop
    try:
890 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
891 9332fd8a Iustin Pop
    except OSError, e:
892 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
893 9332fd8a Iustin Pop
                                    e.strerror)
894 9332fd8a Iustin Pop
895 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
896 9332fd8a Iustin Pop
897 a8083063 Iustin Pop
  return block_devices
898 a8083063 Iustin Pop
899 a8083063 Iustin Pop
900 07813a9e Iustin Pop
def StartInstance(instance):
901 a8083063 Iustin Pop
  """Start an instance.
902 a8083063 Iustin Pop

903 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
904 e69d05fd Iustin Pop
  @param instance: the instance object
905 e69d05fd Iustin Pop
  @rtype: boolean
906 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
907 a8083063 Iustin Pop

908 098c0958 Michael Hanselmann
  """
909 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
910 a8083063 Iustin Pop
911 a8083063 Iustin Pop
  if instance.name in running_instances:
912 dd279568 Iustin Pop
    return (True, "Already running")
913 a8083063 Iustin Pop
914 a8083063 Iustin Pop
  try:
915 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
916 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
917 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
918 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
919 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
920 a8083063 Iustin Pop
  except errors.HypervisorError, err:
921 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
922 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
923 a8083063 Iustin Pop
924 dd279568 Iustin Pop
  return (True, "Instance started successfully")
925 a8083063 Iustin Pop
926 a8083063 Iustin Pop
927 1fae010f Iustin Pop
def InstanceShutdown(instance):
928 a8083063 Iustin Pop
  """Shut an instance down.
929 a8083063 Iustin Pop

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

932 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
933 e69d05fd Iustin Pop
  @param instance: the instance object
934 e69d05fd Iustin Pop
  @rtype: boolean
935 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
936 a8083063 Iustin Pop

937 098c0958 Michael Hanselmann
  """
938 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
939 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
940 a8083063 Iustin Pop
941 a8083063 Iustin Pop
  if instance.name not in running_instances:
942 1fae010f Iustin Pop
    return (True, "Instance already stopped")
943 a8083063 Iustin Pop
944 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
945 a8083063 Iustin Pop
  try:
946 a8083063 Iustin Pop
    hyper.StopInstance(instance)
947 a8083063 Iustin Pop
  except errors.HypervisorError, err:
948 2cc6781a Iustin Pop
    _Fail("Failed to stop instance %s: %s", instance.name, err)
949 a8083063 Iustin Pop
950 a8083063 Iustin Pop
  # test every 10secs for 2min
951 a8083063 Iustin Pop
952 a8083063 Iustin Pop
  time.sleep(1)
953 a8083063 Iustin Pop
  for dummy in range(11):
954 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
955 a8083063 Iustin Pop
      break
956 a8083063 Iustin Pop
    time.sleep(10)
957 a8083063 Iustin Pop
  else:
958 a8083063 Iustin Pop
    # the shutdown did not succeed
959 ca77edbc Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, using destroy",
960 ca77edbc Guido Trotter
                  instance.name)
961 a8083063 Iustin Pop
962 a8083063 Iustin Pop
    try:
963 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
964 a8083063 Iustin Pop
    except errors.HypervisorError, err:
965 2cc6781a Iustin Pop
      _Fail("Failed to force stop instance %s: %s", instance.name, err)
966 a8083063 Iustin Pop
967 a8083063 Iustin Pop
    time.sleep(1)
968 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
969 2cc6781a Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", instance.name)
970 a8083063 Iustin Pop
971 5282084b Iustin Pop
  _RemoveBlockDevLinks(instance.name, instance.disks)
972 3c9c571d Iustin Pop
973 1fae010f Iustin Pop
  return (True, "Instance has been shutdown successfully")
974 a8083063 Iustin Pop
975 a8083063 Iustin Pop
976 07813a9e Iustin Pop
def InstanceReboot(instance, reboot_type):
977 007a2f3e Alexander Schreiber
  """Reboot an instance.
978 007a2f3e Alexander Schreiber

979 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
980 10c2650b Iustin Pop
  @param instance: the instance object to reboot
981 10c2650b Iustin Pop
  @type reboot_type: str
982 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
983 10c2650b Iustin Pop
    constants:
984 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
985 10c2650b Iustin Pop
        instance OS, do not recreate the VM
986 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
987 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
988 10c2650b Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_HARD})
989 10c2650b Iustin Pop
        is not accepted here, since that mode is handled
990 10c2650b Iustin Pop
        differently
991 10c2650b Iustin Pop
  @rtype: boolean
992 10c2650b Iustin Pop
  @return: the success of the operation
993 007a2f3e Alexander Schreiber

994 007a2f3e Alexander Schreiber
  """
995 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
996 007a2f3e Alexander Schreiber
997 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
998 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
999 007a2f3e Alexander Schreiber
1000 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1001 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1002 007a2f3e Alexander Schreiber
    try:
1003 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1004 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1005 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1006 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1007 007a2f3e Alexander Schreiber
    try:
1008 ae48ac32 Iustin Pop
      stop_result = InstanceShutdown(instance)
1009 ae48ac32 Iustin Pop
      if not stop_result[0]:
1010 ae48ac32 Iustin Pop
        return stop_result
1011 07813a9e Iustin Pop
      return StartInstance(instance)
1012 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1013 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1014 007a2f3e Alexander Schreiber
  else:
1015 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1016 007a2f3e Alexander Schreiber
1017 489fcbe9 Iustin Pop
  return (True, "Reboot successful")
1018 007a2f3e Alexander Schreiber
1019 007a2f3e Alexander Schreiber
1020 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1021 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1022 6906a9d8 Guido Trotter

1023 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1024 6906a9d8 Guido Trotter
  @param instance: the instance definition
1025 6906a9d8 Guido Trotter

1026 6906a9d8 Guido Trotter
  """
1027 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1028 cd42d0ad Guido Trotter
  try:
1029 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1030 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1031 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1032 cd42d0ad Guido Trotter
  return (True, info)
1033 6906a9d8 Guido Trotter
1034 6906a9d8 Guido Trotter
1035 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1036 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1037 6906a9d8 Guido Trotter

1038 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1039 6906a9d8 Guido Trotter
  @param instance: the instance definition
1040 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1041 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1042 6906a9d8 Guido Trotter
  @type target: string
1043 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1044 6906a9d8 Guido Trotter

1045 6906a9d8 Guido Trotter
  """
1046 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1047 cd42d0ad Guido Trotter
  try:
1048 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1049 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1050 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1051 6906a9d8 Guido Trotter
  return (True, "Accept successfull")
1052 6906a9d8 Guido Trotter
1053 6906a9d8 Guido Trotter
1054 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1055 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1056 6906a9d8 Guido Trotter

1057 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1058 6906a9d8 Guido Trotter
  @param instance: the instance definition
1059 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1060 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1061 6906a9d8 Guido Trotter
  @type success: boolean
1062 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1063 6906a9d8 Guido Trotter

1064 6906a9d8 Guido Trotter
  """
1065 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1066 cd42d0ad Guido Trotter
  try:
1067 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1068 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1069 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1070 6906a9d8 Guido Trotter
  return (True, "Migration Finalized")
1071 6906a9d8 Guido Trotter
1072 6906a9d8 Guido Trotter
1073 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1074 2a10865c Iustin Pop
  """Migrates an instance to another node.
1075 2a10865c Iustin Pop

1076 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1077 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1078 9f0e6b37 Iustin Pop
  @type target: string
1079 9f0e6b37 Iustin Pop
  @param target: the target node name
1080 9f0e6b37 Iustin Pop
  @type live: boolean
1081 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1082 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1083 9f0e6b37 Iustin Pop
  @rtype: tuple
1084 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1085 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1086 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1087 9f0e6b37 Iustin Pop

1088 2a10865c Iustin Pop
  """
1089 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1090 2a10865c Iustin Pop
1091 2a10865c Iustin Pop
  try:
1092 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
1093 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1094 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1095 2a10865c Iustin Pop
  return (True, "Migration successfull")
1096 2a10865c Iustin Pop
1097 2a10865c Iustin Pop
1098 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1099 a8083063 Iustin Pop
  """Creates a block device for an instance.
1100 a8083063 Iustin Pop

1101 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1102 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1103 b1206984 Iustin Pop
  @type size: int
1104 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1105 b1206984 Iustin Pop
  @type owner: str
1106 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1107 b1206984 Iustin Pop
      used for device cache data
1108 b1206984 Iustin Pop
  @type on_primary: boolean
1109 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1110 b1206984 Iustin Pop
  @type info: string
1111 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1112 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1113 b1206984 Iustin Pop

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

1118 a8083063 Iustin Pop
  """
1119 a8083063 Iustin Pop
  clist = []
1120 a8083063 Iustin Pop
  if disk.children:
1121 a8083063 Iustin Pop
    for child in disk.children:
1122 1063abd1 Iustin Pop
      try:
1123 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1124 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1125 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1126 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1127 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1128 a8083063 Iustin Pop
        # be assembled
1129 1063abd1 Iustin Pop
        try:
1130 1063abd1 Iustin Pop
          crdev.Open()
1131 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1132 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1133 a8083063 Iustin Pop
      clist.append(crdev)
1134 a8083063 Iustin Pop
1135 dab69e97 Iustin Pop
  try:
1136 dab69e97 Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, size)
1137 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1138 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1139 6c626518 Iustin Pop
1140 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1141 1063abd1 Iustin Pop
    try:
1142 1063abd1 Iustin Pop
      device.Assemble()
1143 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1144 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1145 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1146 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1147 1063abd1 Iustin Pop
      try:
1148 1063abd1 Iustin Pop
        device.Open(force=True)
1149 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1150 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1151 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1152 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1153 a0c3fea1 Michael Hanselmann
1154 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1155 a0c3fea1 Michael Hanselmann
1156 a8083063 Iustin Pop
  physical_id = device.unique_id
1157 dab69e97 Iustin Pop
  return True, physical_id
1158 a8083063 Iustin Pop
1159 a8083063 Iustin Pop
1160 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1161 a8083063 Iustin Pop
  """Remove a block device.
1162 a8083063 Iustin Pop

1163 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1164 10c2650b Iustin Pop

1165 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1166 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1167 10c2650b Iustin Pop
  @rtype: boolean
1168 10c2650b Iustin Pop
  @return: the success of the operation
1169 a8083063 Iustin Pop

1170 a8083063 Iustin Pop
  """
1171 e1bc0878 Iustin Pop
  msgs = []
1172 e1bc0878 Iustin Pop
  result = True
1173 a8083063 Iustin Pop
  try:
1174 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1175 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1176 a8083063 Iustin Pop
    # probably can't attach
1177 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1178 a8083063 Iustin Pop
    rdev = None
1179 a8083063 Iustin Pop
  if rdev is not None:
1180 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1181 e1bc0878 Iustin Pop
    try:
1182 0c6c04ec Iustin Pop
      rdev.Remove()
1183 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1184 e1bc0878 Iustin Pop
      msgs.append(str(err))
1185 e1bc0878 Iustin Pop
      result = False
1186 3f78eef2 Iustin Pop
    if result:
1187 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1188 e1bc0878 Iustin Pop
1189 a8083063 Iustin Pop
  if disk.children:
1190 a8083063 Iustin Pop
    for child in disk.children:
1191 e1bc0878 Iustin Pop
      c_status, c_msg = BlockdevRemove(child)
1192 e1bc0878 Iustin Pop
      result = result and c_status
1193 e1bc0878 Iustin Pop
      if c_msg: # not an empty message
1194 e1bc0878 Iustin Pop
        msgs.append(c_msg)
1195 e1bc0878 Iustin Pop
1196 e1bc0878 Iustin Pop
  return (result, "; ".join(msgs))
1197 a8083063 Iustin Pop
1198 a8083063 Iustin Pop
1199 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1200 a8083063 Iustin Pop
  """Activate a block device for an instance.
1201 a8083063 Iustin Pop

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

1204 10c2650b Iustin Pop
  @note: this function is called recursively.
1205 a8083063 Iustin Pop

1206 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1207 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1208 10c2650b Iustin Pop
  @type owner: str
1209 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1210 10c2650b Iustin Pop
  @type as_primary: boolean
1211 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1212 10c2650b Iustin Pop
      read/write
1213 a8083063 Iustin Pop

1214 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1215 10c2650b Iustin Pop
      was assembled)
1216 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1217 10c2650b Iustin Pop
      during the activation of the children or the device
1218 10c2650b Iustin Pop
      itself
1219 a8083063 Iustin Pop

1220 a8083063 Iustin Pop
  """
1221 a8083063 Iustin Pop
  children = []
1222 a8083063 Iustin Pop
  if disk.children:
1223 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1224 fc1dc9d7 Iustin Pop
    if mcn == -1:
1225 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1226 fc1dc9d7 Iustin Pop
    else:
1227 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1228 a8083063 Iustin Pop
    for chld_disk in disk.children:
1229 fc1dc9d7 Iustin Pop
      try:
1230 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1231 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1232 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1233 fc1dc9d7 Iustin Pop
          raise
1234 fc1dc9d7 Iustin Pop
        cdev = None
1235 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1236 1063abd1 Iustin Pop
                      str(err))
1237 fc1dc9d7 Iustin Pop
      children.append(cdev)
1238 a8083063 Iustin Pop
1239 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1240 f96e3c4f Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children)
1241 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1242 a8083063 Iustin Pop
    result = r_dev
1243 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1244 a8083063 Iustin Pop
      r_dev.Open()
1245 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1246 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1247 3f78eef2 Iustin Pop
1248 a8083063 Iustin Pop
  else:
1249 a8083063 Iustin Pop
    result = True
1250 a8083063 Iustin Pop
  return result
1251 a8083063 Iustin Pop
1252 a8083063 Iustin Pop
1253 821d1bd1 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary):
1254 a8083063 Iustin Pop
  """Activate a block device for an instance.
1255 a8083063 Iustin Pop

1256 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1257 a8083063 Iustin Pop

1258 b1206984 Iustin Pop
  @rtype: str or boolean
1259 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1260 b1206984 Iustin Pop
      C{True} for secondary nodes
1261 a8083063 Iustin Pop

1262 a8083063 Iustin Pop
  """
1263 1063abd1 Iustin Pop
  status = True
1264 53c14ef1 Iustin Pop
  result = "no error information"
1265 53c14ef1 Iustin Pop
  try:
1266 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1267 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1268 53c14ef1 Iustin Pop
      result = result.dev_path
1269 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1270 53c14ef1 Iustin Pop
    result = "Error while assembling disk: %s" % str(err)
1271 1063abd1 Iustin Pop
    status = False
1272 53c14ef1 Iustin Pop
  return (status, result)
1273 a8083063 Iustin Pop
1274 a8083063 Iustin Pop
1275 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1276 a8083063 Iustin Pop
  """Shut down a block device.
1277 a8083063 Iustin Pop

1278 c41eea6e Iustin Pop
  First, if the device is assembled (Attach() is successfull), then
1279 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1280 c41eea6e Iustin Pop
  shutdown.
1281 a8083063 Iustin Pop

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

1286 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1287 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1288 10c2650b Iustin Pop
      shutdown
1289 10c2650b Iustin Pop
  @rtype: boolean
1290 10c2650b Iustin Pop
  @return: the success of the operation
1291 10c2650b Iustin Pop

1292 a8083063 Iustin Pop
  """
1293 cacfd1fd Iustin Pop
  msgs = []
1294 746f7476 Iustin Pop
  result = True
1295 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1296 a8083063 Iustin Pop
  if r_dev is not None:
1297 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1298 cacfd1fd Iustin Pop
    try:
1299 746f7476 Iustin Pop
      r_dev.Shutdown()
1300 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1301 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1302 cacfd1fd Iustin Pop
      msgs.append(str(err))
1303 cacfd1fd Iustin Pop
      result = False
1304 746f7476 Iustin Pop
1305 a8083063 Iustin Pop
  if disk.children:
1306 a8083063 Iustin Pop
    for child in disk.children:
1307 cacfd1fd Iustin Pop
      c_status, c_msg = BlockdevShutdown(child)
1308 cacfd1fd Iustin Pop
      result = result and c_status
1309 cacfd1fd Iustin Pop
      if c_msg: # not an empty message
1310 cacfd1fd Iustin Pop
        msgs.append(c_msg)
1311 746f7476 Iustin Pop
1312 cacfd1fd Iustin Pop
  return (result, "; ".join(msgs))
1313 a8083063 Iustin Pop
1314 a8083063 Iustin Pop
1315 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1316 153d9724 Iustin Pop
  """Extend a mirrored block device.
1317 a8083063 Iustin Pop

1318 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1319 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1320 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1321 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1322 10c2650b Iustin Pop
  @rtype: boolean
1323 10c2650b Iustin Pop
  @return: the success of the operation
1324 10c2650b Iustin Pop

1325 a8083063 Iustin Pop
  """
1326 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1327 153d9724 Iustin Pop
  if parent_bdev is None:
1328 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1329 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1330 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1331 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1332 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1333 2cc1da8b Iustin Pop
  return (True, None)
1334 a8083063 Iustin Pop
1335 a8083063 Iustin Pop
1336 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1337 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1338 a8083063 Iustin Pop

1339 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1340 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1341 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1342 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1343 10c2650b Iustin Pop
  @rtype: boolean
1344 10c2650b Iustin Pop
  @return: the success of the operation
1345 10c2650b Iustin Pop

1346 a8083063 Iustin Pop
  """
1347 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1348 153d9724 Iustin Pop
  if parent_bdev is None:
1349 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1350 e739bd57 Iustin Pop
  devs = []
1351 e739bd57 Iustin Pop
  for disk in new_cdevs:
1352 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1353 e739bd57 Iustin Pop
    if rpath is None:
1354 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1355 e739bd57 Iustin Pop
      if bd is None:
1356 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1357 e739bd57 Iustin Pop
      else:
1358 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1359 e739bd57 Iustin Pop
    else:
1360 e739bd57 Iustin Pop
      devs.append(rpath)
1361 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1362 9205a895 Iustin Pop
  return (True, None)
1363 a8083063 Iustin Pop
1364 a8083063 Iustin Pop
1365 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1366 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1367 a8083063 Iustin Pop

1368 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1369 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1370 10c2650b Iustin Pop
  @rtype: disk
1371 10c2650b Iustin Pop
  @return:
1372 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1373 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1374 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1375 10c2650b Iustin Pop
      found
1376 a8083063 Iustin Pop

1377 a8083063 Iustin Pop
  """
1378 a8083063 Iustin Pop
  stats = []
1379 a8083063 Iustin Pop
  for dsk in disks:
1380 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1381 a8083063 Iustin Pop
    if rbd is None:
1382 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1383 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1384 3efa9051 Iustin Pop
  return True, stats
1385 a8083063 Iustin Pop
1386 a8083063 Iustin Pop
1387 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1388 a8083063 Iustin Pop
  """Check if a device is activated.
1389 a8083063 Iustin Pop

1390 a8083063 Iustin Pop
  If so, return informations about the real device.
1391 a8083063 Iustin Pop

1392 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1393 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1394 a8083063 Iustin Pop

1395 10c2650b Iustin Pop
  @return: None if the device can't be found,
1396 10c2650b Iustin Pop
      otherwise the device instance
1397 a8083063 Iustin Pop

1398 a8083063 Iustin Pop
  """
1399 a8083063 Iustin Pop
  children = []
1400 a8083063 Iustin Pop
  if disk.children:
1401 a8083063 Iustin Pop
    for chdisk in disk.children:
1402 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1403 a8083063 Iustin Pop
1404 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
1405 a8083063 Iustin Pop
1406 a8083063 Iustin Pop
1407 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1408 a8083063 Iustin Pop
  """Check if a device is activated.
1409 a8083063 Iustin Pop

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

1412 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1413 10c2650b Iustin Pop
  @param disk: the disk to find
1414 10c2650b Iustin Pop
  @rtype: None or tuple
1415 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1416 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1417 10c2650b Iustin Pop
      estimated_time, is_degraded)
1418 a8083063 Iustin Pop

1419 a8083063 Iustin Pop
  """
1420 23829f6f Iustin Pop
  try:
1421 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1422 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1423 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1424 a8083063 Iustin Pop
  if rbd is None:
1425 23829f6f Iustin Pop
    return (True, None)
1426 23829f6f Iustin Pop
  return (True, (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus())
1427 a8083063 Iustin Pop
1428 a8083063 Iustin Pop
1429 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1430 a8083063 Iustin Pop
  """Write a file to the filesystem.
1431 a8083063 Iustin Pop

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

1435 10c2650b Iustin Pop
  @type file_name: str
1436 10c2650b Iustin Pop
  @param file_name: the target file name
1437 10c2650b Iustin Pop
  @type data: str
1438 10c2650b Iustin Pop
  @param data: the new contents of the file
1439 10c2650b Iustin Pop
  @type mode: int
1440 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1441 10c2650b Iustin Pop
  @type uid: int
1442 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1443 10c2650b Iustin Pop
  @type gid: int
1444 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1445 10c2650b Iustin Pop
  @type atime: float
1446 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1447 10c2650b Iustin Pop
  @type mtime: float
1448 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1449 10c2650b Iustin Pop
  @rtype: boolean
1450 10c2650b Iustin Pop
  @return: the success of the operation; errors are logged
1451 10c2650b Iustin Pop
      in the node daemon log
1452 10c2650b Iustin Pop

1453 a8083063 Iustin Pop
  """
1454 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1455 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1456 a8083063 Iustin Pop
1457 4501a443 Guido Trotter
  allowed_files = set([
1458 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1459 97628462 Iustin Pop
    constants.ETC_HOSTS,
1460 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1461 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1462 4501a443 Guido Trotter
    constants.RAPI_CERT_FILE,
1463 4501a443 Guido Trotter
    constants.RAPI_USERS_FILE,
1464 4501a443 Guido Trotter
    ])
1465 4501a443 Guido Trotter
1466 4501a443 Guido Trotter
  for hv_name in constants.HYPER_TYPES:
1467 4501a443 Guido Trotter
    hv_class = hypervisor.GetHypervisor(hv_name)
1468 4501a443 Guido Trotter
    allowed_files.update(hv_class.GetAncillaryFiles())
1469 afee8008 Michael Hanselmann
1470 553f1c1d Michael Hanselmann
  if file_name not in allowed_files:
1471 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1472 2cc6781a Iustin Pop
          file_name)
1473 a8083063 Iustin Pop
1474 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1475 12bce260 Michael Hanselmann
1476 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1477 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1478 1b54fc6c Guido Trotter
  return (True, "success")
1479 a8083063 Iustin Pop
1480 386b57af Iustin Pop
1481 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1482 89b14f05 Iustin Pop
  """Update all ssconf files.
1483 89b14f05 Iustin Pop

1484 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1485 89b14f05 Iustin Pop

1486 89b14f05 Iustin Pop
  """
1487 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1488 6ddc95ec Michael Hanselmann
1489 6ddc95ec Michael Hanselmann
1490 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1491 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1492 a8083063 Iustin Pop

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

1497 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1498 10c2650b Iustin Pop
  @param err: the exception to format
1499 a8083063 Iustin Pop

1500 a8083063 Iustin Pop
  """
1501 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1502 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1503 a8083063 Iustin Pop
  else:
1504 a8083063 Iustin Pop
    detail = str(err)
1505 a8083063 Iustin Pop
  return detail
1506 a8083063 Iustin Pop
1507 5d0fe286 Iustin Pop
1508 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1509 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1510 a8083063 Iustin Pop

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

1514 10c2650b Iustin Pop
  @type name: str
1515 10c2650b Iustin Pop
  @param name: the OS name we should look for
1516 10c2650b Iustin Pop
  @type os_dir: str
1517 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1518 10c2650b Iustin Pop
  @rtype: int or None
1519 10c2650b Iustin Pop
  @return:
1520 10c2650b Iustin Pop
      Either an integer denoting the version or None in the
1521 10c2650b Iustin Pop
      case when this is not a valid OS name.
1522 10c2650b Iustin Pop
  @raise errors.InvalidOS: if the OS cannot be found
1523 a8083063 Iustin Pop

1524 a8083063 Iustin Pop
  """
1525 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1526 a8083063 Iustin Pop
1527 a8083063 Iustin Pop
  try:
1528 a8083063 Iustin Pop
    st = os.stat(api_file)
1529 a8083063 Iustin Pop
  except EnvironmentError, err:
1530 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1531 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1532 a8083063 Iustin Pop
1533 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1534 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1535 3ecf6786 Iustin Pop
                           " a regular file")
1536 a8083063 Iustin Pop
1537 a8083063 Iustin Pop
  try:
1538 a8083063 Iustin Pop
    f = open(api_file)
1539 a8083063 Iustin Pop
    try:
1540 082a7f91 Guido Trotter
      api_versions = f.readlines()
1541 a8083063 Iustin Pop
    finally:
1542 a8083063 Iustin Pop
      f.close()
1543 a8083063 Iustin Pop
  except EnvironmentError, err:
1544 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1545 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1546 a8083063 Iustin Pop
1547 082a7f91 Guido Trotter
  api_versions = [version.strip() for version in api_versions]
1548 a8083063 Iustin Pop
  try:
1549 082a7f91 Guido Trotter
    api_versions = [int(version) for version in api_versions]
1550 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1551 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1552 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1553 a8083063 Iustin Pop
1554 082a7f91 Guido Trotter
  return api_versions
1555 a8083063 Iustin Pop
1556 386b57af Iustin Pop
1557 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1558 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1559 a8083063 Iustin Pop

1560 10c2650b Iustin Pop
  @type top_dirs: list
1561 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1562 10c2650b Iustin Pop
      search (if not given defaults to
1563 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1564 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1565 10c2650b Iustin Pop
  @return: an OS object for each name in all the given
1566 10c2650b Iustin Pop
      directories
1567 a8083063 Iustin Pop

1568 a8083063 Iustin Pop
  """
1569 7c3d51d4 Guido Trotter
  if top_dirs is None:
1570 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1571 a8083063 Iustin Pop
1572 a8083063 Iustin Pop
  result = []
1573 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1574 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1575 7c3d51d4 Guido Trotter
      try:
1576 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1577 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1578 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1579 7c3d51d4 Guido Trotter
        break
1580 7c3d51d4 Guido Trotter
      for name in f_names:
1581 7c3d51d4 Guido Trotter
        try:
1582 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1583 7c3d51d4 Guido Trotter
          result.append(os_inst)
1584 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1585 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1586 a8083063 Iustin Pop
1587 a8083063 Iustin Pop
  return result
1588 a8083063 Iustin Pop
1589 a8083063 Iustin Pop
1590 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1591 a8083063 Iustin Pop
  """Create an OS instance from disk.
1592 a8083063 Iustin Pop

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

1597 8ee4dc80 Guido Trotter
  @type base_dir: string
1598 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1599 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1600 10c2650b Iustin Pop
  @rtype: L{objects.OS}
1601 10c2650b Iustin Pop
  @return: the OS instance if we find a valid one
1602 10c2650b Iustin Pop
  @raise errors.InvalidOS: if we don't find a valid OS
1603 7c3d51d4 Guido Trotter

1604 a8083063 Iustin Pop
  """
1605 56bcd3f4 Guido Trotter
  if base_dir is None:
1606 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1607 c34c0cfd Iustin Pop
    if os_dir is None:
1608 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1609 c34c0cfd Iustin Pop
  else:
1610 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1611 a8083063 Iustin Pop
1612 082a7f91 Guido Trotter
  api_versions = _OSOndiskVersion(name, os_dir)
1613 a8083063 Iustin Pop
1614 082a7f91 Guido Trotter
  if constants.OS_API_VERSION not in api_versions:
1615 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1616 305a7297 Guido Trotter
                           " (found %s want %s)"
1617 082a7f91 Guido Trotter
                           % (api_versions, constants.OS_API_VERSION))
1618 a8083063 Iustin Pop
1619 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1620 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1621 a8083063 Iustin Pop
1622 a8083063 Iustin Pop
  for script in os_scripts:
1623 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1624 a8083063 Iustin Pop
1625 a8083063 Iustin Pop
    try:
1626 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1627 a8083063 Iustin Pop
    except EnvironmentError, err:
1628 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1629 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1630 a8083063 Iustin Pop
1631 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1632 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1633 305a7297 Guido Trotter
                             script)
1634 a8083063 Iustin Pop
1635 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1636 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1637 305a7297 Guido Trotter
                             script)
1638 a8083063 Iustin Pop
1639 a8083063 Iustin Pop
1640 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1641 62dbbe7e Guido Trotter
                    create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1642 62dbbe7e Guido Trotter
                    export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1643 62dbbe7e Guido Trotter
                    import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1644 62dbbe7e Guido Trotter
                    rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1645 082a7f91 Guido Trotter
                    api_versions=api_versions)
1646 a8083063 Iustin Pop
1647 2266edb2 Guido Trotter
def OSEnvironment(instance, debug=0):
1648 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1649 2266edb2 Guido Trotter

1650 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1651 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1652 2266edb2 Guido Trotter
  @type debug: integer
1653 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1654 2266edb2 Guido Trotter
  @rtype: dict
1655 2266edb2 Guido Trotter
  @return: dict of environment variables
1656 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1657 10c2650b Iustin Pop
      cannot be found
1658 2266edb2 Guido Trotter

1659 2266edb2 Guido Trotter
  """
1660 2266edb2 Guido Trotter
  result = {}
1661 2266edb2 Guido Trotter
  result['OS_API_VERSION'] = '%d' % constants.OS_API_VERSION
1662 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1663 15552312 Iustin Pop
  result['INSTANCE_OS'] = instance.os
1664 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1665 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1666 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1667 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1668 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1669 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1670 2266edb2 Guido Trotter
    if real_disk is None:
1671 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1672 2266edb2 Guido Trotter
                                    str(disk))
1673 2266edb2 Guido Trotter
    real_disk.Open()
1674 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1675 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
1676 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1677 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1678 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1679 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1680 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1681 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1682 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1683 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1684 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1685 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1686 2266edb2 Guido Trotter
    if nic.ip:
1687 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1688 1ba9227f Guido Trotter
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1689 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1690 1ba9227f Guido Trotter
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1691 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
1692 1ba9227f Guido Trotter
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1693 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1694 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1695 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1696 2266edb2 Guido Trotter
1697 2266edb2 Guido Trotter
  return result
1698 a8083063 Iustin Pop
1699 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
1700 594609c0 Iustin Pop
  """Grow a stack of block devices.
1701 594609c0 Iustin Pop

1702 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1703 10c2650b Iustin Pop
  first ones to resize.
1704 594609c0 Iustin Pop

1705 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1706 10c2650b Iustin Pop
  @param disk: the disk to be grown
1707 10c2650b Iustin Pop
  @rtype: (status, result)
1708 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1709 10c2650b Iustin Pop
      (True/False), and the errors message if status
1710 10c2650b Iustin Pop
      is False
1711 594609c0 Iustin Pop

1712 594609c0 Iustin Pop
  """
1713 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1714 594609c0 Iustin Pop
  if r_dev is None:
1715 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1716 594609c0 Iustin Pop
1717 594609c0 Iustin Pop
  try:
1718 594609c0 Iustin Pop
    r_dev.Grow(amount)
1719 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1720 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
1721 594609c0 Iustin Pop
1722 594609c0 Iustin Pop
  return True, None
1723 594609c0 Iustin Pop
1724 594609c0 Iustin Pop
1725 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
1726 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1727 a8083063 Iustin Pop

1728 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1729 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1730 a8083063 Iustin Pop

1731 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1732 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1733 e9e9263d Guido Trotter
  @rtype: string
1734 e9e9263d Guido Trotter
  @return: snapshot disk path
1735 a8083063 Iustin Pop

1736 098c0958 Michael Hanselmann
  """
1737 a8083063 Iustin Pop
  if disk.children:
1738 a8083063 Iustin Pop
    if len(disk.children) == 1:
1739 a8083063 Iustin Pop
      # only one child, let's recurse on it
1740 821d1bd1 Iustin Pop
      return BlockdevSnapshot(disk.children[0])
1741 a8083063 Iustin Pop
    else:
1742 a8083063 Iustin Pop
      # more than one child, choose one that matches
1743 a8083063 Iustin Pop
      for child in disk.children:
1744 a8083063 Iustin Pop
        if child.size == disk.size:
1745 a8083063 Iustin Pop
          # return implies breaking the loop
1746 821d1bd1 Iustin Pop
          return BlockdevSnapshot(child)
1747 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1748 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1749 a8083063 Iustin Pop
    if r_dev is not None:
1750 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1751 87812fd3 Iustin Pop
      return True, r_dev.Snapshot(disk.size)
1752 a8083063 Iustin Pop
    else:
1753 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
1754 a8083063 Iustin Pop
  else:
1755 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1756 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
1757 a8083063 Iustin Pop
1758 a8083063 Iustin Pop
1759 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1760 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1761 a8083063 Iustin Pop

1762 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1763 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1764 74c47259 Iustin Pop
  @type dest_node: str
1765 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1766 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1767 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1768 74c47259 Iustin Pop
  @type cluster_name: str
1769 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1770 74c47259 Iustin Pop
  @type idx: int
1771 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1772 74c47259 Iustin Pop
      used to export to the OS scripts environment
1773 10c2650b Iustin Pop
  @rtype: boolean
1774 74c47259 Iustin Pop
  @return: the success of the operation
1775 a8083063 Iustin Pop

1776 098c0958 Michael Hanselmann
  """
1777 0607699d Guido Trotter
  export_env = OSEnvironment(instance)
1778 d324e3fc Guido Trotter
1779 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1780 a8083063 Iustin Pop
  export_script = inst_os.export_script
1781 a8083063 Iustin Pop
1782 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1783 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1784 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1785 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1786 0607699d Guido Trotter
  real_disk = _RecursiveFindBD(disk)
1787 0607699d Guido Trotter
  if real_disk is None:
1788 ba55d062 Iustin Pop
    _Fail("Block device '%s' is not set up", disk)
1789 ba55d062 Iustin Pop
1790 0607699d Guido Trotter
  real_disk.Open()
1791 0607699d Guido Trotter
1792 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1793 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
1794 a8083063 Iustin Pop
1795 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1796 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1797 a8083063 Iustin Pop
1798 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1799 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1800 a8083063 Iustin Pop
  # valid parameters
1801 0607699d Guido Trotter
  expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1802 0607699d Guido Trotter
                               export_script, logfile)
1803 a8083063 Iustin Pop
1804 a8083063 Iustin Pop
  comprcmd = "gzip"
1805 a8083063 Iustin Pop
1806 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1807 00003458 Guido Trotter
                                destdir, destdir, destfile)
1808 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1809 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1810 62c9ec92 Iustin Pop
                                                   destcmd)
1811 a8083063 Iustin Pop
1812 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1813 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1814 a8083063 Iustin Pop
1815 0607699d Guido Trotter
  result = utils.RunCmd(command, env=export_env)
1816 a8083063 Iustin Pop
1817 a8083063 Iustin Pop
  if result.failed:
1818 ba55d062 Iustin Pop
    _Fail("OS snapshot export command '%s' returned error: %s"
1819 ba55d062 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1820 a8083063 Iustin Pop
1821 ba55d062 Iustin Pop
  return (True, None)
1822 a8083063 Iustin Pop
1823 a8083063 Iustin Pop
1824 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1825 a8083063 Iustin Pop
  """Write out the export configuration information.
1826 a8083063 Iustin Pop

1827 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1828 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
1829 10c2650b Iustin Pop
      saving configuration
1830 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
1831 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
1832 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
1833 a8083063 Iustin Pop

1834 10c2650b Iustin Pop
  @rtype: boolean
1835 10c2650b Iustin Pop
  @return: the success of the operation
1836 a8083063 Iustin Pop

1837 098c0958 Michael Hanselmann
  """
1838 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1839 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1840 a8083063 Iustin Pop
1841 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1842 a8083063 Iustin Pop
1843 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1844 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1845 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1846 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1847 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1848 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1849 a8083063 Iustin Pop
1850 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1851 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1852 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
1853 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
1854 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1855 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
1856 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1857 66f93869 Manuel Franceschini
1858 95268cc3 Iustin Pop
  nic_total = 0
1859 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1860 95268cc3 Iustin Pop
    nic_total += 1
1861 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1862 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1863 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1864 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1865 38206f3c Iustin Pop
               '%s' % nic.bridge)
1866 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1867 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1868 a8083063 Iustin Pop
1869 726d7d68 Iustin Pop
  disk_total = 0
1870 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1871 19d7f90a Guido Trotter
    if disk:
1872 726d7d68 Iustin Pop
      disk_total += 1
1873 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1874 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
1875 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1876 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
1877 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1878 19d7f90a Guido Trotter
                 ('%d' % disk.size))
1879 a8083063 Iustin Pop
1880 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1881 a8083063 Iustin Pop
1882 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1883 726d7d68 Iustin Pop
                  data=config.Dumps())
1884 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1885 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1886 a8083063 Iustin Pop
1887 9b201a0d Iustin Pop
  return True, None
1888 a8083063 Iustin Pop
1889 a8083063 Iustin Pop
1890 a8083063 Iustin Pop
def ExportInfo(dest):
1891 a8083063 Iustin Pop
  """Get export configuration information.
1892 a8083063 Iustin Pop

1893 10c2650b Iustin Pop
  @type dest: str
1894 10c2650b Iustin Pop
  @param dest: directory containing the export
1895 a8083063 Iustin Pop

1896 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
1897 10c2650b Iustin Pop
  @return: a serializable config file containing the
1898 10c2650b Iustin Pop
      export info
1899 a8083063 Iustin Pop

1900 a8083063 Iustin Pop
  """
1901 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1902 a8083063 Iustin Pop
1903 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1904 a8083063 Iustin Pop
  config.read(cff)
1905 a8083063 Iustin Pop
1906 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1907 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1908 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
1909 a8083063 Iustin Pop
1910 3eccac06 Iustin Pop
  return True, config.Dumps()
1911 a8083063 Iustin Pop
1912 a8083063 Iustin Pop
1913 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1914 a8083063 Iustin Pop
  """Import an os image into an instance.
1915 a8083063 Iustin Pop

1916 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1917 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
1918 6c0af70e Guido Trotter
  @type src_node: string
1919 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
1920 6c0af70e Guido Trotter
  @type src_images: list of string
1921 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
1922 6c0af70e Guido Trotter
  @rtype: list of boolean
1923 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
1924 a8083063 Iustin Pop

1925 a8083063 Iustin Pop
  """
1926 6c0af70e Guido Trotter
  import_env = OSEnvironment(instance)
1927 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1928 a8083063 Iustin Pop
  import_script = inst_os.import_script
1929 a8083063 Iustin Pop
1930 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1931 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1932 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1933 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1934 a8083063 Iustin Pop
1935 a8083063 Iustin Pop
  comprcmd = "gunzip"
1936 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1937 d868edb4 Iustin Pop
                               import_script, logfile)
1938 a8083063 Iustin Pop
1939 6c0af70e Guido Trotter
  final_result = []
1940 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
1941 6c0af70e Guido Trotter
    if image:
1942 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
1943 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1944 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
1945 6c0af70e Guido Trotter
                                                       destcmd)
1946 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1947 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1948 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
1949 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
1950 6c0af70e Guido Trotter
      if result.failed:
1951 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
1952 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
1953 726d7d68 Iustin Pop
                      result.output)
1954 944bf548 Iustin Pop
        final_result.append("error importing disk %d: %s, %s" %
1955 944bf548 Iustin Pop
                            (idx, result.fail_reason, result.output[-100]))
1956 a8083063 Iustin Pop
1957 944bf548 Iustin Pop
  if final_result:
1958 944bf548 Iustin Pop
    return False, "; ".join(final_result)
1959 944bf548 Iustin Pop
  return True, None
1960 a8083063 Iustin Pop
1961 a8083063 Iustin Pop
1962 a8083063 Iustin Pop
def ListExports():
1963 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1964 098c0958 Michael Hanselmann

1965 10c2650b Iustin Pop
  @rtype: list
1966 10c2650b Iustin Pop
  @return: list of the exports
1967 10c2650b Iustin Pop

1968 a8083063 Iustin Pop
  """
1969 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1970 1b7bfbb7 Iustin Pop
    return True, utils.ListVisibleFiles(constants.EXPORT_DIR)
1971 a8083063 Iustin Pop
  else:
1972 1b7bfbb7 Iustin Pop
    return False, "No exports directory"
1973 a8083063 Iustin Pop
1974 a8083063 Iustin Pop
1975 a8083063 Iustin Pop
def RemoveExport(export):
1976 a8083063 Iustin Pop
  """Remove an existing export from the node.
1977 a8083063 Iustin Pop

1978 10c2650b Iustin Pop
  @type export: str
1979 10c2650b Iustin Pop
  @param export: the name of the export to remove
1980 10c2650b Iustin Pop
  @rtype: boolean
1981 10c2650b Iustin Pop
  @return: the success of the operation
1982 a8083063 Iustin Pop

1983 098c0958 Michael Hanselmann
  """
1984 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1985 a8083063 Iustin Pop
1986 35fbcd11 Iustin Pop
  try:
1987 35fbcd11 Iustin Pop
    shutil.rmtree(target)
1988 35fbcd11 Iustin Pop
  except EnvironmentError, err:
1989 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
1990 a8083063 Iustin Pop
1991 35fbcd11 Iustin Pop
  return True, None
1992 a8083063 Iustin Pop
1993 a8083063 Iustin Pop
1994 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
1995 f3e513ad Iustin Pop
  """Rename a list of block devices.
1996 f3e513ad Iustin Pop

1997 10c2650b Iustin Pop
  @type devlist: list of tuples
1998 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
1999 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2000 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2001 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2002 10c2650b Iustin Pop
      rename it to
2003 10c2650b Iustin Pop
  @rtype: boolean
2004 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2005 f3e513ad Iustin Pop

2006 f3e513ad Iustin Pop
  """
2007 6b5e3f70 Iustin Pop
  msgs = []
2008 f3e513ad Iustin Pop
  result = True
2009 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2010 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2011 f3e513ad Iustin Pop
    if dev is None:
2012 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2013 f3e513ad Iustin Pop
      result = False
2014 f3e513ad Iustin Pop
      continue
2015 f3e513ad Iustin Pop
    try:
2016 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2017 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2018 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2019 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2020 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2021 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2022 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2023 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2024 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2025 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2026 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2027 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2028 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2029 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2030 f3e513ad Iustin Pop
      result = False
2031 6b5e3f70 Iustin Pop
  return (result, "; ".join(msgs))
2032 f3e513ad Iustin Pop
2033 f3e513ad Iustin Pop
2034 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2035 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2036 778b75bb Manuel Franceschini

2037 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2038 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2039 778b75bb Manuel Franceschini
  directory are allowed.
2040 778b75bb Manuel Franceschini

2041 b1206984 Iustin Pop
  @type file_storage_dir: str
2042 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2043 d61cbe76 Iustin Pop

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

2046 778b75bb Manuel Franceschini
  """
2047 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2048 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2049 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2050 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2051 778b75bb Manuel Franceschini
      base_file_storage_dir):
2052 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
2053 18682bca Iustin Pop
                  " storage directory '%s'",
2054 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
2055 778b75bb Manuel Franceschini
    return None
2056 778b75bb Manuel Franceschini
  return file_storage_dir
2057 778b75bb Manuel Franceschini
2058 778b75bb Manuel Franceschini
2059 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2060 778b75bb Manuel Franceschini
  """Create file storage directory.
2061 778b75bb Manuel Franceschini

2062 b1206984 Iustin Pop
  @type file_storage_dir: str
2063 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2064 778b75bb Manuel Franceschini

2065 b1206984 Iustin Pop
  @rtype: tuple
2066 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2067 b1206984 Iustin Pop
      creation was successful or not
2068 778b75bb Manuel Franceschini

2069 778b75bb Manuel Franceschini
  """
2070 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2071 778b75bb Manuel Franceschini
  result = True,
2072 778b75bb Manuel Franceschini
  if not file_storage_dir:
2073 778b75bb Manuel Franceschini
    result = False,
2074 778b75bb Manuel Franceschini
  else:
2075 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2076 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2077 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2078 778b75bb Manuel Franceschini
        result = False,
2079 778b75bb Manuel Franceschini
    else:
2080 778b75bb Manuel Franceschini
      try:
2081 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
2082 778b75bb Manuel Franceschini
      except OSError, err:
2083 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
2084 18682bca Iustin Pop
                      file_storage_dir, err)
2085 778b75bb Manuel Franceschini
        result = False,
2086 778b75bb Manuel Franceschini
  return result
2087 778b75bb Manuel Franceschini
2088 778b75bb Manuel Franceschini
2089 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2090 778b75bb Manuel Franceschini
  """Remove file storage directory.
2091 778b75bb Manuel Franceschini

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

2094 10c2650b Iustin Pop
  @type file_storage_dir: str
2095 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2096 10c2650b Iustin Pop
  @rtype: tuple (success,)
2097 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2098 10c2650b Iustin Pop
      whether the operation was successfull
2099 778b75bb Manuel Franceschini

2100 778b75bb Manuel Franceschini
  """
2101 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2102 778b75bb Manuel Franceschini
  result = True,
2103 778b75bb Manuel Franceschini
  if not file_storage_dir:
2104 778b75bb Manuel Franceschini
    result = False,
2105 778b75bb Manuel Franceschini
  else:
2106 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2107 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2108 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2109 778b75bb Manuel Franceschini
        result = False,
2110 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
2111 778b75bb Manuel Franceschini
      try:
2112 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
2113 778b75bb Manuel Franceschini
      except OSError, err:
2114 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
2115 18682bca Iustin Pop
                          file_storage_dir)
2116 778b75bb Manuel Franceschini
        result = False,
2117 778b75bb Manuel Franceschini
  return result
2118 778b75bb Manuel Franceschini
2119 778b75bb Manuel Franceschini
2120 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2121 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2122 778b75bb Manuel Franceschini

2123 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2124 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2125 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2126 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2127 10c2650b Iustin Pop
  @rtype: tuple (success,)
2128 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2129 10c2650b Iustin Pop
      whether the operation was successful
2130 778b75bb Manuel Franceschini

2131 778b75bb Manuel Franceschini
  """
2132 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2133 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2134 778b75bb Manuel Franceschini
  result = True,
2135 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
2136 778b75bb Manuel Franceschini
    result = False,
2137 778b75bb Manuel Franceschini
  else:
2138 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
2139 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
2140 778b75bb Manuel Franceschini
        try:
2141 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
2142 778b75bb Manuel Franceschini
        except OSError, err:
2143 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
2144 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
2145 778b75bb Manuel Franceschini
          result =  False,
2146 778b75bb Manuel Franceschini
      else:
2147 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
2148 778b75bb Manuel Franceschini
        result = False,
2149 778b75bb Manuel Franceschini
    else:
2150 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
2151 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
2152 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
2153 778b75bb Manuel Franceschini
        result = False,
2154 778b75bb Manuel Franceschini
  return result
2155 778b75bb Manuel Franceschini
2156 778b75bb Manuel Franceschini
2157 dc31eae3 Michael Hanselmann
def _IsJobQueueFile(file_name):
2158 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2159 ca52cdeb Michael Hanselmann

2160 10c2650b Iustin Pop
  @type file_name: str
2161 10c2650b Iustin Pop
  @param file_name: the file name we should check
2162 10c2650b Iustin Pop
  @rtype: boolean
2163 10c2650b Iustin Pop
  @return: whether the file is under the queue directory
2164 10c2650b Iustin Pop

2165 ca52cdeb Michael Hanselmann
  """
2166 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2167 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2168 dc31eae3 Michael Hanselmann
2169 dc31eae3 Michael Hanselmann
  if not result:
2170 ca52cdeb Michael Hanselmann
    logging.error("'%s' is not a file in the queue directory",
2171 ca52cdeb Michael Hanselmann
                  file_name)
2172 dc31eae3 Michael Hanselmann
2173 dc31eae3 Michael Hanselmann
  return result
2174 dc31eae3 Michael Hanselmann
2175 dc31eae3 Michael Hanselmann
2176 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2177 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2178 dc31eae3 Michael Hanselmann

2179 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2180 10c2650b Iustin Pop
  checking.
2181 10c2650b Iustin Pop

2182 10c2650b Iustin Pop
  @type file_name: str
2183 10c2650b Iustin Pop
  @param file_name: the job file name
2184 10c2650b Iustin Pop
  @type content: str
2185 10c2650b Iustin Pop
  @param content: the new job contents
2186 10c2650b Iustin Pop
  @rtype: boolean
2187 10c2650b Iustin Pop
  @return: the success of the operation
2188 10c2650b Iustin Pop

2189 dc31eae3 Michael Hanselmann
  """
2190 dc31eae3 Michael Hanselmann
  if not _IsJobQueueFile(file_name):
2191 ca52cdeb Michael Hanselmann
    return False
2192 ca52cdeb Michael Hanselmann
2193 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2194 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2195 ca52cdeb Michael Hanselmann
2196 ca52cdeb Michael Hanselmann
  return True
2197 ca52cdeb Michael Hanselmann
2198 ca52cdeb Michael Hanselmann
2199 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2200 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2201 af5ebcb1 Michael Hanselmann

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

2204 10c2650b Iustin Pop
  @type old: str
2205 10c2650b Iustin Pop
  @param old: the old (actual) file name
2206 10c2650b Iustin Pop
  @type new: str
2207 10c2650b Iustin Pop
  @param new: the desired file name
2208 10c2650b Iustin Pop
  @rtype: boolean
2209 10c2650b Iustin Pop
  @return: the success of the operation
2210 10c2650b Iustin Pop

2211 af5ebcb1 Michael Hanselmann
  """
2212 af5ebcb1 Michael Hanselmann
  if not (_IsJobQueueFile(old) and _IsJobQueueFile(new)):
2213 af5ebcb1 Michael Hanselmann
    return False
2214 af5ebcb1 Michael Hanselmann
2215 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2216 af5ebcb1 Michael Hanselmann
2217 af5ebcb1 Michael Hanselmann
  return True
2218 af5ebcb1 Michael Hanselmann
2219 af5ebcb1 Michael Hanselmann
2220 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2221 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2222 5d672980 Iustin Pop

2223 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2224 5d672980 Iustin Pop

2225 10c2650b Iustin Pop
  @type drain_flag: boolean
2226 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2227 10c2650b Iustin Pop
  @rtype: boolean
2228 10c2650b Iustin Pop
  @return: always True
2229 10c2650b Iustin Pop
  @warning: the function always returns True
2230 5d672980 Iustin Pop

2231 5d672980 Iustin Pop
  """
2232 5d672980 Iustin Pop
  if drain_flag:
2233 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2234 5d672980 Iustin Pop
  else:
2235 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2236 5d672980 Iustin Pop
2237 5d672980 Iustin Pop
  return True
2238 5d672980 Iustin Pop
2239 5d672980 Iustin Pop
2240 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2241 d61cbe76 Iustin Pop
  """Closes the given block devices.
2242 d61cbe76 Iustin Pop

2243 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2244 10c2650b Iustin Pop
  DRBD).
2245 10c2650b Iustin Pop

2246 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2247 b2e7666a Iustin Pop
      of this instance will be removed
2248 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2249 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2250 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2251 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2252 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2253 10c2650b Iustin Pop
      which will contain the error details in case we
2254 10c2650b Iustin Pop
      failed
2255 d61cbe76 Iustin Pop

2256 d61cbe76 Iustin Pop
  """
2257 d61cbe76 Iustin Pop
  bdevs = []
2258 d61cbe76 Iustin Pop
  for cf in disks:
2259 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2260 d61cbe76 Iustin Pop
    if rd is None:
2261 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2262 d61cbe76 Iustin Pop
    bdevs.append(rd)
2263 d61cbe76 Iustin Pop
2264 d61cbe76 Iustin Pop
  msg = []
2265 d61cbe76 Iustin Pop
  for rd in bdevs:
2266 d61cbe76 Iustin Pop
    try:
2267 d61cbe76 Iustin Pop
      rd.Close()
2268 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2269 d61cbe76 Iustin Pop
      msg.append(str(err))
2270 d61cbe76 Iustin Pop
  if msg:
2271 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
2272 d61cbe76 Iustin Pop
  else:
2273 b2e7666a Iustin Pop
    if instance_name:
2274 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2275 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
2276 d61cbe76 Iustin Pop
2277 d61cbe76 Iustin Pop
2278 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2279 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2280 6217e295 Iustin Pop

2281 6217e295 Iustin Pop
  @type hvname: string
2282 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2283 6217e295 Iustin Pop
  @type hvparams: dict
2284 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2285 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2286 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2287 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2288 10c2650b Iustin Pop
      which will contain the error details in case we
2289 10c2650b Iustin Pop
      failed
2290 6217e295 Iustin Pop

2291 6217e295 Iustin Pop
  """
2292 6217e295 Iustin Pop
  try:
2293 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2294 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2295 6217e295 Iustin Pop
    return (True, "Validation passed")
2296 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2297 6217e295 Iustin Pop
    return (False, str(err))
2298 6217e295 Iustin Pop
2299 6217e295 Iustin Pop
2300 56aa9fd5 Iustin Pop
def DemoteFromMC():
2301 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2302 56aa9fd5 Iustin Pop

2303 56aa9fd5 Iustin Pop
  """
2304 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2305 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2306 56aa9fd5 Iustin Pop
  if master == myself:
2307 56aa9fd5 Iustin Pop
    return (False, "ssconf status shows I'm the master node, will not demote")
2308 56aa9fd5 Iustin Pop
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2309 56aa9fd5 Iustin Pop
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2310 56aa9fd5 Iustin Pop
    return (False, "The master daemon is running, will not demote")
2311 56aa9fd5 Iustin Pop
  try:
2312 56aa9fd5 Iustin Pop
    utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2313 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2314 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2315 56aa9fd5 Iustin Pop
      return (False, "Error while backing up cluster file: %s" % str(err))
2316 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2317 56aa9fd5 Iustin Pop
  return (True, "Done")
2318 56aa9fd5 Iustin Pop
2319 56aa9fd5 Iustin Pop
2320 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2321 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2322 6b93ec9d Iustin Pop

2323 6b93ec9d Iustin Pop
  """
2324 6b93ec9d Iustin Pop
  # set the correct physical ID
2325 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2326 6b93ec9d Iustin Pop
  for cf in disks:
2327 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2328 6b93ec9d Iustin Pop
2329 6b93ec9d Iustin Pop
  bdevs = []
2330 6b93ec9d Iustin Pop
2331 6b93ec9d Iustin Pop
  for cf in disks:
2332 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2333 6b93ec9d Iustin Pop
    if rd is None:
2334 6b93ec9d Iustin Pop
      return (False, "Can't find device %s" % cf)
2335 6b93ec9d Iustin Pop
    bdevs.append(rd)
2336 6b93ec9d Iustin Pop
  return (True, bdevs)
2337 6b93ec9d Iustin Pop
2338 6b93ec9d Iustin Pop
2339 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2340 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2341 6b93ec9d Iustin Pop

2342 6b93ec9d Iustin Pop
  """
2343 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2344 6b93ec9d Iustin Pop
  if not status:
2345 6b93ec9d Iustin Pop
    return status, bdevs
2346 6b93ec9d Iustin Pop
2347 6b93ec9d Iustin Pop
  # disconnect disks
2348 6b93ec9d Iustin Pop
  for rd in bdevs:
2349 6b93ec9d Iustin Pop
    try:
2350 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2351 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2352 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
2353 2cc6781a Iustin Pop
            err, exc=True)
2354 6b93ec9d Iustin Pop
  return (True, "All disks are now disconnected")
2355 6b93ec9d Iustin Pop
2356 6b93ec9d Iustin Pop
2357 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2358 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2359 6b93ec9d Iustin Pop

2360 6b93ec9d Iustin Pop
  """
2361 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2362 6b93ec9d Iustin Pop
  if not status:
2363 6b93ec9d Iustin Pop
    return status, bdevs
2364 6b93ec9d Iustin Pop
2365 6b93ec9d Iustin Pop
  if multimaster:
2366 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2367 6b93ec9d Iustin Pop
      try:
2368 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2369 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2370 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
2371 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2372 6b93ec9d Iustin Pop
  # needed primary mode
2373 6b93ec9d Iustin Pop
  for rd in bdevs:
2374 6b93ec9d Iustin Pop
    try:
2375 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2376 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2377 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
2378 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2379 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2380 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2381 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2382 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2383 6b93ec9d Iustin Pop
  RECONNECT_TIMEOUT = 2 * 60
2384 6b93ec9d Iustin Pop
  sleep_time = 0.100 # start with 100 miliseconds
2385 6b93ec9d Iustin Pop
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2386 6b93ec9d Iustin Pop
  while time.time() < timeout_limit:
2387 6b93ec9d Iustin Pop
    all_connected = True
2388 6b93ec9d Iustin Pop
    for rd in bdevs:
2389 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2390 6b93ec9d Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2391 6b93ec9d Iustin Pop
        all_connected = False
2392 6b93ec9d Iustin Pop
      if stats.is_standalone:
2393 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2394 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2395 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2396 6b93ec9d Iustin Pop
        try:
2397 6b93ec9d Iustin Pop
          rd.ReAttachNet(multimaster)
2398 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2399 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
2400 6b93ec9d Iustin Pop
    if all_connected:
2401 6b93ec9d Iustin Pop
      break
2402 6b93ec9d Iustin Pop
    time.sleep(sleep_time)
2403 6b93ec9d Iustin Pop
    sleep_time = min(5, sleep_time * 1.5)
2404 6b93ec9d Iustin Pop
  if not all_connected:
2405 6b93ec9d Iustin Pop
    return (False, "Timeout in disk reconnecting")
2406 6b93ec9d Iustin Pop
  if multimaster:
2407 6b93ec9d Iustin Pop
    # change to primary mode
2408 6b93ec9d Iustin Pop
    for rd in bdevs:
2409 d3da87b8 Iustin Pop
      try:
2410 d3da87b8 Iustin Pop
        rd.Open()
2411 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
2412 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
2413 6b93ec9d Iustin Pop
  if multimaster:
2414 6b93ec9d Iustin Pop
    msg = "multi-master and primary"
2415 6b93ec9d Iustin Pop
  else:
2416 6b93ec9d Iustin Pop
    msg = "single-master"
2417 6b93ec9d Iustin Pop
  return (True, "Disks are now configured as %s" % msg)
2418 6b93ec9d Iustin Pop
2419 6b93ec9d Iustin Pop
2420 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2421 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2422 6b93ec9d Iustin Pop

2423 6b93ec9d Iustin Pop
  """
2424 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2425 6b93ec9d Iustin Pop
  if not status:
2426 6b93ec9d Iustin Pop
    return status, bdevs
2427 6b93ec9d Iustin Pop
2428 6b93ec9d Iustin Pop
  min_resync = 100
2429 6b93ec9d Iustin Pop
  alldone = True
2430 6b93ec9d Iustin Pop
  failure = False
2431 6b93ec9d Iustin Pop
  for rd in bdevs:
2432 6b93ec9d Iustin Pop
    stats = rd.GetProcStatus()
2433 6b93ec9d Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2434 6b93ec9d Iustin Pop
      failure = True
2435 6b93ec9d Iustin Pop
      break
2436 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2437 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2438 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2439 6b93ec9d Iustin Pop
  return (not failure, (alldone, min_resync))
2440 6b93ec9d Iustin Pop
2441 6b93ec9d Iustin Pop
2442 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
2443 f5118ade Iustin Pop
  """Hard-powercycle the node.
2444 f5118ade Iustin Pop

2445 f5118ade Iustin Pop
  Because we need to return first, and schedule the powercycle in the
2446 f5118ade Iustin Pop
  background, we won't be able to report failures nicely.
2447 f5118ade Iustin Pop

2448 f5118ade Iustin Pop
  """
2449 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2450 f5118ade Iustin Pop
  try:
2451 f5118ade Iustin Pop
    pid = os.fork()
2452 f5118ade Iustin Pop
  except OSError, err:
2453 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
2454 f5118ade Iustin Pop
    pid = 0
2455 f5118ade Iustin Pop
  if pid > 0:
2456 f5118ade Iustin Pop
    return (True, "Reboot scheduled in 5 seconds")
2457 f5118ade Iustin Pop
  time.sleep(5)
2458 f5118ade Iustin Pop
  hyper.PowercycleNode()
2459 f5118ade Iustin Pop
2460 f5118ade Iustin Pop
2461 a8083063 Iustin Pop
class HooksRunner(object):
2462 a8083063 Iustin Pop
  """Hook runner.
2463 a8083063 Iustin Pop

2464 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2465 10c2650b Iustin Pop
  on the master side.
2466 a8083063 Iustin Pop

2467 a8083063 Iustin Pop
  """
2468 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2469 a8083063 Iustin Pop
2470 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2471 a8083063 Iustin Pop
    """Constructor for hooks runner.
2472 a8083063 Iustin Pop

2473 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2474 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2475 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2476 a8083063 Iustin Pop

2477 a8083063 Iustin Pop
    """
2478 a8083063 Iustin Pop
    if hooks_base_dir is None:
2479 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2480 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2481 a8083063 Iustin Pop
2482 a8083063 Iustin Pop
  @staticmethod
2483 a8083063 Iustin Pop
  def ExecHook(script, env):
2484 a8083063 Iustin Pop
    """Exec one hook script.
2485 a8083063 Iustin Pop

2486 10c2650b Iustin Pop
    @type script: str
2487 10c2650b Iustin Pop
    @param script: the full path to the script
2488 10c2650b Iustin Pop
    @type env: dict
2489 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2490 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2491 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2492 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2493 10c2650b Iustin Pop
        which will contain the error details in case we
2494 10c2650b Iustin Pop
        failed
2495 a8083063 Iustin Pop

2496 a8083063 Iustin Pop
    """
2497 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2498 a8083063 Iustin Pop
    fdstdin = None
2499 a8083063 Iustin Pop
    try:
2500 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2501 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2502 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2503 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2504 a8083063 Iustin Pop
      output = ""
2505 a8083063 Iustin Pop
      try:
2506 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2507 a8083063 Iustin Pop
        child.stdout.close()
2508 a8083063 Iustin Pop
      except EnvironmentError, err:
2509 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2510 a8083063 Iustin Pop
2511 a8083063 Iustin Pop
      while True:
2512 a8083063 Iustin Pop
        try:
2513 a8083063 Iustin Pop
          result = child.wait()
2514 a8083063 Iustin Pop
          break
2515 a8083063 Iustin Pop
        except EnvironmentError, err:
2516 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2517 a8083063 Iustin Pop
            continue
2518 a8083063 Iustin Pop
          raise
2519 a8083063 Iustin Pop
    finally:
2520 a8083063 Iustin Pop
      # try not to leak fds
2521 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2522 a8083063 Iustin Pop
        if fd is not None:
2523 a8083063 Iustin Pop
          try:
2524 a8083063 Iustin Pop
            fd.close()
2525 a8083063 Iustin Pop
          except EnvironmentError, err:
2526 a8083063 Iustin Pop
            # just log the error
2527 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2528 a8083063 Iustin Pop
            pass
2529 a8083063 Iustin Pop
2530 26f15862 Iustin Pop
    return result == 0, utils.SafeEncode(output.strip())
2531 a8083063 Iustin Pop
2532 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2533 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2534 a8083063 Iustin Pop

2535 10c2650b Iustin Pop
    @type hpath: str
2536 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2537 10c2650b Iustin Pop
        holds the scripts
2538 10c2650b Iustin Pop
    @type phase: str
2539 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2540 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2541 10c2650b Iustin Pop
    @type env: dict
2542 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2543 10c2650b Iustin Pop
    @rtype: list
2544 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2545 10c2650b Iustin Pop
      - script path
2546 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2547 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2548 10c2650b Iustin Pop
      - output of the script
2549 10c2650b Iustin Pop

2550 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2551 10c2650b Iustin Pop
        parameters
2552 a8083063 Iustin Pop

2553 a8083063 Iustin Pop
    """
2554 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2555 a8083063 Iustin Pop
      suffix = "pre"
2556 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2557 a8083063 Iustin Pop
      suffix = "post"
2558 a8083063 Iustin Pop
    else:
2559 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
2560 a8083063 Iustin Pop
    rr = []
2561 a8083063 Iustin Pop
2562 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2563 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2564 a8083063 Iustin Pop
    try:
2565 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2566 a8083063 Iustin Pop
    except OSError, err:
2567 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2568 a8083063 Iustin Pop
      return rr
2569 a8083063 Iustin Pop
2570 a8083063 Iustin Pop
    # we use the standard python sort order,
2571 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2572 a8083063 Iustin Pop
    dir_contents.sort()
2573 a8083063 Iustin Pop
    for relname in dir_contents:
2574 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2575 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2576 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2577 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2578 a8083063 Iustin Pop
        output = ""
2579 a8083063 Iustin Pop
      else:
2580 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2581 a8083063 Iustin Pop
        if not result:
2582 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2583 a8083063 Iustin Pop
        else:
2584 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2585 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2586 a8083063 Iustin Pop
2587 a8083063 Iustin Pop
    return rr
2588 3f78eef2 Iustin Pop
2589 3f78eef2 Iustin Pop
2590 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2591 8d528b7c Iustin Pop
  """IAllocator runner.
2592 8d528b7c Iustin Pop

2593 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2594 8d528b7c Iustin Pop
  the master side.
2595 8d528b7c Iustin Pop

2596 8d528b7c Iustin Pop
  """
2597 8d528b7c Iustin Pop
  def Run(self, name, idata):
2598 8d528b7c Iustin Pop
    """Run an iallocator script.
2599 8d528b7c Iustin Pop

2600 10c2650b Iustin Pop
    @type name: str
2601 10c2650b Iustin Pop
    @param name: the iallocator script name
2602 10c2650b Iustin Pop
    @type idata: str
2603 10c2650b Iustin Pop
    @param idata: the allocator input data
2604 10c2650b Iustin Pop

2605 10c2650b Iustin Pop
    @rtype: tuple
2606 10c2650b Iustin Pop
    @return: four element tuple of:
2607 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
2608 8d528b7c Iustin Pop
       - stdout
2609 8d528b7c Iustin Pop
       - stderr
2610 10c2650b Iustin Pop
       - fail reason (as from L{utils.RunResult})
2611 8d528b7c Iustin Pop

2612 8d528b7c Iustin Pop
    """
2613 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2614 8d528b7c Iustin Pop
                                  os.path.isfile)
2615 8d528b7c Iustin Pop
    if alloc_script is None:
2616 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
2617 8d528b7c Iustin Pop
2618 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2619 8d528b7c Iustin Pop
    try:
2620 8d528b7c Iustin Pop
      os.write(fd, idata)
2621 8d528b7c Iustin Pop
      os.close(fd)
2622 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2623 8d528b7c Iustin Pop
      if result.failed:
2624 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
2625 8d528b7c Iustin Pop
                result.fail_reason)
2626 8d528b7c Iustin Pop
    finally:
2627 8d528b7c Iustin Pop
      os.unlink(fin_name)
2628 8d528b7c Iustin Pop
2629 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
2630 8d528b7c Iustin Pop
2631 8d528b7c Iustin Pop
2632 3f78eef2 Iustin Pop
class DevCacheManager(object):
2633 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2634 3f78eef2 Iustin Pop

2635 3f78eef2 Iustin Pop
  """
2636 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2637 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2638 3f78eef2 Iustin Pop
2639 3f78eef2 Iustin Pop
  @classmethod
2640 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2641 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2642 3f78eef2 Iustin Pop

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

2646 10c2650b Iustin Pop
    @type dev_path: str
2647 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2648 10c2650b Iustin Pop
    @rtype: str
2649 10c2650b Iustin Pop
    @return: the converted path name
2650 3f78eef2 Iustin Pop

2651 3f78eef2 Iustin Pop
    """
2652 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2653 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2654 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2655 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2656 3f78eef2 Iustin Pop
    return fpath
2657 3f78eef2 Iustin Pop
2658 3f78eef2 Iustin Pop
  @classmethod
2659 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2660 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2661 3f78eef2 Iustin Pop

2662 10c2650b Iustin Pop
    @type dev_path: str
2663 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2664 10c2650b Iustin Pop
    @type owner: str
2665 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2666 10c2650b Iustin Pop
    @type on_primary: bool
2667 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2668 10c2650b Iustin Pop
        node nor not
2669 10c2650b Iustin Pop
    @type iv_name: str
2670 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2671 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2672 10c2650b Iustin Pop

2673 10c2650b Iustin Pop
    @rtype: None
2674 10c2650b Iustin Pop

2675 3f78eef2 Iustin Pop
    """
2676 cf5a8306 Iustin Pop
    if dev_path is None:
2677 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2678 cf5a8306 Iustin Pop
      return
2679 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2680 3f78eef2 Iustin Pop
    if on_primary:
2681 3f78eef2 Iustin Pop
      state = "primary"
2682 3f78eef2 Iustin Pop
    else:
2683 3f78eef2 Iustin Pop
      state = "secondary"
2684 3f78eef2 Iustin Pop
    if iv_name is None:
2685 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2686 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2687 3f78eef2 Iustin Pop
    try:
2688 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2689 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2690 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
2691 3f78eef2 Iustin Pop
2692 3f78eef2 Iustin Pop
  @classmethod
2693 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2694 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2695 3f78eef2 Iustin Pop

2696 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2697 10c2650b Iustin Pop
    path name and logging.
2698 10c2650b Iustin Pop

2699 10c2650b Iustin Pop
    @type dev_path: str
2700 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2701 10c2650b Iustin Pop

2702 10c2650b Iustin Pop
    @rtype: None
2703 10c2650b Iustin Pop

2704 3f78eef2 Iustin Pop
    """
2705 cf5a8306 Iustin Pop
    if dev_path is None:
2706 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2707 cf5a8306 Iustin Pop
      return
2708 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2709 3f78eef2 Iustin Pop
    try:
2710 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2711 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2712 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)