Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 14850c5e

History | View | Annotate | Download (87.8 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 360b0dc2 Iustin Pop
"""Functions used by the node daemon
23 360b0dc2 Iustin Pop

24 360b0dc2 Iustin Pop
@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
25 360b0dc2 Iustin Pop
     the L{UploadFile} function
26 714ea7ca Iustin Pop
@var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
27 714ea7ca Iustin Pop
     in the L{_CleanDirectory} function
28 360b0dc2 Iustin Pop

29 360b0dc2 Iustin Pop
"""
30 a8083063 Iustin Pop
31 6c881c52 Iustin Pop
# pylint: disable-msg=E1103
32 6c881c52 Iustin Pop
33 6c881c52 Iustin Pop
# E1103: %s %r has no %r member (but some types could not be
34 6c881c52 Iustin Pop
# inferred), because the _TryOSFromDisk returns either (True, os_obj)
35 6c881c52 Iustin Pop
# or (False, "string") which confuses pylint
36 6c881c52 Iustin Pop
37 a8083063 Iustin Pop
38 a8083063 Iustin Pop
import os
39 a8083063 Iustin Pop
import os.path
40 a8083063 Iustin Pop
import shutil
41 a8083063 Iustin Pop
import time
42 a8083063 Iustin Pop
import stat
43 a8083063 Iustin Pop
import errno
44 a8083063 Iustin Pop
import re
45 b544cfe0 Iustin Pop
import random
46 18682bca Iustin Pop
import logging
47 3b9e6a30 Iustin Pop
import tempfile
48 12bce260 Michael Hanselmann
import zlib
49 12bce260 Michael Hanselmann
import base64
50 a8083063 Iustin Pop
51 a8083063 Iustin Pop
from ganeti import errors
52 a8083063 Iustin Pop
from ganeti import utils
53 a8083063 Iustin Pop
from ganeti import ssh
54 a8083063 Iustin Pop
from ganeti import hypervisor
55 a8083063 Iustin Pop
from ganeti import constants
56 a8083063 Iustin Pop
from ganeti import bdev
57 a8083063 Iustin Pop
from ganeti import objects
58 880478f8 Iustin Pop
from ganeti import ssconf
59 a8083063 Iustin Pop
60 a8083063 Iustin Pop
61 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
62 714ea7ca Iustin Pop
_ALLOWED_CLEAN_DIRS = frozenset([
63 714ea7ca Iustin Pop
  constants.DATA_DIR,
64 714ea7ca Iustin Pop
  constants.JOB_QUEUE_ARCHIVE_DIR,
65 714ea7ca Iustin Pop
  constants.QUEUE_DIR,
66 714ea7ca Iustin Pop
  ])
67 13998ef2 Michael Hanselmann
68 13998ef2 Michael Hanselmann
69 2cc6781a Iustin Pop
class RPCFail(Exception):
70 2cc6781a Iustin Pop
  """Class denoting RPC failure.
71 2cc6781a Iustin Pop

72 2cc6781a Iustin Pop
  Its argument is the error message.
73 2cc6781a Iustin Pop

74 2cc6781a Iustin Pop
  """
75 2cc6781a Iustin Pop
76 13998ef2 Michael Hanselmann
77 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
78 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
79 2cc6781a Iustin Pop

80 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
81 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
82 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
83 2cc6781a Iustin Pop
  daemon.
84 2cc6781a Iustin Pop

85 2cc6781a Iustin Pop
  @type msg: string
86 2cc6781a Iustin Pop
  @param msg: the text of the exception
87 2cc6781a Iustin Pop
  @raise RPCFail
88 2cc6781a Iustin Pop

89 2cc6781a Iustin Pop
  """
90 2cc6781a Iustin Pop
  if args:
91 2cc6781a Iustin Pop
    msg = msg % args
92 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
93 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
94 afdc3985 Iustin Pop
      logging.exception(msg)
95 afdc3985 Iustin Pop
    else:
96 afdc3985 Iustin Pop
      logging.error(msg)
97 2cc6781a Iustin Pop
  raise RPCFail(msg)
98 2cc6781a Iustin Pop
99 2cc6781a Iustin Pop
100 c657dcc9 Michael Hanselmann
def _GetConfig():
101 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
102 10c2650b Iustin Pop

103 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
104 93384844 Iustin Pop
  @return: a SimpleStore instance
105 10c2650b Iustin Pop

106 10c2650b Iustin Pop
  """
107 93384844 Iustin Pop
  return ssconf.SimpleStore()
108 c657dcc9 Michael Hanselmann
109 c657dcc9 Michael Hanselmann
110 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
111 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
112 10c2650b Iustin Pop

113 10c2650b Iustin Pop
  @type cluster_name: str
114 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
115 10c2650b Iustin Pop
      by the SshRunner constructor
116 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
117 10c2650b Iustin Pop
  @return: an SshRunner instance
118 10c2650b Iustin Pop

119 10c2650b Iustin Pop
  """
120 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
121 c92b310a Michael Hanselmann
122 c92b310a Michael Hanselmann
123 12bce260 Michael Hanselmann
def _Decompress(data):
124 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
125 12bce260 Michael Hanselmann

126 12bce260 Michael Hanselmann
  @type data: list or tuple
127 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
128 12bce260 Michael Hanselmann
  @rtype: str
129 12bce260 Michael Hanselmann
  @return: Decompressed data
130 12bce260 Michael Hanselmann

131 12bce260 Michael Hanselmann
  """
132 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
133 12bce260 Michael Hanselmann
  assert len(data) == 2
134 12bce260 Michael Hanselmann
  (encoding, content) = data
135 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
136 12bce260 Michael Hanselmann
    return content
137 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
138 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
139 12bce260 Michael Hanselmann
  else:
140 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
141 12bce260 Michael Hanselmann
142 12bce260 Michael Hanselmann
143 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
144 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
145 76ab5558 Michael Hanselmann

146 10c2650b Iustin Pop
  @type path: str
147 10c2650b Iustin Pop
  @param path: the directory to clean
148 76ab5558 Michael Hanselmann
  @type exclude: list
149 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
150 10c2650b Iustin Pop
      to the empty list
151 76ab5558 Michael Hanselmann

152 76ab5558 Michael Hanselmann
  """
153 714ea7ca Iustin Pop
  if path not in _ALLOWED_CLEAN_DIRS:
154 714ea7ca Iustin Pop
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
155 714ea7ca Iustin Pop
          path)
156 714ea7ca Iustin Pop
157 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
158 3956cee1 Michael Hanselmann
    return
159 3bc6be5c Iustin Pop
  if exclude is None:
160 3bc6be5c Iustin Pop
    exclude = []
161 3bc6be5c Iustin Pop
  else:
162 3bc6be5c Iustin Pop
    # Normalize excluded paths
163 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
164 76ab5558 Michael Hanselmann
165 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
166 c4feafe8 Iustin Pop
    full_name = utils.PathJoin(path, rel_name)
167 76ab5558 Michael Hanselmann
    if full_name in exclude:
168 76ab5558 Michael Hanselmann
      continue
169 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
170 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
171 3956cee1 Michael Hanselmann
172 3956cee1 Michael Hanselmann
173 360b0dc2 Iustin Pop
def _BuildUploadFileList():
174 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
175 360b0dc2 Iustin Pop

176 360b0dc2 Iustin Pop
  This is abstracted so that it's built only once at module import time.
177 360b0dc2 Iustin Pop

178 360b0dc2 Iustin Pop
  """
179 b397a7d2 Iustin Pop
  allowed_files = set([
180 b397a7d2 Iustin Pop
    constants.CLUSTER_CONF_FILE,
181 b397a7d2 Iustin Pop
    constants.ETC_HOSTS,
182 b397a7d2 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
183 b397a7d2 Iustin Pop
    constants.VNC_PASSWORD_FILE,
184 b397a7d2 Iustin Pop
    constants.RAPI_CERT_FILE,
185 b397a7d2 Iustin Pop
    constants.RAPI_USERS_FILE,
186 6b7d5878 Michael Hanselmann
    constants.CONFD_HMAC_KEY,
187 b397a7d2 Iustin Pop
    ])
188 b397a7d2 Iustin Pop
189 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
190 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
191 b397a7d2 Iustin Pop
    allowed_files.update(hv_class.GetAncillaryFiles())
192 b397a7d2 Iustin Pop
193 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
194 360b0dc2 Iustin Pop
195 360b0dc2 Iustin Pop
196 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
197 360b0dc2 Iustin Pop
198 360b0dc2 Iustin Pop
199 1bc59f76 Michael Hanselmann
def JobQueuePurge():
200 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
201 10c2650b Iustin Pop

202 c8457ce7 Iustin Pop
  @rtype: tuple
203 c8457ce7 Iustin Pop
  @return: True, None
204 24fc781f Michael Hanselmann

205 24fc781f Michael Hanselmann
  """
206 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
207 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
208 24fc781f Michael Hanselmann
209 24fc781f Michael Hanselmann
210 bd1e4562 Iustin Pop
def GetMasterInfo():
211 bd1e4562 Iustin Pop
  """Returns master information.
212 bd1e4562 Iustin Pop

213 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
214 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
215 bd1e4562 Iustin Pop

216 bd1e4562 Iustin Pop
  @rtype: tuple
217 c26a6bd2 Iustin Pop
  @return: master_netdev, master_ip, master_name
218 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
219 b1b6ea87 Iustin Pop

220 b1b6ea87 Iustin Pop
  """
221 b1b6ea87 Iustin Pop
  try:
222 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
223 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
224 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
225 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
226 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
227 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
228 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
229 b1b6ea87 Iustin Pop
230 b1b6ea87 Iustin Pop
231 3583908a Guido Trotter
def StartMaster(start_daemons, no_voting):
232 a8083063 Iustin Pop
  """Activate local node as master node.
233 a8083063 Iustin Pop

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

238 10c2650b Iustin Pop
  @type start_daemons: boolean
239 c26a6bd2 Iustin Pop
  @param start_daemons: whether to also start the master
240 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
241 3583908a Guido Trotter
  @type no_voting: boolean
242 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
243 3583908a Guido Trotter
      (if start_daemons is True), but still non-interactively
244 10c2650b Iustin Pop
  @rtype: None
245 a8083063 Iustin Pop

246 a8083063 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 396b5733 Iustin Pop
  err_msgs = []
251 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
252 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
253 b1b6ea87 Iustin Pop
      # we already have the ip:
254 b726aff0 Iustin Pop
      logging.debug("Master IP already configured, doing nothing")
255 b1b6ea87 Iustin Pop
    else:
256 b726aff0 Iustin Pop
      msg = "Someone else has the master ip, not activating"
257 b726aff0 Iustin Pop
      logging.error(msg)
258 396b5733 Iustin Pop
      err_msgs.append(msg)
259 b1b6ea87 Iustin Pop
  else:
260 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
261 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
262 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
263 b1b6ea87 Iustin Pop
    if result.failed:
264 b726aff0 Iustin Pop
      msg = "Can't activate master IP: %s" % result.output
265 b726aff0 Iustin Pop
      logging.error(msg)
266 396b5733 Iustin Pop
      err_msgs.append(msg)
267 b1b6ea87 Iustin Pop
268 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
269 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
270 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
271 b1b6ea87 Iustin Pop
272 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
273 b1b6ea87 Iustin Pop
  if start_daemons:
274 3583908a Guido Trotter
    if no_voting:
275 f154a7a3 Michael Hanselmann
      masterd_args = "--no-voting --yes-do-it"
276 f154a7a3 Michael Hanselmann
    else:
277 f154a7a3 Michael Hanselmann
      masterd_args = ""
278 f154a7a3 Michael Hanselmann
279 f154a7a3 Michael Hanselmann
    env = {
280 f154a7a3 Michael Hanselmann
      "EXTRA_MASTERD_ARGS": masterd_args,
281 f154a7a3 Michael Hanselmann
      }
282 f154a7a3 Michael Hanselmann
283 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
284 f154a7a3 Michael Hanselmann
    if result.failed:
285 f154a7a3 Michael Hanselmann
      msg = "Can't start Ganeti master: %s" % result.output
286 f154a7a3 Michael Hanselmann
      logging.error(msg)
287 f154a7a3 Michael Hanselmann
      err_msgs.append(msg)
288 b726aff0 Iustin Pop
289 396b5733 Iustin Pop
  if err_msgs:
290 396b5733 Iustin Pop
    _Fail("; ".join(err_msgs))
291 afdc3985 Iustin Pop
292 a8083063 Iustin Pop
293 1c65840b Iustin Pop
def StopMaster(stop_daemons):
294 a8083063 Iustin Pop
  """Deactivate this node as master.
295 a8083063 Iustin Pop

296 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
297 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
298 10c2650b Iustin Pop
  stop_daemons parameter.
299 10c2650b Iustin Pop

300 10c2650b Iustin Pop
  @type stop_daemons: boolean
301 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
302 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
303 10c2650b Iustin Pop
  @rtype: None
304 a8083063 Iustin Pop

305 a8083063 Iustin Pop
  """
306 6c00d19a Iustin Pop
  # TODO: log and report back to the caller the error failures; we
307 6c00d19a Iustin Pop
  # need to decide in which case we fail the RPC for this
308 2a52a064 Iustin Pop
309 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
310 541741d3 Guido Trotter
  master_netdev, master_ip, _ = GetMasterInfo()
311 a8083063 Iustin Pop
312 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
313 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
314 a8083063 Iustin Pop
  if result.failed:
315 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
316 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
317 b1b6ea87 Iustin Pop
318 b1b6ea87 Iustin Pop
  if stop_daemons:
319 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
320 f154a7a3 Michael Hanselmann
    if result.failed:
321 f154a7a3 Michael Hanselmann
      logging.error("Could not stop Ganeti master, command %s had exitcode %s"
322 f154a7a3 Michael Hanselmann
                    " and error %s",
323 f154a7a3 Michael Hanselmann
                    result.cmd, result.exit_code, result.output)
324 a8083063 Iustin Pop
325 a8083063 Iustin Pop
326 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
327 7900ed01 Iustin Pop
  """Joins this node to the cluster.
328 a8083063 Iustin Pop

329 7900ed01 Iustin Pop
  This does the following:
330 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
331 7900ed01 Iustin Pop
      - adds the ssh private key to the user
332 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
333 a8083063 Iustin Pop

334 10c2650b Iustin Pop
  @type dsa: str
335 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
336 10c2650b Iustin Pop
  @type dsapub: str
337 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
338 10c2650b Iustin Pop
  @type rsa: str
339 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
340 10c2650b Iustin Pop
  @type rsapub: str
341 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
342 10c2650b Iustin Pop
  @type sshkey: str
343 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
344 10c2650b Iustin Pop
  @type sshpub: str
345 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
346 10c2650b Iustin Pop
  @rtype: boolean
347 10c2650b Iustin Pop
  @return: the success of the operation
348 10c2650b Iustin Pop

349 7900ed01 Iustin Pop
  """
350 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
351 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
352 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
353 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
354 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
355 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
356 a8083063 Iustin Pop
357 70d9e3d8 Iustin Pop
  try:
358 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
359 70d9e3d8 Iustin Pop
                                                    mkdir=True)
