Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 3374afa9

History | View | Annotate | Download (79.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 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
72 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
73 afdc3985 Iustin Pop
      logging.exception(msg)
74 afdc3985 Iustin Pop
    else:
75 afdc3985 Iustin Pop
      logging.error(msg)
76 2cc6781a Iustin Pop
  raise RPCFail(msg)
77 2cc6781a Iustin Pop
78 2cc6781a Iustin Pop
79 c657dcc9 Michael Hanselmann
def _GetConfig():
80 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
81 10c2650b Iustin Pop

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

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

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

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

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

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

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

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

151 c8457ce7 Iustin Pop
  @rtype: tuple
152 c8457ce7 Iustin Pop
  @return: True, None
153 24fc781f Michael Hanselmann

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

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

165 bd1e4562 Iustin Pop
  @rtype: tuple
166 c26a6bd2 Iustin Pop
  @return: master_netdev, master_ip, master_name
167 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
168 b1b6ea87 Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

590 e69d05fd Iustin Pop
  @type hypervisor_list: list
591 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
592 e69d05fd Iustin Pop

593 e69d05fd Iustin Pop
  @rtype: list
594 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
595 10c2650b Iustin Pop
    - instance1.example.com
596 10c2650b Iustin Pop
    - instance2.example.com
597 a8083063 Iustin Pop

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

614 e69d05fd Iustin Pop
  @type instance: string
615 e69d05fd Iustin Pop
  @param instance: the instance name
616 e69d05fd Iustin Pop
  @type hname: string
617 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
618 a8083063 Iustin Pop

619 e69d05fd Iustin Pop
  @rtype: dict
620 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
621 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
622 e69d05fd Iustin Pop
      - state: xen state of instance (string)
623 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
624 a8083063 Iustin Pop

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

640 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
641 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
642 56e7640c Iustin Pop

643 56e7640c Iustin Pop
  @rtype: tuple
644 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
645 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
646 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
647 56e7640c Iustin Pop

648 56e7640c Iustin Pop
  """
649 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
650 afdc3985 Iustin Pop
  iname = instance.name
651 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
652 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
653 56e7640c Iustin Pop
654 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
655 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
656 56e7640c Iustin Pop
    if not os.path.islink(link_name):
657 afdc3985 Iustin Pop
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
658 56e7640c Iustin Pop
659 56e7640c Iustin Pop
660 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
661 a8083063 Iustin Pop
  """Gather data about all instances.
662 a8083063 Iustin Pop

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

667 e69d05fd Iustin Pop
  @type hypervisor_list: list
668 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
669 e69d05fd Iustin Pop

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

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

706 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
707 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
708 e557bae9 Guido Trotter
  @type reinstall: boolean
709 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
710 c26a6bd2 Iustin Pop
  @rtype: None
711 a8083063 Iustin Pop

712 a8083063 Iustin Pop
  """
713 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
714 255dcebd Iustin Pop
715 58f6e5ca Guido Trotter
  create_env = OSEnvironment(instance)
716 e557bae9 Guido Trotter
  if reinstall:
717 e557bae9 Guido Trotter
    create_env['INSTANCE_REINSTALL'] = "1"
718 a8083063 Iustin Pop
719 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
720 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
721 decd5f45 Iustin Pop
722 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
723 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
724 decd5f45 Iustin Pop
  if result.failed:
725 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
726 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
727 18682bca Iustin Pop
                  result.output)
728 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
729 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
730 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
731 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
732 decd5f45 Iustin Pop
733 decd5f45 Iustin Pop
734 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
735 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
736 decd5f45 Iustin Pop

737 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
738 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
739 d15a9ad3 Guido Trotter
  @type old_name: string
740 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
741 10c2650b Iustin Pop
  @rtype: boolean
742 10c2650b Iustin Pop
  @return: the success of the operation
743 decd5f45 Iustin Pop

744 decd5f45 Iustin Pop
  """
745 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
746 decd5f45 Iustin Pop
747 ff38b6c0 Guido Trotter
  rename_env = OSEnvironment(instance)
748 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
749 decd5f45 Iustin Pop
750 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
751 decd5f45 Iustin Pop
                                           old_name,
752 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
753 a8083063 Iustin Pop
754 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
755 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
756 a8083063 Iustin Pop
757 a8083063 Iustin Pop
  if result.failed:
758 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
759 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
760 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
761 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
762 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
763 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
764 a8083063 Iustin Pop
765 a8083063 Iustin Pop
766 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
767 a8083063 Iustin Pop
  """Get informations about the volume group.
768 a8083063 Iustin Pop

769 10c2650b Iustin Pop
  @type vg_name: str
770 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
771 10c2650b Iustin Pop
  @rtype: dict
772 10c2650b Iustin Pop
  @return:
773 10c2650b Iustin Pop
    A dictionary with the following keys:
774 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
775 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
776 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
777 a8083063 Iustin Pop

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

781 a8083063 Iustin Pop
  """
782 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
783 f4d377e7 Iustin Pop
784 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
785 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
786 a8083063 Iustin Pop
787 a8083063 Iustin Pop
  if retval.failed:
788 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
789 f4d377e7 Iustin Pop
    return retdic
790 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
791 f4d377e7 Iustin Pop
  if len(valarr) == 3:
792 f4d377e7 Iustin Pop
    try:
793 f4d377e7 Iustin Pop
      retdic = {
794 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
795 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
796 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
797 f4d377e7 Iustin Pop
        }
798 f4d377e7 Iustin Pop
    except ValueError, err:
799 29921401 Iustin Pop
      logging.exception("Fail to parse vgs output: %s", err)
800 f4d377e7 Iustin Pop
  else:
801 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
802 18682bca Iustin Pop
                  " three): %s", str(valarr))
803 a8083063 Iustin Pop
  return retdic
804 a8083063 Iustin Pop
805 a8083063 Iustin Pop
806 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
807 5282084b Iustin Pop
  return os.path.join(constants.DISK_LINKS_DIR,
808 5282084b Iustin Pop
                      "%s:%d" % (instance_name, idx))
809 5282084b Iustin Pop
810 5282084b Iustin Pop
811 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
812 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
813 9332fd8a Iustin Pop

814 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
815 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
816 9332fd8a Iustin Pop

817 9332fd8a Iustin Pop

818 5282084b Iustin Pop
  @param instance_name: the name of the target instance
819 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
820 5282084b Iustin Pop
  @param idx: the disk index
821 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
822 9332fd8a Iustin Pop

823 9332fd8a Iustin Pop
  """
824 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
825 9332fd8a Iustin Pop
  try:
826 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
827 5282084b Iustin Pop
  except OSError, err:
828 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
829 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
830 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
831 9332fd8a Iustin Pop
        os.remove(link_name)
832 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
833 9332fd8a Iustin Pop
    else:
834 9332fd8a Iustin Pop
      raise
835 9332fd8a Iustin Pop
836 9332fd8a Iustin Pop
  return link_name
837 9332fd8a Iustin Pop
838 9332fd8a Iustin Pop
839 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
840 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
841 3c9c571d Iustin Pop

842 3c9c571d Iustin Pop
  """
843 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
844 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
845 5282084b Iustin Pop
    if os.path.islink(link_name):
846 3c9c571d Iustin Pop
      try:
847 03dfa658 Iustin Pop
        os.remove(link_name)
848 03dfa658 Iustin Pop
      except OSError:
849 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
850 3c9c571d Iustin Pop
851 3c9c571d Iustin Pop
852 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
853 a8083063 Iustin Pop
  """Set up an instance's block device(s).
854 a8083063 Iustin Pop

855 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
856 a8083063 Iustin Pop
  devices must be already assembled.
857 a8083063 Iustin Pop

858 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
859 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
860 069cfbf1 Iustin Pop
  @rtype: list
861 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
862 10c2650b Iustin Pop

863 a8083063 Iustin Pop
  """
864 a8083063 Iustin Pop
  block_devices = []
865 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
866 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
867 a8083063 Iustin Pop
    if device is None:
868 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
869 a8083063 Iustin Pop
                                    str(disk))
870 a8083063 Iustin Pop
    device.Open()
871 9332fd8a Iustin Pop
    try:
872 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
873 9332fd8a Iustin Pop
    except OSError, e:
874 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
875 9332fd8a Iustin Pop
                                    e.strerror)
876 9332fd8a Iustin Pop
877 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
878 9332fd8a Iustin Pop
879 a8083063 Iustin Pop
  return block_devices
880 a8083063 Iustin Pop
881 a8083063 Iustin Pop
882 07813a9e Iustin Pop
def StartInstance(instance):
883 a8083063 Iustin Pop
  """Start an instance.
884 a8083063 Iustin Pop

885 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
886 e69d05fd Iustin Pop
  @param instance: the instance object
887 c26a6bd2 Iustin Pop
  @rtype: None
888 a8083063 Iustin Pop

889 098c0958 Michael Hanselmann
  """
890 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
891 a8083063 Iustin Pop
892 a8083063 Iustin Pop
  if instance.name in running_instances:
893 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
894 c26a6bd2 Iustin Pop
    return
895 a8083063 Iustin Pop
896 a8083063 Iustin Pop
  try:
897 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
898 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
899 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
900 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
901 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
902 a8083063 Iustin Pop
  except errors.HypervisorError, err:
903 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
904 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
905 a8083063 Iustin Pop
906 a8083063 Iustin Pop
907 1fae010f Iustin Pop
def InstanceShutdown(instance):
908 a8083063 Iustin Pop
  """Shut an instance down.
909 a8083063 Iustin Pop

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

912 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
913 e69d05fd Iustin Pop
  @param instance: the instance object
914 c26a6bd2 Iustin Pop
  @rtype: None
915 a8083063 Iustin Pop

916 098c0958 Michael Hanselmann
  """
917 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
918 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
919 c26a6bd2 Iustin Pop
  iname = instance.name
920 a8083063 Iustin Pop
921 c26a6bd2 Iustin Pop
  if iname not in running_instances:
922 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
923 c26a6bd2 Iustin Pop
    return
924 a8083063 Iustin Pop
925 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
926 a8083063 Iustin Pop
  try:
927 a8083063 Iustin Pop
    hyper.StopInstance(instance)
928 a8083063 Iustin Pop
  except errors.HypervisorError, err:
929 c26a6bd2 Iustin Pop
    _Fail("Failed to stop instance %s: %s", iname, err)
930 a8083063 Iustin Pop
931 a8083063 Iustin Pop
  # test every 10secs for 2min
932 a8083063 Iustin Pop
933 a8083063 Iustin Pop
  time.sleep(1)
934 a8083063 Iustin Pop
  for dummy in range(11):
935 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
936 a8083063 Iustin Pop
      break
937 a8083063 Iustin Pop
    time.sleep(10)
938 a8083063 Iustin Pop
  else:
939 a8083063 Iustin Pop
    # the shutdown did not succeed
940 c26a6bd2 Iustin Pop
    logging.error("Shutdown of '%s' unsuccessful, using destroy", iname)
941 a8083063 Iustin Pop
942 a8083063 Iustin Pop
    try:
943 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
944 a8083063 Iustin Pop
    except errors.HypervisorError, err:
945 c26a6bd2 Iustin Pop
      _Fail("Failed to force stop instance %s: %s", iname, err)
946 a8083063 Iustin Pop
947 a8083063 Iustin Pop
    time.sleep(1)
948 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
949 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
950 3c9c571d Iustin Pop
951 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
952 a8083063 Iustin Pop
953 a8083063 Iustin Pop
954 07813a9e Iustin Pop
def InstanceReboot(instance, reboot_type):
955 007a2f3e Alexander Schreiber
  """Reboot an instance.
956 007a2f3e Alexander Schreiber

957 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
958 10c2650b Iustin Pop
  @param instance: the instance object to reboot
959 10c2650b Iustin Pop
  @type reboot_type: str
960 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
961 10c2650b Iustin Pop
    constants:
962 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
963 10c2650b Iustin Pop
        instance OS, do not recreate the VM
964 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
965 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
966 10c2650b Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_HARD})
967 10c2650b Iustin Pop
        is not accepted here, since that mode is handled
968 10c2650b Iustin Pop
        differently
969 c26a6bd2 Iustin Pop
  @rtype: None
970 007a2f3e Alexander Schreiber

971 007a2f3e Alexander Schreiber
  """
972 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
973 007a2f3e Alexander Schreiber
974 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
975 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
976 007a2f3e Alexander Schreiber
977 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
978 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
979 007a2f3e Alexander Schreiber
    try:
980 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
981 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
982 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
983 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
984 007a2f3e Alexander Schreiber
    try:
985 c26a6bd2 Iustin Pop
      InstanceShutdown(instance)
986 07813a9e Iustin Pop
      return StartInstance(instance)
987 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
988 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
989 007a2f3e Alexander Schreiber
  else:
990 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
991 007a2f3e Alexander Schreiber
992 007a2f3e Alexander Schreiber
993 6906a9d8 Guido Trotter
def MigrationInfo(instance):
994 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
995 6906a9d8 Guido Trotter

996 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
997 6906a9d8 Guido Trotter
  @param instance: the instance definition
998 6906a9d8 Guido Trotter

999 6906a9d8 Guido Trotter
  """
1000 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1001 cd42d0ad Guido Trotter
  try:
1002 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1003 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1004 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1005 c26a6bd2 Iustin Pop
  return info
1006 6906a9d8 Guido Trotter
1007 6906a9d8 Guido Trotter
1008 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1009 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1010 6906a9d8 Guido Trotter

1011 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1012 6906a9d8 Guido Trotter
  @param instance: the instance definition
1013 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1014 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1015 6906a9d8 Guido Trotter
  @type target: string
1016 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1017 6906a9d8 Guido Trotter

1018 6906a9d8 Guido Trotter
  """
1019 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1020 cd42d0ad Guido Trotter
  try:
1021 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1022 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1023 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1024 6906a9d8 Guido Trotter
1025 6906a9d8 Guido Trotter
1026 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1027 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1028 6906a9d8 Guido Trotter

1029 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1030 6906a9d8 Guido Trotter
  @param instance: the instance definition
1031 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1032 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1033 6906a9d8 Guido Trotter
  @type success: boolean
1034 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1035 6906a9d8 Guido Trotter

1036 6906a9d8 Guido Trotter
  """
1037 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1038 cd42d0ad Guido Trotter
  try:
1039 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1040 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1041 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1042 6906a9d8 Guido Trotter
1043 6906a9d8 Guido Trotter
1044 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1045 2a10865c Iustin Pop
  """Migrates an instance to another node.
1046 2a10865c Iustin Pop

1047 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1048 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1049 9f0e6b37 Iustin Pop
  @type target: string
1050 9f0e6b37 Iustin Pop
  @param target: the target node name
1051 9f0e6b37 Iustin Pop
  @type live: boolean
1052 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1053 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1054 9f0e6b37 Iustin Pop
  @rtype: tuple
1055 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1056 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1057 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1058 9f0e6b37 Iustin Pop

1059 2a10865c Iustin Pop
  """
1060 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1061 2a10865c Iustin Pop
1062 2a10865c Iustin Pop
  try:
1063 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
1064 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1065 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1066 2a10865c Iustin Pop
1067 2a10865c Iustin Pop
1068 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1069 a8083063 Iustin Pop
  """Creates a block device for an instance.
1070 a8083063 Iustin Pop

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

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

1088 a8083063 Iustin Pop
  """
1089 a8083063 Iustin Pop
  clist = []
1090 a8083063 Iustin Pop
  if disk.children:
1091 a8083063 Iustin Pop
    for child in disk.children:
1092 1063abd1 Iustin Pop
      try:
1093 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1094 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1095 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1096 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1097 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1098 a8083063 Iustin Pop
        # be assembled
1099 1063abd1 Iustin Pop
        try:
1100 1063abd1 Iustin Pop
          crdev.Open()
1101 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1102 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1103 a8083063 Iustin Pop
      clist.append(crdev)
1104 a8083063 Iustin Pop
1105 dab69e97 Iustin Pop
  try:
1106 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1107 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1108 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1109 6c626518 Iustin Pop
1110 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1111 1063abd1 Iustin Pop
    try:
1112 1063abd1 Iustin Pop
      device.Assemble()
1113 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1114 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1115 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1116 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1117 1063abd1 Iustin Pop
      try:
1118 1063abd1 Iustin Pop
        device.Open(force=True)
1119 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1120 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1121 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1122 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1123 a0c3fea1 Michael Hanselmann
1124 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1125 a0c3fea1 Michael Hanselmann
1126 c26a6bd2 Iustin Pop
  return device.unique_id
1127 a8083063 Iustin Pop
1128 a8083063 Iustin Pop
1129 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1130 a8083063 Iustin Pop
  """Remove a block device.
1131 a8083063 Iustin Pop

1132 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1133 10c2650b Iustin Pop

1134 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1135 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1136 10c2650b Iustin Pop
  @rtype: boolean
1137 10c2650b Iustin Pop
  @return: the success of the operation
1138 a8083063 Iustin Pop