360 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
361 2cc6781a Iustin Pop
    _Fail("Error while processing user ssh files: %s", err, exc=True)
362 a8083063 Iustin Pop
363 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
364 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
365 a8083063 Iustin Pop
366 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
367 a8083063 Iustin Pop
368 7e1fac25 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "reload-ssh-keys"])
369 7e1fac25 Michael Hanselmann
  if result.failed:
370 7e1fac25 Michael Hanselmann
    _Fail("Unable to reload SSH keys (command %r, exit code %s, output %r)",
371 7e1fac25 Michael Hanselmann
          result.cmd, result.exit_code, result.output)
372 a8083063 Iustin Pop
373 a8083063 Iustin Pop
374 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
375 10c2650b Iustin Pop
  """Cleans up and remove the current node.
376 10c2650b Iustin Pop

377 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
378 10c2650b Iustin Pop
  from the cluster.
379 10c2650b Iustin Pop

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

384 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
385 b989b9d9 Ken Wehr

386 a8083063 Iustin Pop
  """
387 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
388 1bc59f76 Michael Hanselmann
  JobQueuePurge()
389 f78346f5 Michael Hanselmann
390 b989b9d9 Ken Wehr
  if modify_ssh_setup:
391 b989b9d9 Ken Wehr
    try:
392 b989b9d9 Ken Wehr
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
393 7900ed01 Iustin Pop
394 b989b9d9 Ken Wehr
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
395 a8083063 Iustin Pop
396 b989b9d9 Ken Wehr
      utils.RemoveFile(priv_key)
397 b989b9d9 Ken Wehr
      utils.RemoveFile(pub_key)
398 b989b9d9 Ken Wehr
    except errors.OpExecError:
399 b989b9d9 Ken Wehr
      logging.exception("Error while processing ssh files")
400 a8083063 Iustin Pop
401 ed008420 Guido Trotter
  try:
402 6b7d5878 Michael Hanselmann
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
403 ed008420 Guido Trotter
    utils.RemoveFile(constants.RAPI_CERT_FILE)
404 168c1de2 Michael Hanselmann
    utils.RemoveFile(constants.NODED_CERT_FILE)
405 7260cfbe Iustin Pop
  except: # pylint: disable-msg=W0702
406 ed008420 Guido Trotter
    logging.exception("Error while removing cluster secrets")
407 ed008420 Guido Trotter
408 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
409 f154a7a3 Michael Hanselmann
  if result.failed:
410 f154a7a3 Michael Hanselmann
    logging.error("Command %s failed with exitcode %s and error %s",
411 f154a7a3 Michael Hanselmann
                  result.cmd, result.exit_code, result.output)
412 ed008420 Guido Trotter
413 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
414 0623d351 Iustin Pop
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
415 6d8b6238 Guido Trotter
416 a8083063 Iustin Pop
417 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
418 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
419 a8083063 Iustin Pop

420 e69d05fd Iustin Pop
  @type vgname: C{string}
421 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
422 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
423 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
424 e69d05fd Iustin Pop
      memory information
425 e69d05fd Iustin Pop
  @rtype: C{dict}
426 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
427 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
428 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
429 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
430 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
431 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
432 a8083063 Iustin Pop

433 098c0958 Michael Hanselmann
  """
434 a8083063 Iustin Pop
  outputarray = {}
435 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
436 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
437 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
438 a8083063 Iustin Pop
439 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
440 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
441 a8083063 Iustin Pop
  if hyp_info is not None:
442 a8083063 Iustin Pop
    outputarray.update(hyp_info)
443 a8083063 Iustin Pop
444 13998ef2 Michael Hanselmann
  outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
445 3ef10550 Michael Hanselmann
446 c26a6bd2 Iustin Pop
  return outputarray
447 a8083063 Iustin Pop
448 a8083063 Iustin Pop
449 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
450 a8083063 Iustin Pop
  """Verify the status of the local node.
451 a8083063 Iustin Pop

452 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
453 e69d05fd Iustin Pop
  local node.
454 e69d05fd Iustin Pop

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

458 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
459 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
460 e69d05fd Iustin Pop
  report).
461 a8083063 Iustin Pop

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

466 e69d05fd Iustin Pop
  @type what: C{dict}
467 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
468 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
469 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
470 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
471 e69d05fd Iustin Pop
        connectivity with
472 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
473 10c2650b Iustin Pop
  @rtype: dict
474 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
475 10c2650b Iustin Pop
      values representing the result of the checks
476 a8083063 Iustin Pop

477 a8083063 Iustin Pop
  """
478 a8083063 Iustin Pop
  result = {}
479 a8083063 Iustin Pop
480 25361b9a Iustin Pop
  if constants.NV_HYPERVISOR in what:
481 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
482 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
483 0cf5e7f5 Iustin Pop
      try:
484 0cf5e7f5 Iustin Pop
        val = hypervisor.GetHypervisor(hv_name).Verify()
485 0cf5e7f5 Iustin Pop
      except errors.HypervisorError, err:
486 0cf5e7f5 Iustin Pop
        val = "Error while checking hypervisor: %s" % str(err)
487 0cf5e7f5 Iustin Pop
      tmp[hv_name] = val
488 25361b9a Iustin Pop
489 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
490 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
491 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
492 25361b9a Iustin Pop
493 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
494 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
495 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
496 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
497 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
498 a8083063 Iustin Pop
      if not success:
499 25361b9a Iustin Pop
        tmp[node] = message
500 25361b9a Iustin Pop
501 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
502 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
503 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
504 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
505 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
506 9d4bfc96 Iustin Pop
      if name == my_name:
507 9d4bfc96 Iustin Pop
        my_pip = pip
508 9d4bfc96 Iustin Pop
        my_sip = sip
509 9d4bfc96 Iustin Pop
        break
510 9d4bfc96 Iustin Pop
    if not my_pip:
511 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
512 25361b9a Iustin Pop
                      " in the node list")
513 9d4bfc96 Iustin Pop
    else:
514 cd50653c Guido Trotter
      port = utils.GetDaemonPort(constants.NODED)
515 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
516 9d4bfc96 Iustin Pop
        fail = []
517 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
518 9d4bfc96 Iustin Pop
          fail.append("primary")
519 9d4bfc96 Iustin Pop
        if sip != pip:
520 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
521 9d4bfc96 Iustin Pop
            fail.append("secondary")
522 9d4bfc96 Iustin Pop
        if fail:
523 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
524 25361b9a Iustin Pop
                       " and ".join(fail))
525 25361b9a Iustin Pop
526 25361b9a Iustin Pop
  if constants.NV_LVLIST in what:
527 ed904904 Iustin Pop
    try:
528 ed904904 Iustin Pop
      val = GetVolumeList(what[constants.NV_LVLIST])
529 ed904904 Iustin Pop
    except RPCFail, err:
530 ed904904 Iustin Pop
      val = str(err)
531 ed904904 Iustin Pop
    result[constants.NV_LVLIST] = val
532 25361b9a Iustin Pop
533 25361b9a Iustin Pop
  if constants.NV_INSTANCELIST in what:
534 0cf5e7f5 Iustin Pop
    # GetInstanceList can fail
535 0cf5e7f5 Iustin Pop
    try:
536 0cf5e7f5 Iustin Pop
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
537 0cf5e7f5 Iustin Pop
    except RPCFail, err:
538 0cf5e7f5 Iustin Pop
      val = str(err)
539 0cf5e7f5 Iustin Pop
    result[constants.NV_INSTANCELIST] = val
540 25361b9a Iustin Pop
541 25361b9a Iustin Pop
  if constants.NV_VGLIST in what:
542 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
543 25361b9a Iustin Pop
544 d091393e Iustin Pop
  if constants.NV_PVLIST in what:
545 d091393e Iustin Pop
    result[constants.NV_PVLIST] = \
546 d091393e Iustin Pop
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
547 d091393e Iustin Pop
                                   filter_allocatable=False)
548 d091393e Iustin Pop
549 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
550 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
551 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
552 25361b9a Iustin Pop
553 25361b9a Iustin Pop
  if constants.NV_HVINFO in what:
554 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
555 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
556 9d4bfc96 Iustin Pop
557 6d2e83d5 Iustin Pop
  if constants.NV_DRBDLIST in what:
558 6d2e83d5 Iustin Pop
    try:
559 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
560 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
561 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
562 f6eaed12 Iustin Pop
      used_minors = str(err)
563 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
564 6d2e83d5 Iustin Pop
565 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
566 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
567 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
568 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
569 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
570 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
571 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
572 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
573 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
574 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
575 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
576 313b2dd4 Michael Hanselmann
577 313b2dd4 Michael Hanselmann
  if constants.NV_TIME in what:
578 313b2dd4 Michael Hanselmann
    result[constants.NV_TIME] = utils.SplitTime(time.time())
579 313b2dd4 Michael Hanselmann
580 c26a6bd2 Iustin Pop
  return result
581 a8083063 Iustin Pop
582 a8083063 Iustin Pop
583 a8083063 Iustin Pop
def GetVolumeList(vg_name):
584 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
585 a8083063 Iustin Pop

586 10c2650b Iustin Pop
  @type vg_name: str
587 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
588 10c2650b Iustin Pop
  @rtype: dict
589 10c2650b Iustin Pop
  @return:
590 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
591 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
592 10c2650b Iustin Pop

593 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
594 10c2650b Iustin Pop

595 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
596 10c2650b Iustin Pop
      details.
597 a8083063 Iustin Pop

598 a8083063 Iustin Pop
  """
599 cb2037a2 Iustin Pop
  lvs = {}
600 cb2037a2 Iustin Pop
  sep = '|'
601 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
602 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
603 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
604 a8083063 Iustin Pop
  if result.failed:
605 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
606 cb2037a2 Iustin Pop
607 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
608 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
609 df4c2628 Iustin Pop
    line = line.strip()
610 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
611 df4c2628 Iustin Pop
    if not match:
612 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
613 df4c2628 Iustin Pop
      continue
614 df4c2628 Iustin Pop
    name, size, attr = match.groups()
615 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
616 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
617 33f2a81a Iustin Pop
    virtual = attr[0] == 'v'
618 33f2a81a Iustin Pop
    if virtual:
619 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
620 33f2a81a Iustin Pop
      # don't really hold data
621 33f2a81a Iustin Pop
      continue
622 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
623 cb2037a2 Iustin Pop
624 cb2037a2 Iustin Pop
  return lvs
625 a8083063 Iustin Pop
626 a8083063 Iustin Pop
627 a8083063 Iustin Pop
def ListVolumeGroups():
628 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
629 a8083063 Iustin Pop

630 10c2650b Iustin Pop
  @rtype: dict
631 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
632 10c2650b Iustin Pop
      size of the volume
633 a8083063 Iustin Pop

634 a8083063 Iustin Pop
  """
635 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
636 a8083063 Iustin Pop
637 a8083063 Iustin Pop
638 dcb93971 Michael Hanselmann
def NodeVolumes():
639 dcb93971 Michael Hanselmann
  """List all volumes on this node.
640 dcb93971 Michael Hanselmann

641 10c2650b Iustin Pop
  @rtype: list
642 10c2650b Iustin Pop
  @return:
643 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
644 10c2650b Iustin Pop
      - name: the logical volume name,
645 10c2650b Iustin Pop
      - size: the size of the logical volume
646 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
647 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
648 10c2650b Iustin Pop