1139 a8083063 Iustin Pop
  """
1140 e1bc0878 Iustin Pop
  msgs = []
1141 a8083063 Iustin Pop
  try:
1142 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1143 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1144 a8083063 Iustin Pop
    # probably can't attach
1145 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1146 a8083063 Iustin Pop
    rdev = None
1147 a8083063 Iustin Pop
  if rdev is not None:
1148 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1149 e1bc0878 Iustin Pop
    try:
1150 0c6c04ec Iustin Pop
      rdev.Remove()
1151 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1152 e1bc0878 Iustin Pop
      msgs.append(str(err))
1153 c26a6bd2 Iustin Pop
    if not msgs:
1154 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1155 e1bc0878 Iustin Pop
1156 a8083063 Iustin Pop
  if disk.children:
1157 a8083063 Iustin Pop
    for child in disk.children:
1158 c26a6bd2 Iustin Pop
      try:
1159 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1160 c26a6bd2 Iustin Pop
      except RPCFail, err:
1161 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1162 e1bc0878 Iustin Pop
1163 c26a6bd2 Iustin Pop
  if msgs:
1164 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1165 afdc3985 Iustin Pop
1166 a8083063 Iustin Pop
1167 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1168 a8083063 Iustin Pop
  """Activate a block device for an instance.
1169 a8083063 Iustin Pop

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

1172 10c2650b Iustin Pop
  @note: this function is called recursively.
1173 a8083063 Iustin Pop

1174 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1175 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1176 10c2650b Iustin Pop
  @type owner: str
1177 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1178 10c2650b Iustin Pop
  @type as_primary: boolean
1179 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1180 10c2650b Iustin Pop
      read/write
1181 a8083063 Iustin Pop

1182 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1183 10c2650b Iustin Pop
      was assembled)
1184 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1185 10c2650b Iustin Pop
      during the activation of the children or the device
1186 10c2650b Iustin Pop
      itself
1187 a8083063 Iustin Pop

1188 a8083063 Iustin Pop
  """
1189 a8083063 Iustin Pop
  children = []
1190 a8083063 Iustin Pop
  if disk.children:
1191 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1192 fc1dc9d7 Iustin Pop
    if mcn == -1:
1193 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1194 fc1dc9d7 Iustin Pop
    else:
1195 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1196 a8083063 Iustin Pop
    for chld_disk in disk.children:
1197 fc1dc9d7 Iustin Pop
      try:
1198 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1199 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1200 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1201 fc1dc9d7 Iustin Pop
          raise
1202 fc1dc9d7 Iustin Pop
        cdev = None
1203 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1204 1063abd1 Iustin Pop
                      str(err))
1205 fc1dc9d7 Iustin Pop
      children.append(cdev)
1206 a8083063 Iustin Pop
1207 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1208 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1209 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1210 a8083063 Iustin Pop
    result = r_dev
1211 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1212 a8083063 Iustin Pop
      r_dev.Open()
1213 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1214 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1215 3f78eef2 Iustin Pop
1216 a8083063 Iustin Pop
  else:
1217 a8083063 Iustin Pop
    result = True
1218 a8083063 Iustin Pop
  return result
1219 a8083063 Iustin Pop
1220 a8083063 Iustin Pop
1221 821d1bd1 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary):
1222 a8083063 Iustin Pop
  """Activate a block device for an instance.
1223 a8083063 Iustin Pop

1224 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1225 a8083063 Iustin Pop

1226 b1206984 Iustin Pop
  @rtype: str or boolean
1227 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1228 b1206984 Iustin Pop
      C{True} for secondary nodes
1229 a8083063 Iustin Pop

1230 a8083063 Iustin Pop
  """
1231 53c14ef1 Iustin Pop
  try:
1232 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1233 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1234 53c14ef1 Iustin Pop
      result = result.dev_path
1235 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1236 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1237 afdc3985 Iustin Pop
1238 c26a6bd2 Iustin Pop
  return result
1239 a8083063 Iustin Pop
1240 a8083063 Iustin Pop
1241 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1242 a8083063 Iustin Pop
  """Shut down a block device.
1243 a8083063 Iustin Pop

1244 c41eea6e Iustin Pop
  First, if the device is assembled (Attach() is successfull), then
1245 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1246 c41eea6e Iustin Pop
  shutdown.
1247 a8083063 Iustin Pop

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

1252 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1253 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1254 10c2650b Iustin Pop
      shutdown
1255 c26a6bd2 Iustin Pop
  @rtype: None
1256 10c2650b Iustin Pop

1257 a8083063 Iustin Pop
  """
1258 cacfd1fd Iustin Pop
  msgs = []
1259 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1260 a8083063 Iustin Pop
  if r_dev is not None:
1261 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1262 cacfd1fd Iustin Pop
    try:
1263 746f7476 Iustin Pop
      r_dev.Shutdown()
1264 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1265 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1266 cacfd1fd Iustin Pop
      msgs.append(str(err))
1267 746f7476 Iustin Pop
1268 a8083063 Iustin Pop
  if disk.children:
1269 a8083063 Iustin Pop
    for child in disk.children:
1270 c26a6bd2 Iustin Pop
      try:
1271 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1272 c26a6bd2 Iustin Pop
      except RPCFail, err:
1273 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1274 746f7476 Iustin Pop
1275 c26a6bd2 Iustin Pop
  if msgs:
1276 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1277 a8083063 Iustin Pop
1278 a8083063 Iustin Pop
1279 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1280 153d9724 Iustin Pop
  """Extend a mirrored block device.
1281 a8083063 Iustin Pop

1282 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1283 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1284 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1285 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1286 c26a6bd2 Iustin Pop
  @rtype: None
1287 10c2650b Iustin Pop

1288 a8083063 Iustin Pop
  """
1289 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1290 153d9724 Iustin Pop
  if parent_bdev is None:
1291 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1292 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1293 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1294 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1295 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1296 a8083063 Iustin Pop
1297 a8083063 Iustin Pop
1298 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1299 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1300 a8083063 Iustin Pop

1301 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1302 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1303 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1304 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1305 c26a6bd2 Iustin Pop
  @rtype: None
1306 10c2650b Iustin Pop

1307 a8083063 Iustin Pop
  """
1308 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1309 153d9724 Iustin Pop
  if parent_bdev is None:
1310 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1311 e739bd57 Iustin Pop
  devs = []
1312 e739bd57 Iustin Pop
  for disk in new_cdevs:
1313 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1314 e739bd57 Iustin Pop
    if rpath is None:
1315 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1316 e739bd57 Iustin Pop
      if bd is None:
1317 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1318 e739bd57 Iustin Pop
      else:
1319 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1320 e739bd57 Iustin Pop
    else:
1321 e739bd57 Iustin Pop
      devs.append(rpath)
1322 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1323 a8083063 Iustin Pop
1324 a8083063 Iustin Pop
1325 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1326 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1327 a8083063 Iustin Pop

1328 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1329 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1330 10c2650b Iustin Pop
  @rtype: disk
1331 10c2650b Iustin Pop
  @return:
1332 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1333 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1334 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1335 10c2650b Iustin Pop
      found
1336 a8083063 Iustin Pop

1337 a8083063 Iustin Pop
  """
1338 a8083063 Iustin Pop
  stats = []
1339 a8083063 Iustin Pop
  for dsk in disks:
1340 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1341 a8083063 Iustin Pop
    if rbd is None:
1342 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1343 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1344 c26a6bd2 Iustin Pop
  return stats
1345 a8083063 Iustin Pop
1346 a8083063 Iustin Pop
1347 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1348 a8083063 Iustin Pop
  """Check if a device is activated.
1349 a8083063 Iustin Pop

1350 a8083063 Iustin Pop
  If so, return informations about the real device.
1351 a8083063 Iustin Pop

1352 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1353 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1354 a8083063 Iustin Pop

1355 10c2650b Iustin Pop
  @return: None if the device can't be found,
1356 10c2650b Iustin Pop
      otherwise the device instance
1357 a8083063 Iustin Pop

1358 a8083063 Iustin Pop
  """
1359 a8083063 Iustin Pop
  children = []
1360 a8083063 Iustin Pop
  if disk.children:
1361 a8083063 Iustin Pop
    for chdisk in disk.children:
1362 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1363 a8083063 Iustin Pop
1364 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1365 a8083063 Iustin Pop
1366 a8083063 Iustin Pop
1367 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1368 a8083063 Iustin Pop
  """Check if a device is activated.
1369 a8083063 Iustin Pop

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

1372 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1373 10c2650b Iustin Pop
  @param disk: the disk to find
1374 10c2650b Iustin Pop
  @rtype: None or tuple
1375 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1376 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1377 10c2650b Iustin Pop
      estimated_time, is_degraded)
1378 a8083063 Iustin Pop

1379 a8083063 Iustin Pop
  """
1380 23829f6f Iustin Pop
  try:
1381 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1382 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1383 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1384 a8083063 Iustin Pop
  if rbd is None:
1385 c26a6bd2 Iustin Pop
    return None
1386 c26a6bd2 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1387 a8083063 Iustin Pop
1388 a8083063 Iustin Pop
1389 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1390 a8083063 Iustin Pop
  """Write a file to the filesystem.
1391 a8083063 Iustin Pop

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

1395 10c2650b Iustin Pop
  @type file_name: str
1396 10c2650b Iustin Pop
  @param file_name: the target file name
1397 10c2650b Iustin Pop
  @type data: str
1398 10c2650b Iustin Pop
  @param data: the new contents of the file
1399 10c2650b Iustin Pop
  @type mode: int
1400 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1401 10c2650b Iustin Pop
  @type uid: int
1402 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1403 10c2650b Iustin Pop
  @type gid: int
1404 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1405 10c2650b Iustin Pop
  @type atime: float
1406 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1407 10c2650b Iustin Pop
  @type mtime: float
1408 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1409 c26a6bd2 Iustin Pop
  @rtype: None
1410 10c2650b Iustin Pop

1411 a8083063 Iustin Pop
  """
1412 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1413 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1414 a8083063 Iustin Pop
1415 4501a443 Guido Trotter
  allowed_files = set([
1416 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1417 97628462 Iustin Pop
    constants.ETC_HOSTS,
1418 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1419 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1420 4501a443 Guido Trotter
    constants.RAPI_CERT_FILE,
1421 4501a443 Guido Trotter
    constants.RAPI_USERS_FILE,
1422 4501a443 Guido Trotter
    ])
1423 4501a443 Guido Trotter
1424 4501a443 Guido Trotter
  for hv_name in constants.HYPER_TYPES:
1425 4501a443 Guido Trotter
    hv_class = hypervisor.GetHypervisor(hv_name)
1426 4501a443 Guido Trotter
    allowed_files.update(hv_class.GetAncillaryFiles())
1427 afee8008 Michael Hanselmann
1428 553f1c1d Michael Hanselmann
  if file_name not in allowed_files:
1429 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1430 2cc6781a Iustin Pop
          file_name)
1431 a8083063 Iustin Pop
1432 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1433 12bce260 Michael Hanselmann
1434 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1435 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1436 a8083063 Iustin Pop
1437 386b57af Iustin Pop
1438 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1439 89b14f05 Iustin Pop
  """Update all ssconf files.
1440 89b14f05 Iustin Pop

1441 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1442 89b14f05 Iustin Pop

1443 89b14f05 Iustin Pop
  """
1444 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1445 6ddc95ec Michael Hanselmann
1446 6ddc95ec Michael Hanselmann
1447 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1448 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1449 a8083063 Iustin Pop

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

1454 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1455 10c2650b Iustin Pop
  @param err: the exception to format
1456 a8083063 Iustin Pop

1457 a8083063 Iustin Pop
  """
1458 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1459 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1460 a8083063 Iustin Pop
  else:
1461 a8083063 Iustin Pop
    detail = str(err)
1462 a8083063 Iustin Pop
  return detail
1463 a8083063 Iustin Pop
1464 5d0fe286 Iustin Pop
1465 7ead9575 Guido Trotter
def _OSOndiskAPIVersion(name, os_dir):
1466 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1467 a8083063 Iustin Pop

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

1471 10c2650b Iustin Pop
  @type name: str
1472 10c2650b Iustin Pop
  @param name: the OS name we should look for
1473 10c2650b Iustin Pop
  @type os_dir: str
1474 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1475 8e70b181 Iustin Pop
  @rtype: tuple
1476 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
1477 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
1478 a8083063 Iustin Pop

1479 a8083063 Iustin Pop
  """
1480 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1481 a8083063 Iustin Pop
1482 a8083063 Iustin Pop
  try:
1483 a8083063 Iustin Pop
    st = os.stat(api_file)
1484 a8083063 Iustin Pop
  except EnvironmentError, err:
1485 255dcebd Iustin Pop
    return False, ("Required file 'ganeti_api_version' file not"
1486 255dcebd Iustin Pop
                   " found under path %s: %s" % (os_dir, _ErrnoOrStr(err)))
1487 a8083063 Iustin Pop
1488 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1489 255dcebd Iustin Pop
    return False, ("File 'ganeti_api_version' file at %s is not"
1490 255dcebd Iustin Pop
                   " a regular file" % os_dir)
1491 a8083063 Iustin Pop
1492 a8083063 Iustin Pop
  try:
1493 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
1494 a8083063 Iustin Pop
  except EnvironmentError, err:
1495 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
1496 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
1497 a8083063 Iustin Pop
1498 082a7f91 Guido Trotter
  api_versions = [version.strip() for version in api_versions]
1499 a8083063 Iustin Pop
  try:
1500 082a7f91 Guido Trotter
    api_versions = [int(version) for version in api_versions]
1501 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1502 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
1503 255dcebd Iustin Pop
                   str(err))
1504 a8083063 Iustin Pop
1505 255dcebd Iustin Pop
  return True, api_versions
1506 a8083063 Iustin Pop
1507 386b57af Iustin Pop
1508 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1509 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1510 a8083063 Iustin Pop

1511 10c2650b Iustin Pop
  @type top_dirs: list
1512 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1513 10c2650b Iustin Pop
      search (if not given defaults to
1514 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1515 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1516 255dcebd Iustin Pop
  @return: a list of tuples (name, path, status, diagnose)
1517 255dcebd Iustin Pop
      for all (potential) OSes under all search paths, where:
1518 255dcebd Iustin Pop
          - name is the (potential) OS name
1519 255dcebd Iustin Pop
          - path is the full path to the OS
1520 255dcebd Iustin Pop
          - status True/False is the validity of the OS
1521 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
1522 a8083063 Iustin Pop

1523 a8083063 Iustin Pop
  """
1524 7c3d51d4 Guido Trotter
  if top_dirs is None:
1525 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1526 a8083063 Iustin Pop
1527 a8083063 Iustin Pop
  result = []
1528 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1529 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1530 7c3d51d4 Guido Trotter
      try:
1531 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1532 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1533 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1534 7c3d51d4 Guido Trotter
        break
1535 7c3d51d4 Guido Trotter
      for name in f_names:
1536 255dcebd Iustin Pop
        os_path = os.path.sep.join([dir_name, name])
1537 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1538 255dcebd Iustin Pop
        if status:
1539 255dcebd Iustin Pop
          diagnose = ""
1540 255dcebd Iustin Pop
        else:
1541 255dcebd Iustin Pop
          diagnose = os_inst
1542 255dcebd Iustin Pop
        result.append((name, os_path, status, diagnose))
1543 a8083063 Iustin Pop
1544 c26a6bd2 Iustin Pop
  return result
1545 a8083063 Iustin Pop
1546 a8083063 Iustin Pop
1547 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
1548 a8083063 Iustin Pop
  """Create an OS instance from disk.
1549 a8083063 Iustin Pop

1550 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1551 8e70b181 Iustin Pop
  valid OS name.
1552 a8083063 Iustin Pop

1553 8ee4dc80 Guido Trotter
  @type base_dir: string
1554 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1555 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1556 255dcebd Iustin Pop
  @rtype: tuple
1557 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
1558 255dcebd Iustin Pop
      or error message
1559 7c3d51d4 Guido Trotter

1560 a8083063 Iustin Pop
  """
1561 56bcd3f4 Guido Trotter
  if base_dir is None:
1562 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1563 c34c0cfd Iustin Pop
    if os_dir is None:
1564 255dcebd Iustin Pop
      return False, "Directory for OS %s not found in search path" % name
1565 c34c0cfd Iustin Pop
  else:
1566 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1567 a8083063 Iustin Pop
1568 7ead9575 Guido Trotter
  status, api_versions = _OSOndiskAPIVersion(name, os_dir)
1569 255dcebd Iustin Pop
  if not status:
1570 255dcebd Iustin Pop
    # push the error up
1571 255dcebd Iustin Pop
    return status, api_versions
1572 a8083063 Iustin Pop
1573 082a7f91 Guido Trotter
  if constants.OS_API_VERSION not in api_versions:
1574 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1575 255dcebd Iustin Pop
                   (os_dir, api_versions, constants.OS_API_VERSION))
1576 a8083063 Iustin Pop
1577 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1578 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1579 a8083063 Iustin Pop
1580 a8083063 Iustin Pop
  for script in os_scripts:
1581 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1582 a8083063 Iustin Pop
1583 a8083063 Iustin Pop
    try:
1584 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1585 a8083063 Iustin Pop
    except EnvironmentError, err:
1586 255dcebd Iustin Pop
      return False, ("Script '%s' under path '%s' is missing (%s)" %
1587 255dcebd Iustin Pop
                     (script, os_dir, _ErrnoOrStr(err)))