649 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
650 10c2650b Iustin Pop
    error.
651 10c2650b Iustin Pop

652 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
653 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
654 10c2650b Iustin Pop
    multiple times.
655 10c2650b Iustin Pop

656 dcb93971 Michael Hanselmann
  """
657 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
658 dcb93971 Michael Hanselmann
                         "--separator=|",
659 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
660 dcb93971 Michael Hanselmann
  if result.failed:
661 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
662 10bfe6cb Iustin Pop
          result.output)
663 dcb93971 Michael Hanselmann
664 dcb93971 Michael Hanselmann
  def parse_dev(dev):
665 89e5ab02 Iustin Pop
    return dev.split('(')[0]
666 89e5ab02 Iustin Pop
667 89e5ab02 Iustin Pop
  def handle_dev(dev):
668 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
669 dcb93971 Michael Hanselmann
670 dcb93971 Michael Hanselmann
  def map_line(line):
671 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
672 89e5ab02 Iustin Pop
    return [{'name': line[0], 'size': line[1],
673 89e5ab02 Iustin Pop
             'dev': dev, 'vg': line[3]} for dev in handle_dev(line[2])]
674 89e5ab02 Iustin Pop
675 89e5ab02 Iustin Pop
  all_devs = []
676 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
677 89e5ab02 Iustin Pop
    if line.count('|') >= 3:
678 89e5ab02 Iustin Pop
      all_devs.extend(map_line(line.split('|')))
679 89e5ab02 Iustin Pop
    else:
680 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
681 89e5ab02 Iustin Pop
  return all_devs
682 dcb93971 Michael Hanselmann
683 dcb93971 Michael Hanselmann
684 a8083063 Iustin Pop
def BridgesExist(bridges_list):
685 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
686 a8083063 Iustin Pop

687 b1206984 Iustin Pop
  @rtype: boolean
688 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
689 a8083063 Iustin Pop

690 a8083063 Iustin Pop
  """
691 35c0c8da Iustin Pop
  missing = []
692 a8083063 Iustin Pop
  for bridge in bridges_list:
693 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
694 35c0c8da Iustin Pop
      missing.append(bridge)
695 a8083063 Iustin Pop
696 35c0c8da Iustin Pop
  if missing:
697 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
698 35c0c8da Iustin Pop
699 a8083063 Iustin Pop
700 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
701 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
702 a8083063 Iustin Pop

703 e69d05fd Iustin Pop
  @type hypervisor_list: list
704 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
705 e69d05fd Iustin Pop

706 e69d05fd Iustin Pop
  @rtype: list
707 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
708 10c2650b Iustin Pop
    - instance1.example.com
709 10c2650b Iustin Pop
    - instance2.example.com
710 a8083063 Iustin Pop

711 098c0958 Michael Hanselmann
  """
712 e69d05fd Iustin Pop
  results = []
713 e69d05fd Iustin Pop
  for hname in hypervisor_list:
714 e69d05fd Iustin Pop
    try:
715 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
716 e69d05fd Iustin Pop
      results.extend(names)
717 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
718 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
719 aca13712 Iustin Pop
            hname, err, exc=True)
720 a8083063 Iustin Pop
721 e69d05fd Iustin Pop
  return results
722 a8083063 Iustin Pop
723 a8083063 Iustin Pop
724 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
725 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
726 a8083063 Iustin Pop

727 e69d05fd Iustin Pop
  @type instance: string
728 e69d05fd Iustin Pop
  @param instance: the instance name
729 e69d05fd Iustin Pop
  @type hname: string
730 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
731 a8083063 Iustin Pop

732 e69d05fd Iustin Pop
  @rtype: dict
733 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
734 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
735 e69d05fd Iustin Pop
      - state: xen state of instance (string)
736 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
737 a8083063 Iustin Pop

738 098c0958 Michael Hanselmann
  """
739 a8083063 Iustin Pop
  output = {}
740 a8083063 Iustin Pop
741 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
742 a8083063 Iustin Pop
  if iinfo is not None:
743 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
744 a8083063 Iustin Pop
    output['state'] = iinfo[4]
745 a8083063 Iustin Pop
    output['time'] = iinfo[5]
746 a8083063 Iustin Pop
747 c26a6bd2 Iustin Pop
  return output
748 a8083063 Iustin Pop
749 a8083063 Iustin Pop
750 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
751 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
752 56e7640c Iustin Pop

753 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
754 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
755 56e7640c Iustin Pop

756 56e7640c Iustin Pop
  @rtype: tuple
757 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
758 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
759 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
760 56e7640c Iustin Pop

761 56e7640c Iustin Pop
  """
762 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
763 afdc3985 Iustin Pop
  iname = instance.name
764 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
765 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
766 56e7640c Iustin Pop
767 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
768 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
769 56e7640c Iustin Pop
    if not os.path.islink(link_name):
770 afdc3985 Iustin Pop
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
771 56e7640c Iustin Pop
772 56e7640c Iustin Pop
773 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
774 a8083063 Iustin Pop
  """Gather data about all instances.
775 a8083063 Iustin Pop

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

780 e69d05fd Iustin Pop
  @type hypervisor_list: list
781 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
782 e69d05fd Iustin Pop

783 955db481 Guido Trotter
  @rtype: dict
784 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
785 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
786 e69d05fd Iustin Pop
      - state: xen state of instance (string)
787 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
788 10c2650b Iustin Pop
      - vcpus: the number of vcpus
789 a8083063 Iustin Pop

790 098c0958 Michael Hanselmann
  """
791 a8083063 Iustin Pop
  output = {}
792 a8083063 Iustin Pop
793 e69d05fd Iustin Pop
  for hname in hypervisor_list:
794 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
795 e69d05fd Iustin Pop
    if iinfo:
796 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
797 f23b5ae8 Iustin Pop
        value = {
798 e69d05fd Iustin Pop
          'memory': memory,
799 e69d05fd Iustin Pop
          'vcpus': vcpus,
800 e69d05fd Iustin Pop
          'state': state,
801 e69d05fd Iustin Pop
          'time': times,
802 e69d05fd Iustin Pop
          }
803 b33b6f55 Iustin Pop
        if name in output:
804 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
805 b33b6f55 Iustin Pop
          # and not state and time which can change between the
806 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
807 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
808 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
809 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
810 2fa74ef4 Iustin Pop
                    " with different parameters", name)
811 f23b5ae8 Iustin Pop
        output[name] = value
812 a8083063 Iustin Pop
813 c26a6bd2 Iustin Pop
  return output
814 a8083063 Iustin Pop
815 a8083063 Iustin Pop
816 81a3406c Iustin Pop
def _InstanceLogName(kind, os_name, instance):
817 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
818 81a3406c Iustin Pop

819 81a3406c Iustin Pop
  The instance name and os name are passed in as strings since not all
820 81a3406c Iustin Pop
  operations have these as part of an instance object.
821 81a3406c Iustin Pop

822 81a3406c Iustin Pop
  @type kind: string
823 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
824 81a3406c Iustin Pop
  @type os_name: string
825 81a3406c Iustin Pop
  @param os_name: the os name
826 81a3406c Iustin Pop
  @type instance: string
827 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
828 81a3406c Iustin Pop

829 81a3406c Iustin Pop
  """
830 1d466a4f Michael Hanselmann
  base = ("%s-%s-%s-%s.log" %
831 1d466a4f Michael Hanselmann
          (kind, os_name, instance, utils.TimestampForFilename()))
832 81a3406c Iustin Pop
  return utils.PathJoin(constants.LOG_OS_DIR, base)
833 81a3406c Iustin Pop
834 81a3406c Iustin Pop
835 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
836 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
837 a8083063 Iustin Pop

838 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
839 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
840 e557bae9 Guido Trotter
  @type reinstall: boolean
841 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
842 4a0e011f Iustin Pop
  @type debug: integer
843 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
844 c26a6bd2 Iustin Pop
  @rtype: None
845 a8083063 Iustin Pop

846 a8083063 Iustin Pop
  """
847 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
848 255dcebd Iustin Pop
849 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
850 e557bae9 Guido Trotter
  if reinstall:
851 e557bae9 Guido Trotter
    create_env['INSTANCE_REINSTALL'] = "1"
852 a8083063 Iustin Pop
853 81a3406c Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name)
854 decd5f45 Iustin Pop
855 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
856 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
857 decd5f45 Iustin Pop
  if result.failed:
858 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
859 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
860 18682bca Iustin Pop
                  result.output)
861 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
862 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
863 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
864 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
865 decd5f45 Iustin Pop
866 decd5f45 Iustin Pop
867 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
868 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
869 decd5f45 Iustin Pop

870 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
871 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
872 d15a9ad3 Guido Trotter
  @type old_name: string
873 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
874 4a0e011f Iustin Pop
  @type debug: integer
875 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
876 10c2650b Iustin Pop
  @rtype: boolean
877 10c2650b Iustin Pop
  @return: the success of the operation
878 decd5f45 Iustin Pop

879 decd5f45 Iustin Pop
  """
880 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
881 decd5f45 Iustin Pop
882 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
883 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
884 decd5f45 Iustin Pop
885 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
886 81a3406c Iustin Pop
                             "%s-%s" % (old_name, instance.name))
887 a8083063 Iustin Pop
888 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
889 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
890 a8083063 Iustin Pop
891 a8083063 Iustin Pop
  if result.failed:
892 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
893 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
894 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
895 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
896 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
897 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
898 a8083063 Iustin Pop
899 a8083063 Iustin Pop
900 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
901 5bbd3f7f Michael Hanselmann
  """Get information about the volume group.
902 a8083063 Iustin Pop

903 10c2650b Iustin Pop
  @type vg_name: str
904 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
905 10c2650b Iustin Pop
  @rtype: dict
906 10c2650b Iustin Pop
  @return:
907 10c2650b Iustin Pop
    A dictionary with the following keys:
908 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
909 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
910 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
911 a8083063 Iustin Pop

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

915 a8083063 Iustin Pop
  """
916 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
917 f4d377e7 Iustin Pop
918 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
919 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
920 a8083063 Iustin Pop
921 a8083063 Iustin Pop
  if retval.failed:
922 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
923 f4d377e7 Iustin Pop
    return retdic
924 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
925 f4d377e7 Iustin Pop
  if len(valarr) == 3:
926 f4d377e7 Iustin Pop
    try:
927 f4d377e7 Iustin Pop
      retdic = {
928 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
929 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
930 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
931 f4d377e7 Iustin Pop
        }
932 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
933 29921401 Iustin Pop
      logging.exception("Fail to parse vgs output: %s", err)
934 f4d377e7 Iustin Pop
  else:
935 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
936 18682bca Iustin Pop
                  " three): %s", str(valarr))
937 a8083063 Iustin Pop
  return retdic
938 a8083063 Iustin Pop
939 a8083063 Iustin Pop
940 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
941 c4feafe8 Iustin Pop
  return utils.PathJoin(constants.DISK_LINKS_DIR,
942 c4feafe8 Iustin Pop
                        "%s:%d" % (instance_name, idx))
943 5282084b Iustin Pop
944 5282084b Iustin Pop
945 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
946 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
947 9332fd8a Iustin Pop

948 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
949 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
950 9332fd8a Iustin Pop

951 9332fd8a Iustin Pop

952 5282084b Iustin Pop
  @param instance_name: the name of the target instance
953 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
954 5282084b Iustin Pop
  @param idx: the disk index
955 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
956 9332fd8a Iustin Pop

957 9332fd8a Iustin Pop
  """
958 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
959 9332fd8a Iustin Pop
  try:
960 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
961 5282084b Iustin Pop
  except OSError, err:
962 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
963 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
964 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
965 9332fd8a Iustin Pop
        os.remove(link_name)
966 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
967 9332fd8a Iustin Pop
    else:
968 9332fd8a Iustin Pop
      raise
969 9332fd8a Iustin Pop
970 9332fd8a Iustin Pop
  return link_name
971 9332fd8a Iustin Pop
972 9332fd8a Iustin Pop
973 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
974 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
975 3c9c571d Iustin Pop

976 3c9c571d Iustin Pop
  """
977 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
978 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
979 5282084b Iustin Pop
    if os.path.islink(link_name):
980 3c9c571d Iustin Pop
      try:
981 03dfa658 Iustin Pop
        os.remove(link_name)
982 03dfa658 Iustin Pop
      except OSError:
983 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
984 3c9c571d Iustin Pop
985 3c9c571d Iustin Pop
986 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
987 a8083063 Iustin Pop
  """Set up an instance's block device(s).
988 a8083063 Iustin Pop

989 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
990 a8083063 Iustin Pop
  devices must be already assembled.
991 a8083063 Iustin Pop

992 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
993 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
994 069cfbf1 Iustin Pop
  @rtype: list
995 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
996 10c2650b Iustin Pop

997 a8083063 Iustin Pop
  """
998 a8083063 Iustin Pop
  block_devices = []
999 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1000 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1001 a8083063 Iustin Pop
    if device is None:
1002 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1003 a8083063 Iustin Pop
                                    str(disk))
1004 a8083063 Iustin Pop
    device.Open()
1005 9332fd8a Iustin Pop
    try:
1006 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1007 9332fd8a Iustin Pop
    except OSError, e:
1008 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1009 9332fd8a Iustin Pop
                                    e.strerror)