1588 a8083063 Iustin Pop
1589 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1590 255dcebd Iustin Pop
      return False, ("Script '%s' under path '%s' is not executable" %
1591 255dcebd Iustin Pop
                     (script, os_dir))
1592 a8083063 Iustin Pop
1593 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1594 255dcebd Iustin Pop
      return False, ("Script '%s' under path '%s' is not a regular file" %
1595 255dcebd Iustin Pop
                     (script, os_dir))
1596 255dcebd Iustin Pop
1597 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
1598 255dcebd Iustin Pop
                      create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1599 255dcebd Iustin Pop
                      export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1600 255dcebd Iustin Pop
                      import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1601 255dcebd Iustin Pop
                      rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1602 255dcebd Iustin Pop
                      api_versions=api_versions)
1603 255dcebd Iustin Pop
  return True, os_obj
1604 255dcebd Iustin Pop
1605 255dcebd Iustin Pop
1606 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
1607 255dcebd Iustin Pop
  """Create an OS instance from disk.
1608 255dcebd Iustin Pop

1609 255dcebd Iustin Pop
  This function will return an OS instance if the given name is a
1610 255dcebd Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
1611 255dcebd Iustin Pop
  L{RPCFail} exception, detailing why this is not a valid OS.
1612 255dcebd Iustin Pop

1613 255dcebd Iustin Pop
  This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
1614 255dcebd Iustin Pop
  an exception but returns true/false status data.
1615 255dcebd Iustin Pop

1616 255dcebd Iustin Pop
  @type base_dir: string
1617 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
1618 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1619 255dcebd Iustin Pop
  @rtype: L{objects.OS}
1620 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
1621 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
1622 255dcebd Iustin Pop

1623 255dcebd Iustin Pop
  """
1624 255dcebd Iustin Pop
  status, payload = _TryOSFromDisk(name, base_dir)
1625 255dcebd Iustin Pop
1626 255dcebd Iustin Pop
  if not status:
1627 255dcebd Iustin Pop
    _Fail(payload)
1628 a8083063 Iustin Pop
1629 255dcebd Iustin Pop
  return payload
1630 a8083063 Iustin Pop
1631 a8083063 Iustin Pop
1632 2266edb2 Guido Trotter
def OSEnvironment(instance, debug=0):
1633 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1634 2266edb2 Guido Trotter

1635 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1636 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1637 2266edb2 Guido Trotter
  @type debug: integer
1638 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1639 2266edb2 Guido Trotter
  @rtype: dict
1640 2266edb2 Guido Trotter
  @return: dict of environment variables
1641 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1642 10c2650b Iustin Pop
      cannot be found
1643 2266edb2 Guido Trotter

1644 2266edb2 Guido Trotter
  """
1645 2266edb2 Guido Trotter
  result = {}
1646 2266edb2 Guido Trotter
  result['OS_API_VERSION'] = '%d' % constants.OS_API_VERSION
1647 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1648 15552312 Iustin Pop
  result['INSTANCE_OS'] = instance.os
1649 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1650 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1651 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1652 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1653 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1654 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1655 2266edb2 Guido Trotter
    if real_disk is None:
1656 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1657 2266edb2 Guido Trotter
                                    str(disk))
1658 2266edb2 Guido Trotter
    real_disk.Open()
1659 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1660 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
1661 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1662 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1663 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1664 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1665 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1666 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1667 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1668 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1669 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1670 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1671 2266edb2 Guido Trotter
    if nic.ip:
1672 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1673 1ba9227f Guido Trotter
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1674 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1675 1ba9227f Guido Trotter
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1676 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
1677 1ba9227f Guido Trotter
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1678 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1679 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1680 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1681 2266edb2 Guido Trotter
1682 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1683 67fc3042 Iustin Pop
    for key, value in source.items():
1684 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1685 67fc3042 Iustin Pop
1686 2266edb2 Guido Trotter
  return result
1687 a8083063 Iustin Pop
1688 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
1689 594609c0 Iustin Pop
  """Grow a stack of block devices.
1690 594609c0 Iustin Pop

1691 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1692 10c2650b Iustin Pop
  first ones to resize.
1693 594609c0 Iustin Pop

1694 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1695 10c2650b Iustin Pop
  @param disk: the disk to be grown
1696 10c2650b Iustin Pop
  @rtype: (status, result)
1697 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1698 10c2650b Iustin Pop
      (True/False), and the errors message if status
1699 10c2650b Iustin Pop
      is False
1700 594609c0 Iustin Pop

1701 594609c0 Iustin Pop
  """
1702 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1703 594609c0 Iustin Pop
  if r_dev is None:
1704 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
1705 594609c0 Iustin Pop
1706 594609c0 Iustin Pop
  try:
1707 594609c0 Iustin Pop
    r_dev.Grow(amount)
1708 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1709 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
1710 594609c0 Iustin Pop
1711 594609c0 Iustin Pop
1712 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
1713 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1714 a8083063 Iustin Pop

1715 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1716 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1717 a8083063 Iustin Pop

1718 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1719 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1720 e9e9263d Guido Trotter
  @rtype: string
1721 e9e9263d Guido Trotter
  @return: snapshot disk path
1722 a8083063 Iustin Pop

1723 098c0958 Michael Hanselmann
  """
1724 a8083063 Iustin Pop
  if disk.children:
1725 a8083063 Iustin Pop
    if len(disk.children) == 1:
1726 a8083063 Iustin Pop
      # only one child, let's recurse on it
1727 821d1bd1 Iustin Pop
      return BlockdevSnapshot(disk.children[0])
1728 a8083063 Iustin Pop
    else:
1729 a8083063 Iustin Pop
      # more than one child, choose one that matches
1730 a8083063 Iustin Pop
      for child in disk.children:
1731 a8083063 Iustin Pop
        if child.size == disk.size:
1732 a8083063 Iustin Pop
          # return implies breaking the loop
1733 821d1bd1 Iustin Pop
          return BlockdevSnapshot(child)
1734 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1735 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1736 a8083063 Iustin Pop
    if r_dev is not None:
1737 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1738 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
1739 a8083063 Iustin Pop
    else:
1740 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
1741 a8083063 Iustin Pop
  else:
1742 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1743 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
1744 a8083063 Iustin Pop
1745 a8083063 Iustin Pop
1746 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1747 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1748 a8083063 Iustin Pop

1749 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1750 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1751 74c47259 Iustin Pop
  @type dest_node: str
1752 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1753 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1754 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1755 74c47259 Iustin Pop
  @type cluster_name: str
1756 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1757 74c47259 Iustin Pop
  @type idx: int
1758 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1759 74c47259 Iustin Pop
      used to export to the OS scripts environment
1760 c26a6bd2 Iustin Pop
  @rtype: None
1761 a8083063 Iustin Pop

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

1811 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1812 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
1813 10c2650b Iustin Pop
      saving configuration
1814 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
1815 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
1816 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
1817 a8083063 Iustin Pop

1818 c26a6bd2 Iustin Pop
  @rtype: None
1819 a8083063 Iustin Pop

1820 098c0958 Michael Hanselmann
  """
1821 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1822 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1823 a8083063 Iustin Pop
1824 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1825 a8083063 Iustin Pop
1826 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1827 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1828 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1829 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1830 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1831 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1832 a8083063 Iustin Pop
1833 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1834 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1835 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
1836 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
1837 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1838 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
1839 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1840 66f93869 Manuel Franceschini
1841 95268cc3 Iustin Pop
  nic_total = 0
1842 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1843 95268cc3 Iustin Pop
    nic_total += 1
1844 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1845 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1846 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1847 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1848 38206f3c Iustin Pop
               '%s' % nic.bridge)
1849 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1850 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1851 a8083063 Iustin Pop
1852 726d7d68 Iustin Pop
  disk_total = 0
1853 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1854 19d7f90a Guido Trotter
    if disk:
1855 726d7d68 Iustin Pop
      disk_total += 1
1856 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1857 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
1858 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1859 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
1860 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1861 19d7f90a Guido Trotter
                 ('%d' % disk.size))
1862 a8083063 Iustin Pop
1863 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1864 a8083063 Iustin Pop
1865 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1866 726d7d68 Iustin Pop
                  data=config.Dumps())
1867 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1868 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1869 a8083063 Iustin Pop
1870 a8083063 Iustin Pop
1871 a8083063 Iustin Pop
def ExportInfo(dest):
1872 a8083063 Iustin Pop
  """Get export configuration information.
1873 a8083063 Iustin Pop

1874 10c2650b Iustin Pop
  @type dest: str
1875 10c2650b Iustin Pop
  @param dest: directory containing the export
1876 a8083063 Iustin Pop

1877 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
1878 10c2650b Iustin Pop
  @return: a serializable config file containing the
1879 10c2650b Iustin Pop
      export info