1010 9332fd8a Iustin Pop
1011 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1012 9332fd8a Iustin Pop
1013 a8083063 Iustin Pop
  return block_devices
1014 a8083063 Iustin Pop
1015 a8083063 Iustin Pop
1016 07813a9e Iustin Pop
def StartInstance(instance):
1017 a8083063 Iustin Pop
  """Start an instance.
1018 a8083063 Iustin Pop

1019 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1020 e69d05fd Iustin Pop
  @param instance: the instance object
1021 c26a6bd2 Iustin Pop
  @rtype: None
1022 a8083063 Iustin Pop

1023 098c0958 Michael Hanselmann
  """
1024 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1025 a8083063 Iustin Pop
1026 a8083063 Iustin Pop
  if instance.name in running_instances:
1027 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1028 c26a6bd2 Iustin Pop
    return
1029 a8083063 Iustin Pop
1030 a8083063 Iustin Pop
  try:
1031 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1032 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1033 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
1034 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1035 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1036 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1037 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1038 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1039 a8083063 Iustin Pop
1040 a8083063 Iustin Pop
1041 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1042 a8083063 Iustin Pop
  """Shut an instance down.
1043 a8083063 Iustin Pop

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

1046 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1047 e69d05fd Iustin Pop
  @param instance: the instance object
1048 6263189c Guido Trotter
  @type timeout: integer
1049 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1050 c26a6bd2 Iustin Pop
  @rtype: None
1051 a8083063 Iustin Pop

1052 098c0958 Michael Hanselmann
  """
1053 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1054 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1055 c26a6bd2 Iustin Pop
  iname = instance.name
1056 a8083063 Iustin Pop
1057 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1058 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1059 c26a6bd2 Iustin Pop
    return
1060 a8083063 Iustin Pop
1061 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1062 3c0cdc83 Michael Hanselmann
    def __init__(self):
1063 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1064 a8083063 Iustin Pop
1065 3c0cdc83 Michael Hanselmann
    def __call__(self):
1066 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1067 3c0cdc83 Michael Hanselmann
        return
1068 3c0cdc83 Michael Hanselmann
1069 3c0cdc83 Michael Hanselmann
      try:
1070 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1071 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1072 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1073 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1074 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1075 3c0cdc83 Michael Hanselmann
          return
1076 3c0cdc83 Michael Hanselmann
1077 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1078 3c0cdc83 Michael Hanselmann
1079 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1080 3c0cdc83 Michael Hanselmann
1081 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1082 3c0cdc83 Michael Hanselmann
1083 3c0cdc83 Michael Hanselmann
  try:
1084 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1085 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1086 a8083063 Iustin Pop
    # the shutdown did not succeed
1087 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1088 a8083063 Iustin Pop
1089 a8083063 Iustin Pop
    try:
1090 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1091 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1092 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1093 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1094 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1095 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1096 a8083063 Iustin Pop
1097 a8083063 Iustin Pop
    time.sleep(1)
1098 3c0cdc83 Michael Hanselmann
1099 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1100 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1101 3c9c571d Iustin Pop
1102 f28ec899 Guido Trotter
  try:
1103 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1104 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1105 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1106 f28ec899 Guido Trotter
1107 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1108 a8083063 Iustin Pop
1109 a8083063 Iustin Pop
1110 17c3f802 Guido Trotter
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1111 007a2f3e Alexander Schreiber
  """Reboot an instance.
1112 007a2f3e Alexander Schreiber

1113 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1114 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1115 10c2650b Iustin Pop
  @type reboot_type: str
1116 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1117 10c2650b Iustin Pop
    constants:
1118 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1119 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1120 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1121 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1122 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1123 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1124 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1125 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1126 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1127 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1128 c26a6bd2 Iustin Pop
  @rtype: None
1129 007a2f3e Alexander Schreiber

1130 007a2f3e Alexander Schreiber
  """
1131 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1132 007a2f3e Alexander Schreiber
1133 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1134 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1135 007a2f3e Alexander Schreiber
1136 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1137 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1138 007a2f3e Alexander Schreiber
    try:
1139 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1140 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1141 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1142 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1143 007a2f3e Alexander Schreiber
    try:
1144 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1145 07813a9e Iustin Pop
      return StartInstance(instance)
1146 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1147 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1148 007a2f3e Alexander Schreiber
  else:
1149 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1150 007a2f3e Alexander Schreiber
1151 007a2f3e Alexander Schreiber
1152 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1153 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1154 6906a9d8 Guido Trotter

1155 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1156 6906a9d8 Guido Trotter
  @param instance: the instance definition
1157 6906a9d8 Guido Trotter

1158 6906a9d8 Guido Trotter
  """
1159 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1160 cd42d0ad Guido Trotter
  try:
1161 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1162 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1163 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1164 c26a6bd2 Iustin Pop
  return info
1165 6906a9d8 Guido Trotter
1166 6906a9d8 Guido Trotter
1167 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1168 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1169 6906a9d8 Guido Trotter

1170 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1171 6906a9d8 Guido Trotter
  @param instance: the instance definition
1172 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1173 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1174 6906a9d8 Guido Trotter
  @type target: string
1175 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1176 6906a9d8 Guido Trotter

1177 6906a9d8 Guido Trotter
  """
1178 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1179 cd42d0ad Guido Trotter
  try:
1180 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1181 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1182 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1183 6906a9d8 Guido Trotter
1184 6906a9d8 Guido Trotter
1185 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1186 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1187 6906a9d8 Guido Trotter

1188 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1189 6906a9d8 Guido Trotter
  @param instance: the instance definition
1190 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1191 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1192 6906a9d8 Guido Trotter
  @type success: boolean
1193 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1194 6906a9d8 Guido Trotter

1195 6906a9d8 Guido Trotter
  """
1196 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1197 cd42d0ad Guido Trotter
  try:
1198 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1199 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1200 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1201 6906a9d8 Guido Trotter
1202 6906a9d8 Guido Trotter
1203 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1204 2a10865c Iustin Pop
  """Migrates an instance to another node.
1205 2a10865c Iustin Pop

1206 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1207 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1208 9f0e6b37 Iustin Pop
  @type target: string
1209 9f0e6b37 Iustin Pop
  @param target: the target node name
1210 9f0e6b37 Iustin Pop
  @type live: boolean
1211 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1212 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1213 9f0e6b37 Iustin Pop
  @rtype: tuple
1214 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1215 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1216 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1217 9f0e6b37 Iustin Pop

1218 2a10865c Iustin Pop
  """
1219 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1220 2a10865c Iustin Pop
1221 2a10865c Iustin Pop
  try:
1222 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1223 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1224 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1225 2a10865c Iustin Pop
1226 2a10865c Iustin Pop
1227 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1228 a8083063 Iustin Pop
  """Creates a block device for an instance.
1229 a8083063 Iustin Pop

1230 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1231 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1232 b1206984 Iustin Pop
  @type size: int
1233 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1234 b1206984 Iustin Pop
  @type owner: str
1235 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1236 b1206984 Iustin Pop
      used for device cache data
1237 b1206984 Iustin Pop
  @type on_primary: boolean
1238 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1239 b1206984 Iustin Pop
  @type info: string
1240 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1241 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1242 b1206984 Iustin Pop

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

1247 a8083063 Iustin Pop
  """
1248 7260cfbe Iustin Pop
  # TODO: remove the obsolete 'size' argument
1249 7260cfbe Iustin Pop
  # pylint: disable-msg=W0613
1250 a8083063 Iustin Pop
  clist = []
1251 a8083063 Iustin Pop
  if disk.children:
1252 a8083063 Iustin Pop
    for child in disk.children:
1253 1063abd1 Iustin Pop
      try:
1254 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1255 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1256 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1257 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1258 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1259 a8083063 Iustin Pop
        # be assembled
1260 1063abd1 Iustin Pop
        try:
1261 fe267188 Iustin Pop
          # pylint: disable-msg=E1103
1262 1063abd1 Iustin Pop
          crdev.Open()
1263 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1264 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1265 a8083063 Iustin Pop
      clist.append(crdev)
1266 a8083063 Iustin Pop
1267 dab69e97 Iustin Pop
  try:
1268 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1269 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1270 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1271 6c626518 Iustin Pop
1272 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1273 1063abd1 Iustin Pop
    try:
1274 1063abd1 Iustin Pop
      device.Assemble()
1275 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1276 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1277 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1278 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1279 1063abd1 Iustin Pop
      try:
1280 1063abd1 Iustin Pop
        device.Open(force=True)
1281 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1282 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1283 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1284 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1285 a0c3fea1 Michael Hanselmann
1286 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1287 a0c3fea1 Michael Hanselmann
1288 c26a6bd2 Iustin Pop
  return device.unique_id
1289 a8083063 Iustin Pop
1290 a8083063 Iustin Pop
1291 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1292 a8083063 Iustin Pop
  """Remove a block device.
1293 a8083063 Iustin Pop

1294 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1295 10c2650b Iustin Pop

1296 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1297 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1298 10c2650b Iustin Pop
  @rtype: boolean
1299 10c2650b Iustin Pop
  @return: the success of the operation
1300 a8083063 Iustin Pop

1301 a8083063 Iustin Pop
  """
1302 e1bc0878 Iustin Pop
  msgs = []
1303 a8083063 Iustin Pop
  try:
1304 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1305 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1306 a8083063 Iustin Pop
    # probably can't attach
1307 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1308 a8083063 Iustin Pop
    rdev = None
1309 a8083063 Iustin Pop
  if rdev is not None:
1310 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1311 e1bc0878 Iustin Pop
    try:
1312 0c6c04ec Iustin Pop
      rdev.Remove()
1313 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1314 e1bc0878 Iustin Pop
      msgs.append(str(err))
1315 c26a6bd2 Iustin Pop
    if not msgs:
1316 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1317 e1bc0878 Iustin Pop
1318 a8083063 Iustin Pop
  if disk.children:
1319 a8083063 Iustin Pop
    for child in disk.children:
1320 c26a6bd2 Iustin Pop
      try:
1321 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1322 c26a6bd2 Iustin Pop
      except RPCFail, err:
1323 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1324 e1bc0878 Iustin Pop
1325 c26a6bd2 Iustin Pop
  if msgs:
1326 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1327 afdc3985 Iustin Pop
1328 a8083063 Iustin Pop
1329 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1330 a8083063 Iustin Pop
  """Activate a block device for an instance.
1331 a8083063 Iustin Pop

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

1334 10c2650b Iustin Pop
  @note: this function is called recursively.
1335 a8083063 Iustin Pop

1336 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1337 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1338 10c2650b Iustin Pop
  @type owner: str
1339 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1340 10c2650b Iustin Pop
  @type as_primary: boolean
1341 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1342 10c2650b Iustin Pop
      read/write
1343 a8083063 Iustin Pop

1344 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1345 10c2650b Iustin Pop
      was assembled)
1346 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1347 10c2650b Iustin Pop
      during the activation of the children or the device
1348 10c2650b Iustin Pop
      itself
1349 a8083063 Iustin Pop

1350 a8083063 Iustin Pop
  """
1351 a8083063 Iustin Pop
  children = []
1352 a8083063 Iustin Pop
  if disk.children:
1353 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1354 fc1dc9d7 Iustin Pop
    if mcn == -1:
1355 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1356 fc1dc9d7 Iustin Pop
    else:
1357 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1358 a8083063 Iustin Pop
    for chld_disk in disk.children:
1359 fc1dc9d7 Iustin Pop
      try:
1360 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1361 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1362 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1363 fc1dc9d7 Iustin Pop
          raise
1364 fc1dc9d7 Iustin Pop
        cdev = None
1365 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1366 1063abd1 Iustin Pop
                      str(err))
1367 fc1dc9d7 Iustin Pop
      children.append(cdev)
1368 a8083063 Iustin Pop
1369 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1370 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1371 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1372 a8083063 Iustin Pop
    result = r_dev
1373 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1374 a8083063 Iustin Pop
      r_dev.Open()
1375 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1376 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1377 3f78eef2 Iustin Pop
1378 a8083063 Iustin Pop
  else:
1379 a8083063 Iustin Pop
    result = True
1380 a8083063 Iustin Pop
  return result
1381 a8083063 Iustin Pop
1382 a8083063 Iustin Pop
1383 821d1bd1 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary):
1384 a8083063 Iustin Pop
  """Activate a block device for an instance.
1385 a8083063 Iustin Pop

1386 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1387 a8083063 Iustin Pop

1388 b1206984 Iustin Pop
  @rtype: str or boolean
1389 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1390 b1206984 Iustin Pop
      C{True} for secondary nodes
1391 a8083063 Iustin Pop

1392 a8083063 Iustin Pop
  """
1393 53c14ef1 Iustin Pop
  try:
1394 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1395 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1396 fe267188 Iustin Pop
      # pylint: disable-msg=E1103
1397 53c14ef1 Iustin Pop
      result = result.dev_path
1398 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1399 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1400 afdc3985 Iustin Pop
1401 c26a6bd2 Iustin Pop
  return result
1402 a8083063 Iustin Pop
1403 a8083063 Iustin Pop
1404 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1405 a8083063 Iustin Pop
  """Shut down a block device.
1406 a8083063 Iustin Pop

1407 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1408 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1409 c41eea6e Iustin Pop
  shutdown.
1410 a8083063 Iustin Pop

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

1415 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1416 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1417 10c2650b Iustin Pop
      shutdown
1418 c26a6bd2 Iustin Pop
  @rtype: None
1419 10c2650b Iustin Pop

1420 a8083063 Iustin Pop
  """
1421 cacfd1fd Iustin Pop
  msgs = []
1422 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1423 a8083063 Iustin Pop
  if r_dev is not None:
1424 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1425 cacfd1fd Iustin Pop
    try:
1426 746f7476 Iustin Pop
      r_dev.Shutdown()
1427 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1428 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1429 cacfd1fd Iustin Pop
      msgs.append(str(err))
1430 746f7476 Iustin Pop
1431 a8083063 Iustin Pop
  if disk.children:
1432 a8083063 Iustin Pop
    for child in disk.children:
1433 c26a6bd2 Iustin Pop
      try:
1434 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1435 c26a6bd2 Iustin Pop
      except RPCFail, err:
1436 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1437 746f7476 Iustin Pop
1438 c26a6bd2 Iustin Pop
  if msgs:
1439 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1440 a8083063 Iustin Pop
1441 a8083063 Iustin Pop
1442 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1443 153d9724 Iustin Pop
  """Extend a mirrored block device.
1444 a8083063 Iustin Pop

1445 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1446 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1447 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1448 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1449 c26a6bd2 Iustin Pop
  @rtype: None
1450 10c2650b Iustin Pop

1451 a8083063 Iustin Pop
  """
1452 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1453 153d9724 Iustin Pop
  if parent_bdev is None:
1454 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1455 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1456 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1457 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1458 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1459 a8083063 Iustin Pop
1460 a8083063 Iustin Pop
1461 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1462 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1463 a8083063 Iustin Pop

1464 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1465 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1466 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1467 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1468 c26a6bd2 Iustin Pop
  @rtype: None
1469 10c2650b Iustin Pop

1470 a8083063 Iustin Pop
  """
1471 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1472 153d9724 Iustin Pop
  if parent_bdev is None:
1473 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1474 e739bd57 Iustin Pop
  devs = []
1475 e739bd57 Iustin Pop
  for disk in new_cdevs:
1476 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1477 e739bd57 Iustin Pop
    if rpath is None:
1478 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1479 e739bd57 Iustin Pop
      if bd is None:
1480 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1481 e739bd57 Iustin Pop
      else:
1482 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1483 e739bd57 Iustin Pop
    else:
1484 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1485 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1486 e739bd57 Iustin Pop
      devs.append(rpath)
1487 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1488 a8083063 Iustin Pop
1489 a8083063 Iustin Pop
1490 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1491 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1492 a8083063 Iustin Pop

1493 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1494 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1495 10c2650b Iustin Pop
  @rtype: disk
1496 10c2650b Iustin Pop
  @return:
1497 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1498 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1499 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1500 10c2650b Iustin Pop
      found
1501 a8083063 Iustin Pop

1502 a8083063 Iustin Pop
  """
1503 a8083063 Iustin Pop
  stats = []
1504 a8083063 Iustin Pop
  for dsk in disks:
1505 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1506 a8083063 Iustin Pop
    if rbd is None:
1507 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1508 96acbc09 Michael Hanselmann
1509 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1510 96acbc09 Michael Hanselmann
1511 c26a6bd2 Iustin Pop
  return stats
1512 a8083063 Iustin Pop
1513 a8083063 Iustin Pop
1514 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1515 a8083063 Iustin Pop
  """Check if a device is activated.
1516 a8083063 Iustin Pop

1517 5bbd3f7f Michael Hanselmann
  If so, return information about the real device.
1518 a8083063 Iustin Pop

1519 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1520 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1521 a8083063 Iustin Pop

1522 10c2650b Iustin Pop
  @return: None if the device can't be found,
1523 10c2650b Iustin Pop
      otherwise the device instance
1524 a8083063 Iustin Pop

1525 a8083063 Iustin Pop
  """
1526 a8083063 Iustin Pop
  children = []
1527 a8083063 Iustin Pop
  if disk.children:
1528 a8083063 Iustin Pop
    for chdisk in disk.children:
1529 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1530 a8083063 Iustin Pop
1531 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1532 a8083063 Iustin Pop
1533 a8083063 Iustin Pop
1534 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1535 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1536 f2e07bb4 Michael Hanselmann

1537 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1538 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1539 f2e07bb4 Michael Hanselmann

1540 f2e07bb4 Michael Hanselmann
  """
1541 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1542 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1543 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1544 f2e07bb4 Michael Hanselmann
1545 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1546 f2e07bb4 Michael Hanselmann
1547 f2e07bb4 Michael Hanselmann
  return real_disk
1548 f2e07bb4 Michael Hanselmann
1549 f2e07bb4 Michael Hanselmann
1550 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1551 a8083063 Iustin Pop
  """Check if a device is activated.
1552 a8083063 Iustin Pop

1553 5bbd3f7f Michael Hanselmann
  If it is, return information about the real device.
1554 a8083063 Iustin Pop

1555 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1556 10c2650b Iustin Pop
  @param disk: the disk to find
1557 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1558 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1559 96acbc09 Michael Hanselmann
           information
1560 a8083063 Iustin Pop

1561 a8083063 Iustin Pop
  """
1562 23829f6f Iustin Pop
  try:
1563 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1564 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1565 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1566 96acbc09 Michael Hanselmann
1567 a8083063 Iustin Pop
  if rbd is None:
1568 c26a6bd2 Iustin Pop
    return None
1569 96acbc09 Michael Hanselmann
1570 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
1571 a8083063 Iustin Pop
1572 a8083063 Iustin Pop
1573 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1574 968a7623 Iustin Pop
  """Computes the size of the given disks.
1575 968a7623 Iustin Pop

1576 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
1577 968a7623 Iustin Pop

1578 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
1579 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
1580 968a7623 Iustin Pop
  @rtype: list
1581 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
1582 968a7623 Iustin Pop
      otherwise the size
1583 968a7623 Iustin Pop

1584 968a7623 Iustin Pop
  """
1585 968a7623 Iustin Pop
  result = []
1586 968a7623 Iustin Pop
  for cf in disks:
1587 968a7623 Iustin Pop
    try:
1588 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
1589 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
1590 968a7623 Iustin Pop
      result.append(None)
1591 968a7623 Iustin Pop
      continue
1592 968a7623 Iustin Pop
    if rbd is None:
1593 968a7623 Iustin Pop
      result.append(None)
1594 968a7623 Iustin Pop
    else:
1595 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
1596 968a7623 Iustin Pop
  return result
1597 968a7623 Iustin Pop
1598 968a7623 Iustin Pop
1599 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1600 858f3d18 Iustin Pop
  """Export a block device to a remote node.
1601 858f3d18 Iustin Pop

1602 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
1603 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
1604 858f3d18 Iustin Pop
  @type dest_node: str
1605 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
1606 858f3d18 Iustin Pop
  @type dest_path: str
1607 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
1608 858f3d18 Iustin Pop
  @type cluster_name: str
1609 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1610 858f3d18 Iustin Pop
  @rtype: None
1611 858f3d18 Iustin Pop

1612 858f3d18 Iustin Pop
  """
1613 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
1614 858f3d18 Iustin Pop
1615 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
1616 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1617 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
1618 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
1619 858f3d18 Iustin Pop
1620 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
1621 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
1622 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
1623 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
1624 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
1625 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
1626 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
1627 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
1628 858f3d18 Iustin Pop
1629 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1630 858f3d18 Iustin Pop
                                                   constants.GANETI_RUNAS,
1631 858f3d18 Iustin Pop
                                                   destcmd)
1632 858f3d18 Iustin Pop
1633 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1634 858f3d18 Iustin Pop
  command = '|'.join([expcmd, utils.ShellQuoteArgs(remotecmd)])
1635 858f3d18 Iustin Pop
1636 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
1637 858f3d18 Iustin Pop
1638 858f3d18 Iustin Pop
  if result.failed:
1639 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
1640 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1641 858f3d18 Iustin Pop
1642 858f3d18 Iustin Pop
1643 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1644 a8083063 Iustin Pop
  """Write a file to the filesystem.
1645 a8083063 Iustin Pop

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

1649 10c2650b Iustin Pop
  @type file_name: str
1650 10c2650b Iustin Pop
  @param file_name: the target file name
1651 10c2650b Iustin Pop
  @type data: str
1652 10c2650b Iustin Pop
  @param data: the new contents of the file
1653 10c2650b Iustin Pop
  @type mode: int
1654 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1655 10c2650b Iustin Pop
  @type uid: int
1656 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1657 10c2650b Iustin Pop
  @type gid: int
1658 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1659 10c2650b Iustin Pop
  @type atime: float
1660 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1661 10c2650b Iustin Pop
  @type mtime: float
1662 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1663 c26a6bd2 Iustin Pop
  @rtype: None
1664 10c2650b Iustin Pop

1665 a8083063 Iustin Pop
  """
1666 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1667 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1668 a8083063 Iustin Pop
1669 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
1670 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1671 2cc6781a Iustin Pop
          file_name)
1672 a8083063 Iustin Pop
1673 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1674 12bce260 Michael Hanselmann
1675 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1676 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1677 a8083063 Iustin Pop
1678 386b57af Iustin Pop
1679 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1680 89b14f05 Iustin Pop
  """Update all ssconf files.
1681 89b14f05 Iustin Pop

1682 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1683 89b14f05 Iustin Pop

1684 89b14f05 Iustin Pop
  """
1685 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1686 6ddc95ec Michael Hanselmann
1687 6ddc95ec Michael Hanselmann
1688 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1689 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1690 a8083063 Iustin Pop

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

1695 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1696 10c2650b Iustin Pop
  @param err: the exception to format
1697 a8083063 Iustin Pop

1698 a8083063 Iustin Pop
  """
1699 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1700 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1701 a8083063 Iustin Pop
  else:
1702 a8083063 Iustin Pop
    detail = str(err)
1703 a8083063 Iustin Pop
  return detail
1704 a8083063 Iustin Pop
1705 5d0fe286 Iustin Pop
1706 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
1707 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1708 a8083063 Iustin Pop

1709 c19f9810 Iustin Pop
  This function will try to read the API version of the OS residing in
1710 c19f9810 Iustin Pop
  the 'os_dir' directory.
1711 7c3d51d4 Guido Trotter

1712 10c2650b Iustin Pop
  @type os_dir: str
1713 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
1714 8e70b181 Iustin Pop
  @rtype: tuple
1715 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
1716 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
1717 a8083063 Iustin Pop

1718 a8083063 Iustin Pop
  """
1719 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1720 a8083063 Iustin Pop
1721 a8083063 Iustin Pop
  try:
1722 a8083063 Iustin Pop
    st = os.stat(api_file)
1723 a8083063 Iustin Pop
  except EnvironmentError, err:
1724 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
1725 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1726 a8083063 Iustin Pop
1727 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1728 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
1729 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
1730 a8083063 Iustin Pop
1731 a8083063 Iustin Pop
  try:
1732 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
1733 a8083063 Iustin Pop
  except EnvironmentError, err:
1734 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
1735 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
1736 a8083063 Iustin Pop
1737 a8083063 Iustin Pop
  try:
1738 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
1739 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1740 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
1741 255dcebd Iustin Pop
                   str(err))
1742 a8083063 Iustin Pop
1743 255dcebd Iustin Pop
  return True, api_versions
1744 a8083063 Iustin Pop
1745 386b57af Iustin Pop
1746 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1747 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1748 a8083063 Iustin Pop

1749 10c2650b Iustin Pop
  @type top_dirs: list