1880 a8083063 Iustin Pop

1881 a8083063 Iustin Pop
  """
1882 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1883 a8083063 Iustin Pop
1884 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1885 a8083063 Iustin Pop
  config.read(cff)
1886 a8083063 Iustin Pop
1887 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1888 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1889 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
1890 a8083063 Iustin Pop
1891 c26a6bd2 Iustin Pop
  return config.Dumps()
1892 a8083063 Iustin Pop
1893 a8083063 Iustin Pop
1894 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1895 a8083063 Iustin Pop
  """Import an os image into an instance.
1896 a8083063 Iustin Pop

1897 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1898 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
1899 6c0af70e Guido Trotter
  @type src_node: string
1900 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
1901 6c0af70e Guido Trotter
  @type src_images: list of string
1902 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
1903 6c0af70e Guido Trotter
  @rtype: list of boolean
1904 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
1905 a8083063 Iustin Pop

1906 a8083063 Iustin Pop
  """
1907 6c0af70e Guido Trotter
  import_env = OSEnvironment(instance)
1908 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1909 a8083063 Iustin Pop
  import_script = inst_os.import_script
1910 a8083063 Iustin Pop
1911 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1912 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1913 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1914 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1915 a8083063 Iustin Pop
1916 a8083063 Iustin Pop
  comprcmd = "gunzip"
1917 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1918 d868edb4 Iustin Pop
                               import_script, logfile)
1919 a8083063 Iustin Pop
1920 6c0af70e Guido Trotter
  final_result = []
1921 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
1922 6c0af70e Guido Trotter
    if image:
1923 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
1924 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1925 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
1926 6c0af70e Guido Trotter
                                                       destcmd)
1927 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1928 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1929 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
1930 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
1931 6c0af70e Guido Trotter
      if result.failed:
1932 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
1933 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
1934 726d7d68 Iustin Pop
                      result.output)
1935 944bf548 Iustin Pop
        final_result.append("error importing disk %d: %s, %s" %
1936 944bf548 Iustin Pop
                            (idx, result.fail_reason, result.output[-100]))
1937 a8083063 Iustin Pop
1938 944bf548 Iustin Pop
  if final_result:
1939 afdc3985 Iustin Pop
    _Fail("; ".join(final_result), log=False)
1940 a8083063 Iustin Pop
1941 a8083063 Iustin Pop
1942 a8083063 Iustin Pop
def ListExports():
1943 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1944 098c0958 Michael Hanselmann

1945 10c2650b Iustin Pop
  @rtype: list
1946 10c2650b Iustin Pop
  @return: list of the exports
1947 10c2650b Iustin Pop

1948 a8083063 Iustin Pop
  """
1949 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1950 c26a6bd2 Iustin Pop
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1951 a8083063 Iustin Pop
  else:
1952 afdc3985 Iustin Pop
    _Fail("No exports directory")
1953 a8083063 Iustin Pop
1954 a8083063 Iustin Pop
1955 a8083063 Iustin Pop
def RemoveExport(export):
1956 a8083063 Iustin Pop
  """Remove an existing export from the node.
1957 a8083063 Iustin Pop

1958 10c2650b Iustin Pop
  @type export: str
1959 10c2650b Iustin Pop
  @param export: the name of the export to remove
1960 c26a6bd2 Iustin Pop
  @rtype: None
1961 a8083063 Iustin Pop

1962 098c0958 Michael Hanselmann
  """
1963 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1964 a8083063 Iustin Pop
1965 35fbcd11 Iustin Pop
  try:
1966 35fbcd11 Iustin Pop
    shutil.rmtree(target)
1967 35fbcd11 Iustin Pop
  except EnvironmentError, err:
1968 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
1969 a8083063 Iustin Pop
1970 a8083063 Iustin Pop
1971 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
1972 f3e513ad Iustin Pop
  """Rename a list of block devices.
1973 f3e513ad Iustin Pop

1974 10c2650b Iustin Pop
  @type devlist: list of tuples
1975 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
1976 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
1977 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
1978 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
1979 10c2650b Iustin Pop
      rename it to
1980 10c2650b Iustin Pop
  @rtype: boolean
1981 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
1982 f3e513ad Iustin Pop

1983 f3e513ad Iustin Pop
  """
1984 6b5e3f70 Iustin Pop
  msgs = []
1985 f3e513ad Iustin Pop
  result = True
1986 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1987 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1988 f3e513ad Iustin Pop
    if dev is None:
1989 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
1990 f3e513ad Iustin Pop
      result = False
1991 f3e513ad Iustin Pop
      continue
1992 f3e513ad Iustin Pop
    try:
1993 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1994 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1995 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1996 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1997 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1998 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1999 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2000 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2001 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2002 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2003 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2004 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2005 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2006 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2007 f3e513ad Iustin Pop
      result = False
2008 afdc3985 Iustin Pop
  if not result:
2009 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2010 f3e513ad Iustin Pop
2011 f3e513ad Iustin Pop
2012 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2013 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2014 778b75bb Manuel Franceschini

2015 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2016 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2017 778b75bb Manuel Franceschini
  directory are allowed.
2018 778b75bb Manuel Franceschini

2019 b1206984 Iustin Pop
  @type file_storage_dir: str
2020 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2021 d61cbe76 Iustin Pop

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

2024 778b75bb Manuel Franceschini
  """
2025 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2026 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2027 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2028 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2029 778b75bb Manuel Franceschini
      base_file_storage_dir):
2030 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2031 b2b8bcce Iustin Pop
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2032 778b75bb Manuel Franceschini
  return file_storage_dir
2033 778b75bb Manuel Franceschini
2034 778b75bb Manuel Franceschini
2035 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2036 778b75bb Manuel Franceschini
  """Create file storage directory.
2037 778b75bb Manuel Franceschini

2038 b1206984 Iustin Pop
  @type file_storage_dir: str
2039 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2040 778b75bb Manuel Franceschini

2041 b1206984 Iustin Pop
  @rtype: tuple
2042 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2043 b1206984 Iustin Pop
      creation was successful or not
2044 778b75bb Manuel Franceschini

2045 778b75bb Manuel Franceschini
  """
2046 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2047 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2048 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2049 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2050 b2b8bcce Iustin Pop
            file_storage_dir)
2051 778b75bb Manuel Franceschini
  else:
2052 b2b8bcce Iustin Pop
    try:
2053 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2054 b2b8bcce Iustin Pop
    except OSError, err:
2055 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2056 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2057 778b75bb Manuel Franceschini
2058 778b75bb Manuel Franceschini
2059 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2060 778b75bb Manuel Franceschini
  """Remove file storage directory.
2061 778b75bb Manuel Franceschini

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

2064 10c2650b Iustin Pop
  @type file_storage_dir: str
2065 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2066 10c2650b Iustin Pop
  @rtype: tuple (success,)
2067 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2068 10c2650b Iustin Pop
      whether the operation was successfull
2069 778b75bb Manuel Franceschini

2070 778b75bb Manuel Franceschini
  """
2071 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2072 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2073 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2074 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2075 b2b8bcce Iustin Pop
            file_storage_dir)
2076 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2077 b2b8bcce Iustin Pop
    try:
2078 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2079 b2b8bcce Iustin Pop
    except OSError, err:
2080 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2081 b2b8bcce Iustin Pop
            file_storage_dir, err)
2082 b2b8bcce Iustin Pop
2083 778b75bb Manuel Franceschini
2084 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2085 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2086 778b75bb Manuel Franceschini

2087 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2088 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2089 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2090 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2091 10c2650b Iustin Pop
  @rtype: tuple (success,)
2092 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2093 10c2650b Iustin Pop
      whether the operation was successful
2094 778b75bb Manuel Franceschini

2095 778b75bb Manuel Franceschini
  """
2096 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2097 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2098 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2099 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2100 b2b8bcce Iustin Pop
      try:
2101 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2102 b2b8bcce Iustin Pop
      except OSError, err:
2103 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2104 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2105 778b75bb Manuel Franceschini
    else:
2106 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2107 b2b8bcce Iustin Pop
            old_file_storage_dir)
2108 b2b8bcce Iustin Pop
  else:
2109 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2110 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2111 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2112 778b75bb Manuel Franceschini
2113 778b75bb Manuel Franceschini
2114 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2115 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2116 ca52cdeb Michael Hanselmann

2117 10c2650b Iustin Pop
  @type file_name: str
2118 10c2650b Iustin Pop
  @param file_name: the file name we should check
2119 c8457ce7 Iustin Pop
  @rtype: None
2120 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2121 10c2650b Iustin Pop