1750 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1751 10c2650b Iustin Pop
      search (if not given defaults to
1752 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1753 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1754 ba00557a Guido Trotter
  @return: a list of tuples (name, path, status, diagnose, variants)
1755 255dcebd Iustin Pop
      for all (potential) OSes under all search paths, where:
1756 255dcebd Iustin Pop
          - name is the (potential) OS name
1757 255dcebd Iustin Pop
          - path is the full path to the OS
1758 255dcebd Iustin Pop
          - status True/False is the validity of the OS
1759 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
1760 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
1761 a8083063 Iustin Pop

1762 a8083063 Iustin Pop
  """
1763 7c3d51d4 Guido Trotter
  if top_dirs is None:
1764 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1765 a8083063 Iustin Pop
1766 a8083063 Iustin Pop
  result = []
1767 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1768 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1769 7c3d51d4 Guido Trotter
      try:
1770 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1771 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1772 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1773 7c3d51d4 Guido Trotter
        break
1774 7c3d51d4 Guido Trotter
      for name in f_names:
1775 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
1776 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1777 255dcebd Iustin Pop
        if status:
1778 255dcebd Iustin Pop
          diagnose = ""
1779 ba00557a Guido Trotter
          variants = os_inst.supported_variants
1780 255dcebd Iustin Pop
        else:
1781 255dcebd Iustin Pop
          diagnose = os_inst
1782 ba00557a Guido Trotter
          variants = []
1783 ba00557a Guido Trotter
        result.append((name, os_path, status, diagnose, variants))
1784 a8083063 Iustin Pop
1785 c26a6bd2 Iustin Pop
  return result
1786 a8083063 Iustin Pop
1787 a8083063 Iustin Pop
1788 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
1789 a8083063 Iustin Pop
  """Create an OS instance from disk.
1790 a8083063 Iustin Pop

1791 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1792 8e70b181 Iustin Pop
  valid OS name.
1793 a8083063 Iustin Pop

1794 8ee4dc80 Guido Trotter
  @type base_dir: string
1795 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1796 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1797 255dcebd Iustin Pop
  @rtype: tuple
1798 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
1799 255dcebd Iustin Pop
      or error message
1800 7c3d51d4 Guido Trotter

1801 a8083063 Iustin Pop
  """
1802 56bcd3f4 Guido Trotter
  if base_dir is None:
1803 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1804 c34c0cfd Iustin Pop
  else:
1805 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1806 f95c81bf Iustin Pop
1807 f95c81bf Iustin Pop
  if os_dir is None:
1808 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
1809 a8083063 Iustin Pop
1810 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
1811 255dcebd Iustin Pop
  if not status:
1812 255dcebd Iustin Pop
    # push the error up
1813 255dcebd Iustin Pop
    return status, api_versions
1814 a8083063 Iustin Pop
1815 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1816 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1817 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1818 a8083063 Iustin Pop
1819 41ba4061 Guido Trotter
  # OS Files dictionary, we will populate it with the absolute path names
1820 41ba4061 Guido Trotter
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1821 a8083063 Iustin Pop
1822 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
1823 95075fba Guido Trotter
    os_files[constants.OS_VARIANTS_FILE] = ''
1824 95075fba Guido Trotter
1825 ea79fc15 Michael Hanselmann
  for filename in os_files:
1826 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
1827 a8083063 Iustin Pop
1828 a8083063 Iustin Pop
    try:
1829 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
1830 a8083063 Iustin Pop
    except EnvironmentError, err:
1831 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
1832 ea79fc15 Michael Hanselmann
                     (filename, os_dir, _ErrnoOrStr(err)))
1833 a8083063 Iustin Pop
1834 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1835 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
1836 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
1837 255dcebd Iustin Pop
1838 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
1839 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1840 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
1841 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
1842 0757c107 Guido Trotter
1843 95075fba Guido Trotter
  variants = None
1844 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
1845 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
1846 95075fba Guido Trotter
    try:
1847 95075fba Guido Trotter
      variants = utils.ReadFile(variants_file).splitlines()
1848 95075fba Guido Trotter
    except EnvironmentError, err:
1849 95075fba Guido Trotter
      return False, ("Error while reading the OS variants file at %s: %s" %
1850 95075fba Guido Trotter
                     (variants_file, _ErrnoOrStr(err)))
1851 95075fba Guido Trotter
    if not variants:
1852 95075fba Guido Trotter
      return False, ("No supported os variant found")
1853 0757c107 Guido Trotter
1854 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
1855 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
1856 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
1857 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
1858 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
1859 95075fba Guido Trotter
                      supported_variants=variants,
1860 255dcebd Iustin Pop
                      api_versions=api_versions)
1861 255dcebd Iustin Pop
  return True, os_obj
1862 255dcebd Iustin Pop
1863 255dcebd Iustin Pop
1864 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
1865 255dcebd Iustin Pop
  """Create an OS instance from disk.
1866 255dcebd Iustin Pop

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

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

1874 255dcebd Iustin Pop
  @type base_dir: string
1875 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
1876 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1877 255dcebd Iustin Pop
  @rtype: L{objects.OS}
1878 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
1879 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
1880 255dcebd Iustin Pop

1881 255dcebd Iustin Pop
  """
1882 69b99987 Michael Hanselmann
  name_only = name.split("+", 1)[0]
1883 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
1884 255dcebd Iustin Pop
1885 255dcebd Iustin Pop
  if not status:
1886 255dcebd Iustin Pop
    _Fail(payload)
1887 a8083063 Iustin Pop
1888 255dcebd Iustin Pop
  return payload
1889 a8083063 Iustin Pop
1890 a8083063 Iustin Pop
1891 099c52ad Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
1892 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1893 2266edb2 Guido Trotter

1894 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1895 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1896 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
1897 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
1898 2266edb2 Guido Trotter
  @type debug: integer
1899 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1900 2266edb2 Guido Trotter
  @rtype: dict
1901 2266edb2 Guido Trotter
  @return: dict of environment variables
1902 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1903 10c2650b Iustin Pop
      cannot be found
1904 2266edb2 Guido Trotter

1905 2266edb2 Guido Trotter
  """
1906 2266edb2 Guido Trotter
  result = {}
1907 099c52ad Iustin Pop
  api_version = \
1908 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
1909 d1a7d66f Guido Trotter
  result['OS_API_VERSION'] = '%d' % api_version
1910 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1911 15552312 Iustin Pop
  result['INSTANCE_OS'] = instance.os
1912 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1913 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1914 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1915 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1916 f11280b5 Guido Trotter
  if api_version >= constants.OS_API_V15:
1917 f11280b5 Guido Trotter
    try:
1918 f11280b5 Guido Trotter
      variant = instance.os.split('+', 1)[1]
1919 f11280b5 Guido Trotter
    except IndexError:
1920 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
1921 f11280b5 Guido Trotter
    result['OS_VARIANT'] = variant
1922 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1923 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
1924 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1925 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
1926 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1927 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1928 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1929 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1930 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1931 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1932 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1933 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1934 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1935 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1936 2266edb2 Guido Trotter
    if nic.ip:
1937 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1938 1ba9227f Guido Trotter
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1939 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1940 1ba9227f Guido Trotter
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1941 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
1942 1ba9227f Guido Trotter
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1943 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1944 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1945 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1946 2266edb2 Guido Trotter
1947 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1948 67fc3042 Iustin Pop
    for key, value in source.items():
1949 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1950 67fc3042 Iustin Pop
1951 2266edb2 Guido Trotter
  return result
1952 a8083063 Iustin Pop
1953 f2e07bb4 Michael Hanselmann
1954 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
1955 594609c0 Iustin Pop
  """Grow a stack of block devices.
1956 594609c0 Iustin Pop

1957 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1958 10c2650b Iustin Pop
  first ones to resize.
1959 594609c0 Iustin Pop

1960 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1961 10c2650b Iustin Pop
  @param disk: the disk to be grown
1962 10c2650b Iustin Pop
  @rtype: (status, result)
1963 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1964 10c2650b Iustin Pop
      (True/False), and the errors message if status
1965 10c2650b Iustin Pop
      is False
1966 594609c0 Iustin Pop

1967 594609c0 Iustin Pop
  """
1968 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1969 594609c0 Iustin Pop
  if r_dev is None:
1970 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
1971 594609c0 Iustin Pop
1972 594609c0 Iustin Pop
  try:
1973 594609c0 Iustin Pop
    r_dev.Grow(amount)
1974 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1975 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
1976 594609c0 Iustin Pop
1977 594609c0 Iustin Pop
1978 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
1979 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1980 a8083063 Iustin Pop

1981 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1982 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1983 a8083063 Iustin Pop

1984 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1985 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1986 e9e9263d Guido Trotter
  @rtype: string
1987 e9e9263d Guido Trotter
  @return: snapshot disk path
1988 a8083063 Iustin Pop

1989 098c0958 Michael Hanselmann
  """
1990 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
1991 433c63aa Iustin Pop
    if not disk.children:
1992 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
1993 433c63aa Iustin Pop
            disk.unique_id)
1994 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
1995 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1996 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1997 a8083063 Iustin Pop
    if r_dev is not None:
1998 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
1999 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2000 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2001 a8083063 Iustin Pop
    else:
2002 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2003 a8083063 Iustin Pop
  else:
2004 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2005 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2006 a8083063 Iustin Pop
2007 a8083063 Iustin Pop
2008 4a0e011f Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx, debug):
2009 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
2010 a8083063 Iustin Pop

2011 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
2012 74c47259 Iustin Pop
  @param disk: the description of the disk to export
2013 74c47259 Iustin Pop
  @type dest_node: str
2014 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
2015 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
2016 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
2017 74c47259 Iustin Pop
  @type cluster_name: str
2018 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2019 74c47259 Iustin Pop
  @type idx: int
2020 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
2021 74c47259 Iustin Pop
      used to export to the OS scripts environment
2022 4a0e011f Iustin Pop
  @type debug: integer
2023 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
2024 c26a6bd2 Iustin Pop
  @rtype: None
2025 a8083063 Iustin Pop

2026 098c0958 Michael Hanselmann
  """
2027 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
2028 4a0e011f Iustin Pop
  export_env = OSEnvironment(instance, inst_os, debug)
2029 d1a7d66f Guido Trotter
2030 a8083063 Iustin Pop
  export_script = inst_os.export_script
2031 a8083063 Iustin Pop
2032 81a3406c Iustin Pop
  logfile = _InstanceLogName("export", inst_os.name, instance.name)
2033 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
2034 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
2035 ba55d062 Iustin Pop
2036 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
2037 0607699d Guido Trotter
2038 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
2039 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
2040 a8083063 Iustin Pop
2041 c4feafe8 Iustin Pop
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2042 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
2043 a8083063 Iustin Pop
2044 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
2045 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
2046 a8083063 Iustin Pop
  # valid parameters
2047 a48b08bf Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
2048 a48b08bf Iustin Pop
                               inst_os.path, export_script, logfile)
2049 a8083063 Iustin Pop
2050 a8083063 Iustin Pop
  comprcmd = "gzip"
2051 a8083063 Iustin Pop
2052 0411c011 Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s",
2053 0411c011 Iustin Pop
                                destdir, utils.PathJoin(destdir, destfile))
2054 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2055 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
2056 62c9ec92 Iustin Pop
                                                   destcmd)
2057 a8083063 Iustin Pop
2058 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
2059 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
2060 a8083063 Iustin Pop
2061 a48b08bf Iustin Pop
  result = utils.RunCmd(["bash", "-c", command], env=export_env)
2062 a8083063 Iustin Pop
2063 a8083063 Iustin Pop
  if result.failed:
2064 ba55d062 Iustin Pop
    _Fail("OS snapshot export command '%s' returned error: %s"
2065 ba55d062 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
2066 a8083063 Iustin Pop
2067 a8083063 Iustin Pop
2068 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2069 a8083063 Iustin Pop
  """Write out the export configuration information.
2070 a8083063 Iustin Pop

2071 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2072 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2073 10c2650b Iustin Pop
      saving configuration
2074 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2075 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2076 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2077 a8083063 Iustin Pop

2078 c26a6bd2 Iustin Pop
  @rtype: None
2079 a8083063 Iustin Pop

2080 098c0958 Michael Hanselmann
  """
2081 c4feafe8 Iustin Pop
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2082 c4feafe8 Iustin Pop
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2083 a8083063 Iustin Pop
2084 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2085 a8083063 Iustin Pop
2086 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2087 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
2088 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2089 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2090 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
2091 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
2092 a8083063 Iustin Pop
2093 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2094 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
2095 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
2096 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
2097 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
2098 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2099 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2100 3c8954ad Iustin Pop
  config.set(constants.INISECT_INS, 'hypervisor', instance.hypervisor)
2101 66f93869 Manuel Franceschini
2102 95268cc3 Iustin Pop
  nic_total = 0
2103 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2104 95268cc3 Iustin Pop
    nic_total += 1
2105 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2106 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
2107 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2108 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2109 6801eb5c Iustin Pop
      config.set(constants.INISECT_INS, 'nic%d_%s' % (nic_count, param),
2110 6801eb5c Iustin Pop
                 '%s' % nic.nicparams.get(param, None))
2111 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2112 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2113 a8083063 Iustin Pop
2114 726d7d68 Iustin Pop
  disk_total = 0
2115 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2116 19d7f90a Guido Trotter
    if disk:
2117 726d7d68 Iustin Pop
      disk_total += 1
2118 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2119 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
2120 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2121 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
2122 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2123 19d7f90a Guido Trotter
                 ('%d' % disk.size))
2124 a8083063 Iustin Pop
2125 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2126 a8083063 Iustin Pop
2127 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2128 3c8954ad Iustin Pop
2129 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2130 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2131 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2132 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2133 3c8954ad Iustin Pop
2134 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2135 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2136 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2137 3c8954ad Iustin Pop
2138 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2139 726d7d68 Iustin Pop
                  data=config.Dumps())
2140 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2141 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2142 a8083063 Iustin Pop
2143 a8083063 Iustin Pop
2144 a8083063 Iustin Pop
def ExportInfo(dest):
2145 a8083063 Iustin Pop
  """Get export configuration information.
2146 a8083063 Iustin Pop

2147 10c2650b Iustin Pop
  @type dest: str
2148 10c2650b Iustin Pop
  @param dest: directory containing the export
2149 a8083063 Iustin Pop

2150 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2151 10c2650b Iustin Pop
  @return: a serializable config file containing the
2152 10c2650b Iustin Pop
      export info
2153 a8083063 Iustin Pop

2154 a8083063 Iustin Pop
  """
2155 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2156 a8083063 Iustin Pop
2157 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2158 a8083063 Iustin Pop
  config.read(cff)
2159 a8083063 Iustin Pop
2160 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2161 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2162 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2163 a8083063 Iustin Pop
2164 c26a6bd2 Iustin Pop
  return config.Dumps()
2165 a8083063 Iustin Pop
2166 a8083063 Iustin Pop
2167 4a0e011f Iustin Pop
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name, debug):
2168 a8083063 Iustin Pop
  """Import an os image into an instance.
2169 a8083063 Iustin Pop

2170 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
2171 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
2172 6c0af70e Guido Trotter
  @type src_node: string
2173 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
2174 6c0af70e Guido Trotter
  @type src_images: list of string
2175 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
2176 4a0e011f Iustin Pop
  @type debug: integer
2177 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
2178 6c0af70e Guido Trotter
  @rtype: list of boolean
2179 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
2180 a8083063 Iustin Pop

2181 a8083063 Iustin Pop
  """
2182 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
2183 4a0e011f Iustin Pop
  import_env = OSEnvironment(instance, inst_os, debug)
2184 a8083063 Iustin Pop
  import_script = inst_os.import_script
2185 a8083063 Iustin Pop
2186 81a3406c Iustin Pop
  logfile = _InstanceLogName("import", instance.os, instance.name)
2187 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
2188 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
2189 a8083063 Iustin Pop
2190 a8083063 Iustin Pop
  comprcmd = "gunzip"
2191 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
2192 d868edb4 Iustin Pop
                               import_script, logfile)
2193 a8083063 Iustin Pop
2194 6c0af70e Guido Trotter
  final_result = []
2195 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
2196 6c0af70e Guido Trotter
    if image:
2197 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
2198 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
2199 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
2200 6c0af70e Guido Trotter
                                                       destcmd)
2201 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
2202 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
2203 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
2204 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
2205 6c0af70e Guido Trotter
      if result.failed:
2206 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
2207 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
2208 726d7d68 Iustin Pop
                      result.output)
2209 944bf548 Iustin Pop
        final_result.append("error importing disk %d: %s, %s" %
2210 944bf548 Iustin Pop
                            (idx, result.fail_reason, result.output[-100]))
2211 a8083063 Iustin Pop
2212 944bf548 Iustin Pop
  if final_result:
2213 afdc3985 Iustin Pop
    _Fail("; ".join(final_result), log=False)
2214 a8083063 Iustin Pop
2215 a8083063 Iustin Pop
2216 a8083063 Iustin Pop
def ListExports():
2217 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2218 098c0958 Michael Hanselmann

2219 10c2650b Iustin Pop
  @rtype: list
2220 10c2650b Iustin Pop
  @return: list of the exports
2221 10c2650b Iustin Pop

2222 a8083063 Iustin Pop
  """
2223 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
2224 c26a6bd2 Iustin Pop
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
2225 a8083063 Iustin Pop
  else:
2226 afdc3985 Iustin Pop
    _Fail("No exports directory")
2227 a8083063 Iustin Pop
2228 a8083063 Iustin Pop
2229 a8083063 Iustin Pop
def RemoveExport(export):
2230 a8083063 Iustin Pop
  """Remove an existing export from the node.
2231 a8083063 Iustin Pop

2232 10c2650b Iustin Pop
  @type export: str
2233 10c2650b Iustin Pop
  @param export: the name of the export to remove
2234 c26a6bd2 Iustin Pop
  @rtype: None
2235 a8083063 Iustin Pop

2236 098c0958 Michael Hanselmann
  """
2237 c4feafe8 Iustin Pop
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2238 a8083063 Iustin Pop
2239 35fbcd11 Iustin Pop
  try:
2240 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2241 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2242 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2243 a8083063 Iustin Pop
2244 a8083063 Iustin Pop
2245 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2246 f3e513ad Iustin Pop
  """Rename a list of block devices.
2247 f3e513ad Iustin Pop

2248 10c2650b Iustin Pop
  @type devlist: list of tuples
2249 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2250 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2251 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2252 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2253 10c2650b Iustin Pop
      rename it to
2254 10c2650b Iustin Pop
  @rtype: boolean
2255 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2256 f3e513ad Iustin Pop

2257 f3e513ad Iustin Pop
  """
2258 6b5e3f70 Iustin Pop
  msgs = []
2259 f3e513ad Iustin Pop
  result = True
2260 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2261 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2262 f3e513ad Iustin Pop
    if dev is None:
2263 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2264 f3e513ad Iustin Pop
      result = False
2265 f3e513ad Iustin Pop
      continue
2266 f3e513ad Iustin Pop
    try:
2267 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2268 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2269 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2270 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2271 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2272 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2273 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2274 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2275 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2276 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2277 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2278 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2279 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2280 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2281 f3e513ad Iustin Pop
      result = False
2282 afdc3985 Iustin Pop
  if not result:
2283 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2284 f3e513ad Iustin Pop
2285 f3e513ad Iustin Pop
2286 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2287 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2288 778b75bb Manuel Franceschini

2289 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2290 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2291 778b75bb Manuel Franceschini
  directory are allowed.
2292 778b75bb Manuel Franceschini

2293 b1206984 Iustin Pop
  @type file_storage_dir: str
2294 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2295 d61cbe76 Iustin Pop

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

2298 778b75bb Manuel Franceschini
  """
2299 cb7c0198 Iustin Pop
  if not constants.ENABLE_FILE_STORAGE:
2300 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2301 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2302 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2303 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2304 56569f4e Michael Hanselmann
  if (os.path.commonprefix([file_storage_dir, base_file_storage_dir]) !=
2305 778b75bb Manuel Franceschini
      base_file_storage_dir):
2306 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2307 b2b8bcce Iustin Pop
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2308 778b75bb Manuel Franceschini
  return file_storage_dir
2309 778b75bb Manuel Franceschini
2310 778b75bb Manuel Franceschini
2311 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2312 778b75bb Manuel Franceschini
  """Create file storage directory.
2313 778b75bb Manuel Franceschini

2314 b1206984 Iustin Pop
  @type file_storage_dir: str
2315 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2316 778b75bb Manuel Franceschini

2317 b1206984 Iustin Pop
  @rtype: tuple
2318 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2319 b1206984 Iustin Pop
      creation was successful or not
2320 778b75bb Manuel Franceschini

2321 778b75bb Manuel Franceschini
  """
2322 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2323 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2324 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2325 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2326 b2b8bcce Iustin Pop
            file_storage_dir)
2327 778b75bb Manuel Franceschini
  else:
2328 b2b8bcce Iustin Pop
    try:
2329 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2330 b2b8bcce Iustin Pop
    except OSError, err:
2331 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2332 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2333 778b75bb Manuel Franceschini
2334 778b75bb Manuel Franceschini
2335 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2336 778b75bb Manuel Franceschini
  """Remove file storage directory.
2337 778b75bb Manuel Franceschini

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

2340 10c2650b Iustin Pop
  @type file_storage_dir: str
2341 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2342 10c2650b Iustin Pop
  @rtype: tuple (success,)
2343 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2344 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2345 778b75bb Manuel Franceschini

2346 778b75bb Manuel Franceschini
  """
2347 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2348 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2349 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2350 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2351 b2b8bcce Iustin Pop
            file_storage_dir)
2352 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2353 b2b8bcce Iustin Pop
    try:
2354 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2355 b2b8bcce Iustin Pop
    except OSError, err:
2356 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2357 b2b8bcce Iustin Pop
            file_storage_dir, err)
2358 b2b8bcce Iustin Pop
2359 778b75bb Manuel Franceschini
2360 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2361 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2362 778b75bb Manuel Franceschini

2363 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2364 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2365 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2366 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2367 10c2650b Iustin Pop
  @rtype: tuple (success,)
2368 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2369 10c2650b Iustin Pop
      whether the operation was successful
2370 778b75bb Manuel Franceschini

2371 778b75bb Manuel Franceschini
  """
2372 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2373 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2374 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2375 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2376 b2b8bcce Iustin Pop
      try:
2377 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2378 b2b8bcce Iustin Pop
      except OSError, err:
2379 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2380 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2381 778b75bb Manuel Franceschini
    else:
2382 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2383 b2b8bcce Iustin Pop
            old_file_storage_dir)
2384 b2b8bcce Iustin Pop
  else:
2385 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2386 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2387 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2388 778b75bb Manuel Franceschini
2389 778b75bb Manuel Franceschini
2390 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2391 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2392 ca52cdeb Michael Hanselmann

2393 10c2650b Iustin Pop
  @type file_name: str
2394 10c2650b Iustin Pop
  @param file_name: the file name we should check
2395 c8457ce7 Iustin Pop
  @rtype: None
2396 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2397 10c2650b Iustin Pop

2398 ca52cdeb Michael Hanselmann
  """
2399 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2400 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2401 dc31eae3 Michael Hanselmann
2402 dc31eae3 Michael Hanselmann
  if not result:
2403 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2404 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2405 dc31eae3 Michael Hanselmann
2406 dc31eae3 Michael Hanselmann
2407 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2408 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2409 dc31eae3 Michael Hanselmann

2410 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2411 10c2650b Iustin Pop
  checking.
2412 10c2650b Iustin Pop

2413 10c2650b Iustin Pop
  @type file_name: str
2414 10c2650b Iustin Pop
  @param file_name: the job file name
2415 10c2650b Iustin Pop
  @type content: str
2416 10c2650b Iustin Pop
  @param content: the new job contents
2417 10c2650b Iustin Pop
  @rtype: boolean
2418 10c2650b Iustin Pop
  @return: the success of the operation
2419 10c2650b Iustin Pop

2420 dc31eae3 Michael Hanselmann
  """
2421 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2422 ca52cdeb Michael Hanselmann
2423 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2424 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2425 ca52cdeb Michael Hanselmann
2426 ca52cdeb Michael Hanselmann
2427 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2428 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2429 af5ebcb1 Michael Hanselmann

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

2432 10c2650b Iustin Pop
  @type old: str
2433 10c2650b Iustin Pop
  @param old: the old (actual) file name
2434 10c2650b Iustin Pop
  @type new: str
2435 10c2650b Iustin Pop
  @param new: the desired file name
2436 c8457ce7 Iustin Pop
  @rtype: tuple
2437 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2438 10c2650b Iustin Pop

2439 af5ebcb1 Michael Hanselmann
  """
2440 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2441 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2442 af5ebcb1 Michael Hanselmann
2443 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2444 af5ebcb1 Michael Hanselmann
2445 af5ebcb1 Michael Hanselmann
2446 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2447 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2448 5d672980 Iustin Pop

2449 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2450 5d672980 Iustin Pop

2451 10c2650b Iustin Pop
  @type drain_flag: boolean
2452 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2453 c8457ce7 Iustin Pop
  @rtype: truple
2454 c8457ce7 Iustin Pop
  @return: always True, None
2455 10c2650b Iustin Pop
  @warning: the function always returns True
2456 5d672980 Iustin Pop

2457 5d672980 Iustin Pop
  """
2458 5d672980 Iustin Pop
  if drain_flag:
2459 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2460 5d672980 Iustin Pop
  else:
2461 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2462 5d672980 Iustin Pop
2463 5d672980 Iustin Pop
2464 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2465 d61cbe76 Iustin Pop
  """Closes the given block devices.
2466 d61cbe76 Iustin Pop

2467 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2468 10c2650b Iustin Pop
  DRBD).
2469 10c2650b Iustin Pop

2470 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2471 b2e7666a Iustin Pop
      of this instance will be removed
2472 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2473 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2474 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2475 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2476 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2477 10c2650b Iustin Pop
      which will contain the error details in case we
2478 10c2650b Iustin Pop
      failed
2479 d61cbe76 Iustin Pop

2480 d61cbe76 Iustin Pop
  """
2481 d61cbe76 Iustin Pop
  bdevs = []
2482 d61cbe76 Iustin Pop
  for cf in disks:
2483 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2484 d61cbe76 Iustin Pop
    if rd is None:
2485 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2486 d61cbe76 Iustin Pop
    bdevs.append(rd)
2487 d61cbe76 Iustin Pop
2488 d61cbe76 Iustin Pop
  msg = []
2489 d61cbe76 Iustin Pop
  for rd in bdevs:
2490 d61cbe76 Iustin Pop
    try:
2491 d61cbe76 Iustin Pop
      rd.Close()
2492 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2493 d61cbe76 Iustin Pop
      msg.append(str(err))
2494 d61cbe76 Iustin Pop
  if msg:
2495 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2496 d61cbe76 Iustin Pop
  else:
2497 b2e7666a Iustin Pop
    if instance_name:
2498 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2499 d61cbe76 Iustin Pop
2500 d61cbe76 Iustin Pop
2501 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2502 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2503 6217e295 Iustin Pop

2504 6217e295 Iustin Pop
  @type hvname: string
2505 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2506 6217e295 Iustin Pop
  @type hvparams: dict
2507 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2508 c26a6bd2 Iustin Pop
  @rtype: None
2509 6217e295 Iustin Pop

2510 6217e295 Iustin Pop
  """
2511 6217e295 Iustin Pop
  try:
2512 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2513 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2514 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2515 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2516 6217e295 Iustin Pop
2517 6217e295 Iustin Pop
2518 56aa9fd5 Iustin Pop
def DemoteFromMC():
2519 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2520 56aa9fd5 Iustin Pop