2122 ca52cdeb Michael Hanselmann
  """
2123 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2124 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2125 dc31eae3 Michael Hanselmann
2126 dc31eae3 Michael Hanselmann
  if not result:
2127 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2128 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2129 dc31eae3 Michael Hanselmann
2130 dc31eae3 Michael Hanselmann
2131 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2132 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2133 dc31eae3 Michael Hanselmann

2134 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2135 10c2650b Iustin Pop
  checking.
2136 10c2650b Iustin Pop

2137 10c2650b Iustin Pop
  @type file_name: str
2138 10c2650b Iustin Pop
  @param file_name: the job file name
2139 10c2650b Iustin Pop
  @type content: str
2140 10c2650b Iustin Pop
  @param content: the new job contents
2141 10c2650b Iustin Pop
  @rtype: boolean
2142 10c2650b Iustin Pop
  @return: the success of the operation
2143 10c2650b Iustin Pop

2144 dc31eae3 Michael Hanselmann
  """
2145 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2146 ca52cdeb Michael Hanselmann
2147 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2148 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2149 ca52cdeb Michael Hanselmann
2150 ca52cdeb Michael Hanselmann
2151 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2152 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2153 af5ebcb1 Michael Hanselmann

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

2156 10c2650b Iustin Pop
  @type old: str
2157 10c2650b Iustin Pop
  @param old: the old (actual) file name
2158 10c2650b Iustin Pop
  @type new: str
2159 10c2650b Iustin Pop
  @param new: the desired file name
2160 c8457ce7 Iustin Pop
  @rtype: tuple
2161 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2162 10c2650b Iustin Pop

2163 af5ebcb1 Michael Hanselmann
  """
2164 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2165 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2166 af5ebcb1 Michael Hanselmann
2167 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2168 af5ebcb1 Michael Hanselmann
2169 af5ebcb1 Michael Hanselmann
2170 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2171 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2172 5d672980 Iustin Pop

2173 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2174 5d672980 Iustin Pop

2175 10c2650b Iustin Pop
  @type drain_flag: boolean
2176 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2177 c8457ce7 Iustin Pop
  @rtype: truple
2178 c8457ce7 Iustin Pop
  @return: always True, None
2179 10c2650b Iustin Pop
  @warning: the function always returns True
2180 5d672980 Iustin Pop

2181 5d672980 Iustin Pop
  """
2182 5d672980 Iustin Pop
  if drain_flag:
2183 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2184 5d672980 Iustin Pop
  else:
2185 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2186 5d672980 Iustin Pop
2187 5d672980 Iustin Pop
2188 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2189 d61cbe76 Iustin Pop
  """Closes the given block devices.
2190 d61cbe76 Iustin Pop

2191 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2192 10c2650b Iustin Pop
  DRBD).
2193 10c2650b Iustin Pop

2194 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2195 b2e7666a Iustin Pop
      of this instance will be removed
2196 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2197 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2198 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2199 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2200 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2201 10c2650b Iustin Pop
      which will contain the error details in case we
2202 10c2650b Iustin Pop
      failed
2203 d61cbe76 Iustin Pop

2204 d61cbe76 Iustin Pop
  """
2205 d61cbe76 Iustin Pop
  bdevs = []
2206 d61cbe76 Iustin Pop
  for cf in disks:
2207 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2208 d61cbe76 Iustin Pop
    if rd is None:
2209 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2210 d61cbe76 Iustin Pop
    bdevs.append(rd)
2211 d61cbe76 Iustin Pop
2212 d61cbe76 Iustin Pop
  msg = []
2213 d61cbe76 Iustin Pop
  for rd in bdevs:
2214 d61cbe76 Iustin Pop
    try:
2215 d61cbe76 Iustin Pop
      rd.Close()
2216 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2217 d61cbe76 Iustin Pop
      msg.append(str(err))
2218 d61cbe76 Iustin Pop
  if msg:
2219 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2220 d61cbe76 Iustin Pop
  else:
2221 b2e7666a Iustin Pop
    if instance_name:
2222 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2223 d61cbe76 Iustin Pop
2224 d61cbe76 Iustin Pop
2225 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2226 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2227 6217e295 Iustin Pop

2228 6217e295 Iustin Pop
  @type hvname: string
2229 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2230 6217e295 Iustin Pop
  @type hvparams: dict
2231 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2232 c26a6bd2 Iustin Pop
  @rtype: None
2233 6217e295 Iustin Pop

2234 6217e295 Iustin Pop
  """
2235 6217e295 Iustin Pop
  try:
2236 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2237 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2238 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2239 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2240 6217e295 Iustin Pop
2241 6217e295 Iustin Pop
2242 56aa9fd5 Iustin Pop
def DemoteFromMC():
2243 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2244 56aa9fd5 Iustin Pop

2245 56aa9fd5 Iustin Pop
  """
2246 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2247 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2248 56aa9fd5 Iustin Pop
  if master == myself:
2249 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2250 56aa9fd5 Iustin Pop
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2251 56aa9fd5 Iustin Pop
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2252 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2253 56aa9fd5 Iustin Pop
  try:
2254 56aa9fd5 Iustin Pop
    utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2255 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2256 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2257 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2258 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2259 56aa9fd5 Iustin Pop
2260 56aa9fd5 Iustin Pop
2261 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2262 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2263 6b93ec9d Iustin Pop

2264 6b93ec9d Iustin Pop
  """
2265 6b93ec9d Iustin Pop
  # set the correct physical ID
2266 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2267 6b93ec9d Iustin Pop
  for cf in disks:
2268 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2269 6b93ec9d Iustin Pop
2270 6b93ec9d Iustin Pop
  bdevs = []
2271 6b93ec9d Iustin Pop
2272 6b93ec9d Iustin Pop
  for cf in disks:
2273 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2274 6b93ec9d Iustin Pop
    if rd is None:
2275 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
2276 6b93ec9d Iustin Pop
    bdevs.append(rd)
2277 5a533f8a Iustin Pop
  return bdevs
2278 6b93ec9d Iustin Pop
2279 6b93ec9d Iustin Pop
2280 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2281 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2282 6b93ec9d Iustin Pop

2283 6b93ec9d Iustin Pop
  """
2284 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2285 6b93ec9d Iustin Pop
2286 6b93ec9d Iustin Pop
  # disconnect disks
2287 6b93ec9d Iustin Pop
  for rd in bdevs:
2288 6b93ec9d Iustin Pop
    try:
2289 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2290 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2291 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
2292 2cc6781a Iustin Pop
            err, exc=True)
2293 6b93ec9d Iustin Pop
2294 6b93ec9d Iustin Pop
2295 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2296 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2297 6b93ec9d Iustin Pop

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

2354 6b93ec9d Iustin Pop
  """
2355 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2356 6b93ec9d Iustin Pop
2357 6b93ec9d Iustin Pop
  min_resync = 100
2358 6b93ec9d Iustin Pop
  alldone = True
2359 6b93ec9d Iustin Pop
  for rd in bdevs:
2360 6b93ec9d Iustin Pop
    stats = rd.GetProcStatus()
2361 6b93ec9d Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2362 afdc3985 Iustin Pop
      _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2363 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2364 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2365 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2366 afdc3985 Iustin Pop
2367 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
2368 6b93ec9d Iustin Pop
2369 6b93ec9d Iustin Pop
2370 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
2371 f5118ade Iustin Pop
  """Hard-powercycle the node.
2372 f5118ade Iustin Pop

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

2376 f5118ade Iustin Pop
  """
2377 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2378 f5118ade Iustin Pop
  try:
2379 f5118ade Iustin Pop
    pid = os.fork()
2380 29921401 Iustin Pop
  except OSError:
2381 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
2382 f5118ade Iustin Pop
    pid = 0
2383 f5118ade Iustin Pop
  if pid > 0:
2384 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
2385 f5118ade Iustin Pop
  time.sleep(5)
2386 f5118ade Iustin Pop
  hyper.PowercycleNode()
2387 f5118ade Iustin Pop
2388 f5118ade Iustin Pop
2389 a8083063 Iustin Pop
class HooksRunner(object):
2390 a8083063 Iustin Pop
  """Hook runner.
2391 a8083063 Iustin Pop

2392 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2393 10c2650b Iustin Pop
  on the master side.
2394 a8083063 Iustin Pop

2395 a8083063 Iustin Pop
  """
2396 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2397 a8083063 Iustin Pop
2398 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2399 a8083063 Iustin Pop
    """Constructor for hooks runner.
2400 a8083063 Iustin Pop

2401 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2402 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2403 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2404 a8083063 Iustin Pop

2405 a8083063 Iustin Pop
    """
2406 a8083063 Iustin Pop
    if hooks_base_dir is None:
2407 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2408 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2409 a8083063 Iustin Pop
2410 a8083063 Iustin Pop
  @staticmethod
2411 a8083063 Iustin Pop
  def ExecHook(script, env):
2412 a8083063 Iustin Pop
    """Exec one hook script.