2521 56aa9fd5 Iustin Pop
  """
2522 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2523 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2524 56aa9fd5 Iustin Pop
  if master == myself:
2525 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2526 f154a7a3 Michael Hanselmann
2527 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2528 f154a7a3 Michael Hanselmann
  if not result.failed:
2529 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2530 f154a7a3 Michael Hanselmann
2531 56aa9fd5 Iustin Pop
  try:
2532 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2533 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2534 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2535 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2536 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2537 f154a7a3 Michael Hanselmann
2538 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2539 56aa9fd5 Iustin Pop
2540 56aa9fd5 Iustin Pop
2541 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2542 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2543 6b93ec9d Iustin Pop

2544 6b93ec9d Iustin Pop
  """
2545 6b93ec9d Iustin Pop
  # set the correct physical ID
2546 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2547 6b93ec9d Iustin Pop
  for cf in disks:
2548 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2549 6b93ec9d Iustin Pop
2550 6b93ec9d Iustin Pop
  bdevs = []
2551 6b93ec9d Iustin Pop
2552 6b93ec9d Iustin Pop
  for cf in disks:
2553 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2554 6b93ec9d Iustin Pop
    if rd is None:
2555 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
2556 6b93ec9d Iustin Pop
    bdevs.append(rd)
2557 5a533f8a Iustin Pop
  return bdevs
2558 6b93ec9d Iustin Pop
2559 6b93ec9d Iustin Pop
2560 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2561 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2562 6b93ec9d Iustin Pop

2563 6b93ec9d Iustin Pop
  """
2564 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2565 6b93ec9d Iustin Pop
2566 6b93ec9d Iustin Pop
  # disconnect disks
2567 6b93ec9d Iustin Pop
  for rd in bdevs:
2568 6b93ec9d Iustin Pop
    try:
2569 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2570 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2571 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
2572 2cc6781a Iustin Pop
            err, exc=True)
2573 6b93ec9d Iustin Pop
2574 6b93ec9d Iustin Pop
2575 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2576 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2577 6b93ec9d Iustin Pop

2578 6b93ec9d Iustin Pop
  """
2579 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2580 6b93ec9d Iustin Pop
2581 6b93ec9d Iustin Pop
  if multimaster:
2582 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2583 6b93ec9d Iustin Pop
      try:
2584 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2585 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2586 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
2587 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2588 6b93ec9d Iustin Pop
  # needed primary mode
2589 6b93ec9d Iustin Pop
  for rd in bdevs:
2590 6b93ec9d Iustin Pop
    try:
2591 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2592 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2593 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
2594 3c0cdc83 Michael Hanselmann
2595 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2596 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2597 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2598 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2599 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2600 3c0cdc83 Michael Hanselmann
2601 3c0cdc83 Michael Hanselmann
  def _Attach():
2602 6b93ec9d Iustin Pop
    all_connected = True
2603 3c0cdc83 Michael Hanselmann
2604 6b93ec9d Iustin Pop
    for rd in bdevs:
2605 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2606 3c0cdc83 Michael Hanselmann
2607 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
2608 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
2609 3c0cdc83 Michael Hanselmann
2610 6b93ec9d Iustin Pop
      if stats.is_standalone:
2611 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2612 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2613 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2614 6b93ec9d Iustin Pop
        try:
2615 c738375b Iustin Pop
          rd.AttachNet(multimaster)
2616 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2617 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
2618 3c0cdc83 Michael Hanselmann
2619 3c0cdc83 Michael Hanselmann
    if not all_connected:
2620 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
2621 3c0cdc83 Michael Hanselmann
2622 3c0cdc83 Michael Hanselmann
  try:
2623 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
2624 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
2625 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
2626 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
2627 3c0cdc83 Michael Hanselmann
2628 6b93ec9d Iustin Pop
  if multimaster:
2629 6b93ec9d Iustin Pop
    # change to primary mode
2630 6b93ec9d Iustin Pop
    for rd in bdevs:
2631 d3da87b8 Iustin Pop
      try:
2632 d3da87b8 Iustin Pop
        rd.Open()
2633 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
2634 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
2635 6b93ec9d Iustin Pop
2636 6b93ec9d Iustin Pop
2637 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2638 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2639 6b93ec9d Iustin Pop

2640 6b93ec9d Iustin Pop
  """
2641 db8667b7 Iustin Pop
  def _helper(rd):
2642 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
2643 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2644 db8667b7 Iustin Pop
      raise utils.RetryAgain()
2645 db8667b7 Iustin Pop
    return stats
2646 db8667b7 Iustin Pop
2647 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2648 6b93ec9d Iustin Pop
2649 6b93ec9d Iustin Pop
  min_resync = 100
2650 6b93ec9d Iustin Pop
  alldone = True
2651 6b93ec9d Iustin Pop
  for rd in bdevs:
2652 db8667b7 Iustin Pop
    try:
2653 db8667b7 Iustin Pop
      # poll each second for 15 seconds
2654 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
2655 db8667b7 Iustin Pop
    except utils.RetryTimeout:
2656 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
2657 db8667b7 Iustin Pop
      # last check
2658 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2659 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2660 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2661 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2662 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2663 afdc3985 Iustin Pop
2664 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
2665 6b93ec9d Iustin Pop
2666 6b93ec9d Iustin Pop
2667 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
2668 f5118ade Iustin Pop
  """Hard-powercycle the node.
2669 f5118ade Iustin Pop

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

2673 f5118ade Iustin Pop
  """
2674 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2675 f5118ade Iustin Pop
  try:
2676 f5118ade Iustin Pop
    pid = os.fork()
2677 29921401 Iustin Pop
  except OSError:
2678 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
2679 f5118ade Iustin Pop
    pid = 0
2680 f5118ade Iustin Pop
  if pid > 0:
2681 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
2682 f5118ade Iustin Pop
  time.sleep(5)
2683 f5118ade Iustin Pop
  hyper.PowercycleNode()
2684 f5118ade Iustin Pop
2685 f5118ade Iustin Pop
2686 a8083063 Iustin Pop
class HooksRunner(object):
2687 a8083063 Iustin Pop
  """Hook runner.
2688 a8083063 Iustin Pop

2689 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2690 10c2650b Iustin Pop
  on the master side.
2691 a8083063 Iustin Pop

2692 a8083063 Iustin Pop
  """
2693 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2694 a8083063 Iustin Pop
    """Constructor for hooks runner.
2695 a8083063 Iustin Pop

2696 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2697 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2698 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2699 a8083063 Iustin Pop

2700 a8083063 Iustin Pop
    """
2701 a8083063 Iustin Pop
    if hooks_base_dir is None:
2702 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2703 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
2704 fe267188 Iustin Pop
    # constant
2705 fe267188 Iustin Pop
    self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
2706 a8083063 Iustin Pop
2707 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2708 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2709 a8083063 Iustin Pop

2710 10c2650b Iustin Pop
    @type hpath: str
2711 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2712 10c2650b Iustin Pop
        holds the scripts
2713 10c2650b Iustin Pop
    @type phase: str
2714 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2715 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2716 10c2650b Iustin Pop
    @type env: dict
2717 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2718 10c2650b Iustin Pop
    @rtype: list
2719 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2720 10c2650b Iustin Pop
      - script path
2721 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2722 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2723 10c2650b Iustin Pop
      - output of the script
2724 10c2650b Iustin Pop

2725 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2726 10c2650b Iustin Pop
        parameters
2727 a8083063 Iustin Pop

2728 a8083063 Iustin Pop
    """
2729 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2730 a8083063 Iustin Pop
      suffix = "pre"
2731 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2732 a8083063 Iustin Pop
      suffix = "post"
2733 a8083063 Iustin Pop
    else:
2734 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
2735 3fb4f740 Iustin Pop
2736 a8083063 Iustin Pop
2737 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2738 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
2739 6bb65e3a Guido Trotter
2740 6bb65e3a Guido Trotter
    results = []
2741 a9b7e346 Iustin Pop
2742 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
2743 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
2744 a9b7e346 Iustin Pop
      # warning at every operation
2745 a9b7e346 Iustin Pop
      return results
2746 a9b7e346 Iustin Pop
2747 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
2748 a9b7e346 Iustin Pop
2749 6bb65e3a Guido Trotter
    for (relname, relstatus, runresult)  in runparts_results:
2750 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
2751 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2752 a8083063 Iustin Pop
        output = ""
2753 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
2754 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
2755 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
2756 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
2757 6bb65e3a Guido Trotter
        if runresult.failed:
2758 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2759 a8083063 Iustin Pop
        else:
2760 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
2761 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
2762 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
2763 6bb65e3a Guido Trotter
2764 6bb65e3a Guido Trotter
    return results
2765 3f78eef2 Iustin Pop
2766 3f78eef2 Iustin Pop
2767 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2768 8d528b7c Iustin Pop
  """IAllocator runner.
2769 8d528b7c Iustin Pop

2770 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2771 8d528b7c Iustin Pop
  the master side.
2772 8d528b7c Iustin Pop

2773 8d528b7c Iustin Pop
  """
2774 7e950d31 Iustin Pop
  @staticmethod
2775 7e950d31 Iustin Pop
  def Run(name, idata):
2776 8d528b7c Iustin Pop
    """Run an iallocator script.
2777 8d528b7c Iustin Pop

2778 10c2650b Iustin Pop
    @type name: str
2779 10c2650b Iustin Pop
    @param name: the iallocator script name
2780 10c2650b Iustin Pop
    @type idata: str
2781 10c2650b Iustin Pop
    @param idata: the allocator input data
2782 10c2650b Iustin Pop

2783 10c2650b Iustin Pop
    @rtype: tuple
2784 87f5c298 Iustin Pop
    @return: two element tuple of:
2785 87f5c298 Iustin Pop
       - status
2786 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
2787 8d528b7c Iustin Pop

2788 8d528b7c Iustin Pop
    """
2789 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2790 8d528b7c Iustin Pop
                                  os.path.isfile)
2791 8d528b7c Iustin Pop
    if alloc_script is None:
2792 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
2793 8d528b7c Iustin Pop
2794 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2795 8d528b7c Iustin Pop
    try:
2796 8d528b7c Iustin Pop
      os.write(fd, idata)
2797 8d528b7c Iustin Pop
      os.close(fd)
2798 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2799 8d528b7c Iustin Pop
      if result.failed:
2800 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2801 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
2802 8d528b7c Iustin Pop
    finally:
2803 8d528b7c Iustin Pop
      os.unlink(fin_name)
2804 8d528b7c Iustin Pop
2805 c26a6bd2 Iustin Pop
    return result.stdout
2806 8d528b7c Iustin Pop
2807 8d528b7c Iustin Pop
2808 3f78eef2 Iustin Pop
class DevCacheManager(object):
2809 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2810 3f78eef2 Iustin Pop

2811 3f78eef2 Iustin Pop
  """
2812 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2813 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2814 3f78eef2 Iustin Pop
2815 3f78eef2 Iustin Pop
  @classmethod
2816 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2817 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2818 3f78eef2 Iustin Pop

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

2822 10c2650b Iustin Pop
    @type dev_path: str
2823 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2824 10c2650b Iustin Pop
    @rtype: str
2825 10c2650b Iustin Pop
    @return: the converted path name
2826 3f78eef2 Iustin Pop

2827 3f78eef2 Iustin Pop
    """
2828 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2829 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2830 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2831 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
2832 3f78eef2 Iustin Pop
    return fpath
2833 3f78eef2 Iustin Pop
2834 3f78eef2 Iustin Pop
  @classmethod
2835 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2836 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2837 3f78eef2 Iustin Pop

2838 10c2650b Iustin Pop
    @type dev_path: str
2839 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2840 10c2650b Iustin Pop
    @type owner: str
2841 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2842 10c2650b Iustin Pop
    @type on_primary: bool
2843 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2844 10c2650b Iustin Pop
        node nor not
2845 10c2650b Iustin Pop
    @type iv_name: str
2846 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2847 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2848 10c2650b Iustin Pop

2849 10c2650b Iustin Pop
    @rtype: None
2850 10c2650b Iustin Pop

2851 3f78eef2 Iustin Pop
    """
2852 cf5a8306 Iustin Pop
    if dev_path is None:
2853 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2854 cf5a8306 Iustin Pop
      return
2855 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2856 3f78eef2 Iustin Pop
    if on_primary:
2857 3f78eef2 Iustin Pop
      state = "primary"
2858 3f78eef2 Iustin Pop
    else:
2859 3f78eef2 Iustin Pop
      state = "secondary"
2860 3f78eef2 Iustin Pop
    if iv_name is None:
2861 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2862 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2863 3f78eef2 Iustin Pop
    try:
2864 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2865 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2866 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2867 3f78eef2 Iustin Pop
2868 3f78eef2 Iustin Pop
  @classmethod
2869 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2870 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2871 3f78eef2 Iustin Pop

2872 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2873 10c2650b Iustin Pop
    path name and logging.
2874 10c2650b Iustin Pop

2875 10c2650b Iustin Pop
    @type dev_path: str
2876 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2877 10c2650b Iustin Pop

2878 10c2650b Iustin Pop
    @rtype: None
2879 10c2650b Iustin Pop

2880 3f78eef2 Iustin Pop
    """
2881 cf5a8306 Iustin Pop
    if dev_path is None:
2882 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2883 cf5a8306 Iustin Pop
      return
2884 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2885 3f78eef2 Iustin Pop
    try:
2886 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2887 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2888 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)