2413 a8083063 Iustin Pop

2414 10c2650b Iustin Pop
    @type script: str
2415 10c2650b Iustin Pop
    @param script: the full path to the script
2416 10c2650b Iustin Pop
    @type env: dict
2417 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2418 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2419 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2420 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2421 10c2650b Iustin Pop
        which will contain the error details in case we
2422 10c2650b Iustin Pop
        failed
2423 a8083063 Iustin Pop

2424 a8083063 Iustin Pop
    """
2425 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2426 a8083063 Iustin Pop
    fdstdin = None
2427 a8083063 Iustin Pop
    try:
2428 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2429 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2430 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2431 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2432 a8083063 Iustin Pop
      output = ""
2433 a8083063 Iustin Pop
      try:
2434 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2435 a8083063 Iustin Pop
        child.stdout.close()
2436 a8083063 Iustin Pop
      except EnvironmentError, err:
2437 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2438 a8083063 Iustin Pop
2439 a8083063 Iustin Pop
      while True:
2440 a8083063 Iustin Pop
        try:
2441 a8083063 Iustin Pop
          result = child.wait()
2442 a8083063 Iustin Pop
          break
2443 a8083063 Iustin Pop
        except EnvironmentError, err:
2444 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2445 a8083063 Iustin Pop
            continue
2446 a8083063 Iustin Pop
          raise
2447 a8083063 Iustin Pop
    finally:
2448 a8083063 Iustin Pop
      # try not to leak fds
2449 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2450 a8083063 Iustin Pop
        if fd is not None:
2451 a8083063 Iustin Pop
          try:
2452 a8083063 Iustin Pop
            fd.close()
2453 a8083063 Iustin Pop
          except EnvironmentError, err:
2454 a8083063 Iustin Pop
            # just log the error
2455 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2456 a8083063 Iustin Pop
            pass
2457 a8083063 Iustin Pop
2458 26f15862 Iustin Pop
    return result == 0, utils.SafeEncode(output.strip())
2459 a8083063 Iustin Pop
2460 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2461 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2462 a8083063 Iustin Pop

2463 10c2650b Iustin Pop
    @type hpath: str
2464 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2465 10c2650b Iustin Pop
        holds the scripts
2466 10c2650b Iustin Pop
    @type phase: str
2467 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2468 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2469 10c2650b Iustin Pop
    @type env: dict
2470 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2471 10c2650b Iustin Pop
    @rtype: list
2472 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2473 10c2650b Iustin Pop
      - script path
2474 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2475 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2476 10c2650b Iustin Pop
      - output of the script
2477 10c2650b Iustin Pop

2478 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2479 10c2650b Iustin Pop
        parameters
2480 a8083063 Iustin Pop

2481 a8083063 Iustin Pop
    """
2482 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2483 a8083063 Iustin Pop
      suffix = "pre"
2484 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2485 a8083063 Iustin Pop
      suffix = "post"
2486 a8083063 Iustin Pop
    else:
2487 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
2488 3fb4f740 Iustin Pop
2489 a8083063 Iustin Pop
    rr = []
2490 a8083063 Iustin Pop
2491 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2492 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2493 a8083063 Iustin Pop
    try:
2494 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2495 29921401 Iustin Pop
    except OSError:
2496 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2497 c26a6bd2 Iustin Pop
      return rr
2498 a8083063 Iustin Pop
2499 a8083063 Iustin Pop
    # we use the standard python sort order,
2500 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2501 a8083063 Iustin Pop
    dir_contents.sort()
2502 a8083063 Iustin Pop
    for relname in dir_contents:
2503 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2504 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2505 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2506 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2507 a8083063 Iustin Pop
        output = ""
2508 a8083063 Iustin Pop
      else:
2509 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2510 a8083063 Iustin Pop
        if not result:
2511 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2512 a8083063 Iustin Pop
        else:
2513 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2514 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2515 a8083063 Iustin Pop
2516 c26a6bd2 Iustin Pop
    return rr
2517 3f78eef2 Iustin Pop
2518 3f78eef2 Iustin Pop
2519 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2520 8d528b7c Iustin Pop
  """IAllocator runner.
2521 8d528b7c Iustin Pop

2522 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2523 8d528b7c Iustin Pop
  the master side.
2524 8d528b7c Iustin Pop

2525 8d528b7c Iustin Pop
  """
2526 8d528b7c Iustin Pop
  def Run(self, name, idata):
2527 8d528b7c Iustin Pop
    """Run an iallocator script.
2528 8d528b7c Iustin Pop

2529 10c2650b Iustin Pop
    @type name: str
2530 10c2650b Iustin Pop
    @param name: the iallocator script name
2531 10c2650b Iustin Pop
    @type idata: str
2532 10c2650b Iustin Pop
    @param idata: the allocator input data
2533 10c2650b Iustin Pop

2534 10c2650b Iustin Pop
    @rtype: tuple
2535 87f5c298 Iustin Pop
    @return: two element tuple of:
2536 87f5c298 Iustin Pop
       - status
2537 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
2538 8d528b7c Iustin Pop

2539 8d528b7c Iustin Pop
    """
2540 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2541 8d528b7c Iustin Pop
                                  os.path.isfile)
2542 8d528b7c Iustin Pop
    if alloc_script is None:
2543 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
2544 8d528b7c Iustin Pop
2545 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2546 8d528b7c Iustin Pop
    try:
2547 8d528b7c Iustin Pop
      os.write(fd, idata)
2548 8d528b7c Iustin Pop
      os.close(fd)
2549 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2550 8d528b7c Iustin Pop
      if result.failed:
2551 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2552 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
2553 8d528b7c Iustin Pop
    finally:
2554 8d528b7c Iustin Pop
      os.unlink(fin_name)
2555 8d528b7c Iustin Pop
2556 c26a6bd2 Iustin Pop
    return result.stdout
2557 8d528b7c Iustin Pop
2558 8d528b7c Iustin Pop
2559 3f78eef2 Iustin Pop
class DevCacheManager(object):
2560 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2561 3f78eef2 Iustin Pop

2562 3f78eef2 Iustin Pop
  """
2563 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2564 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2565 3f78eef2 Iustin Pop
2566 3f78eef2 Iustin Pop
  @classmethod
2567 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2568 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2569 3f78eef2 Iustin Pop

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

2573 10c2650b Iustin Pop
    @type dev_path: str
2574 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2575 10c2650b Iustin Pop
    @rtype: str
2576 10c2650b Iustin Pop
    @return: the converted path name
2577 3f78eef2 Iustin Pop

2578 3f78eef2 Iustin Pop
    """
2579 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2580 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2581 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2582 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2583 3f78eef2 Iustin Pop
    return fpath
2584 3f78eef2 Iustin Pop
2585 3f78eef2 Iustin Pop
  @classmethod
2586 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2587 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2588 3f78eef2 Iustin Pop

2589 10c2650b Iustin Pop
    @type dev_path: str
2590 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2591 10c2650b Iustin Pop
    @type owner: str
2592 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2593 10c2650b Iustin Pop
    @type on_primary: bool
2594 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2595 10c2650b Iustin Pop
        node nor not
2596 10c2650b Iustin Pop
    @type iv_name: str
2597 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2598 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2599 10c2650b Iustin Pop

2600 10c2650b Iustin Pop
    @rtype: None
2601 10c2650b Iustin Pop

2602 3f78eef2 Iustin Pop
    """
2603 cf5a8306 Iustin Pop
    if dev_path is None:
2604 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2605 cf5a8306 Iustin Pop
      return
2606 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2607 3f78eef2 Iustin Pop
    if on_primary:
2608 3f78eef2 Iustin Pop
      state = "primary"
2609 3f78eef2 Iustin Pop
    else:
2610 3f78eef2 Iustin Pop
      state = "secondary"
2611 3f78eef2 Iustin Pop
    if iv_name is None:
2612 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2613 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2614 3f78eef2 Iustin Pop
    try:
2615 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2616 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2617 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2618 3f78eef2 Iustin Pop
2619 3f78eef2 Iustin Pop
  @classmethod
2620 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2621 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2622 3f78eef2 Iustin Pop

2623 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2624 10c2650b Iustin Pop
    path name and logging.
2625 10c2650b Iustin Pop

2626 10c2650b Iustin Pop
    @type dev_path: str
2627 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2628 10c2650b Iustin Pop

2629 10c2650b Iustin Pop
    @rtype: None
2630 10c2650b Iustin Pop

2631 3f78eef2 Iustin Pop
    """
2632 cf5a8306 Iustin Pop
    if dev_path is None:
2633 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2634 cf5a8306 Iustin Pop
      return
2635 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2636 3f78eef2 Iustin Pop
    try:
2637 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2638 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2639 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)