Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 6b9b18a2

History | View | Annotate | Download (103.4 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 397693d3 Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 f81c4737 Michael Hanselmann
import signal
51 a8083063 Iustin Pop
52 a8083063 Iustin Pop
from ganeti import errors
53 a8083063 Iustin Pop
from ganeti import utils
54 a8083063 Iustin Pop
from ganeti import ssh
55 a8083063 Iustin Pop
from ganeti import hypervisor
56 a8083063 Iustin Pop
from ganeti import constants
57 a8083063 Iustin Pop
from ganeti import bdev
58 a8083063 Iustin Pop
from ganeti import objects
59 880478f8 Iustin Pop
from ganeti import ssconf
60 1651d116 Michael Hanselmann
from ganeti import serializer
61 a744b676 Manuel Franceschini
from ganeti import netutils
62 82b22e19 René Nussbaumer
from ganeti import runtime
63 a8083063 Iustin Pop
64 a8083063 Iustin Pop
65 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
66 714ea7ca Iustin Pop
_ALLOWED_CLEAN_DIRS = frozenset([
67 714ea7ca Iustin Pop
  constants.DATA_DIR,
68 714ea7ca Iustin Pop
  constants.JOB_QUEUE_ARCHIVE_DIR,
69 714ea7ca Iustin Pop
  constants.QUEUE_DIR,
70 f942a838 Michael Hanselmann
  constants.CRYPTO_KEYS_DIR,
71 714ea7ca Iustin Pop
  ])
72 f942a838 Michael Hanselmann
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
73 f942a838 Michael Hanselmann
_X509_KEY_FILE = "key"
74 f942a838 Michael Hanselmann
_X509_CERT_FILE = "cert"
75 1651d116 Michael Hanselmann
_IES_STATUS_FILE = "status"
76 1651d116 Michael Hanselmann
_IES_PID_FILE = "pid"
77 1651d116 Michael Hanselmann
_IES_CA_FILE = "ca"
78 13998ef2 Michael Hanselmann
79 0b5303da Iustin Pop
#: Valid LVS output line regex
80 84d7e26b Dmitry Chernyak
_LVSLINE_REGEX = re.compile("^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
81 0b5303da Iustin Pop
82 13998ef2 Michael Hanselmann
83 2cc6781a Iustin Pop
class RPCFail(Exception):
84 2cc6781a Iustin Pop
  """Class denoting RPC failure.
85 2cc6781a Iustin Pop

86 2cc6781a Iustin Pop
  Its argument is the error message.
87 2cc6781a Iustin Pop

88 2cc6781a Iustin Pop
  """
89 2cc6781a Iustin Pop
90 13998ef2 Michael Hanselmann
91 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
92 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
93 2cc6781a Iustin Pop

94 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
95 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
96 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
97 2cc6781a Iustin Pop
  daemon.
98 2cc6781a Iustin Pop

99 2cc6781a Iustin Pop
  @type msg: string
100 2cc6781a Iustin Pop
  @param msg: the text of the exception
101 2cc6781a Iustin Pop
  @raise RPCFail
102 2cc6781a Iustin Pop

103 2cc6781a Iustin Pop
  """
104 2cc6781a Iustin Pop
  if args:
105 2cc6781a Iustin Pop
    msg = msg % args
106 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
107 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
108 afdc3985 Iustin Pop
      logging.exception(msg)
109 afdc3985 Iustin Pop
    else:
110 afdc3985 Iustin Pop
      logging.error(msg)
111 2cc6781a Iustin Pop
  raise RPCFail(msg)
112 2cc6781a Iustin Pop
113 2cc6781a Iustin Pop
114 c657dcc9 Michael Hanselmann
def _GetConfig():
115 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
116 10c2650b Iustin Pop

117 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
118 93384844 Iustin Pop
  @return: a SimpleStore instance
119 10c2650b Iustin Pop

120 10c2650b Iustin Pop
  """
121 93384844 Iustin Pop
  return ssconf.SimpleStore()
122 c657dcc9 Michael Hanselmann
123 c657dcc9 Michael Hanselmann
124 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
125 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
126 10c2650b Iustin Pop

127 10c2650b Iustin Pop
  @type cluster_name: str
128 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
129 10c2650b Iustin Pop
      by the SshRunner constructor
130 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
131 10c2650b Iustin Pop
  @return: an SshRunner instance
132 10c2650b Iustin Pop

133 10c2650b Iustin Pop
  """
134 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
135 c92b310a Michael Hanselmann
136 c92b310a Michael Hanselmann
137 12bce260 Michael Hanselmann
def _Decompress(data):
138 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
139 12bce260 Michael Hanselmann

140 12bce260 Michael Hanselmann
  @type data: list or tuple
141 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
142 12bce260 Michael Hanselmann
  @rtype: str
143 12bce260 Michael Hanselmann
  @return: Decompressed data
144 12bce260 Michael Hanselmann

145 12bce260 Michael Hanselmann
  """
146 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
147 12bce260 Michael Hanselmann
  assert len(data) == 2
148 12bce260 Michael Hanselmann
  (encoding, content) = data
149 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
150 12bce260 Michael Hanselmann
    return content
151 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
152 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
153 12bce260 Michael Hanselmann
  else:
154 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
155 12bce260 Michael Hanselmann
156 12bce260 Michael Hanselmann
157 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
158 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
159 76ab5558 Michael Hanselmann

160 10c2650b Iustin Pop
  @type path: str
161 10c2650b Iustin Pop
  @param path: the directory to clean
162 76ab5558 Michael Hanselmann
  @type exclude: list
163 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
164 10c2650b Iustin Pop
      to the empty list
165 76ab5558 Michael Hanselmann

166 76ab5558 Michael Hanselmann
  """
167 714ea7ca Iustin Pop
  if path not in _ALLOWED_CLEAN_DIRS:
168 714ea7ca Iustin Pop
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
169 714ea7ca Iustin Pop
          path)
170 714ea7ca Iustin Pop
171 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
172 3956cee1 Michael Hanselmann
    return
173 3bc6be5c Iustin Pop
  if exclude is None:
174 3bc6be5c Iustin Pop
    exclude = []
175 3bc6be5c Iustin Pop
  else:
176 3bc6be5c Iustin Pop
    # Normalize excluded paths
177 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
178 76ab5558 Michael Hanselmann
179 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
180 c4feafe8 Iustin Pop
    full_name = utils.PathJoin(path, rel_name)
181 76ab5558 Michael Hanselmann
    if full_name in exclude:
182 76ab5558 Michael Hanselmann
      continue
183 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
184 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
185 3956cee1 Michael Hanselmann
186 3956cee1 Michael Hanselmann
187 360b0dc2 Iustin Pop
def _BuildUploadFileList():
188 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
189 360b0dc2 Iustin Pop

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

192 360b0dc2 Iustin Pop
  """
193 b397a7d2 Iustin Pop
  allowed_files = set([
194 b397a7d2 Iustin Pop
    constants.CLUSTER_CONF_FILE,
195 b397a7d2 Iustin Pop
    constants.ETC_HOSTS,
196 b397a7d2 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
197 b397a7d2 Iustin Pop
    constants.VNC_PASSWORD_FILE,
198 b397a7d2 Iustin Pop
    constants.RAPI_CERT_FILE,
199 b397a7d2 Iustin Pop
    constants.RAPI_USERS_FILE,
200 6b7d5878 Michael Hanselmann
    constants.CONFD_HMAC_KEY,
201 ff89a747 Michael Hanselmann
    constants.CLUSTER_DOMAIN_SECRET_FILE,
202 b397a7d2 Iustin Pop
    ])
203 b397a7d2 Iustin Pop
204 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
205 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
206 b397a7d2 Iustin Pop
    allowed_files.update(hv_class.GetAncillaryFiles())
207 b397a7d2 Iustin Pop
208 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
209 360b0dc2 Iustin Pop
210 360b0dc2 Iustin Pop
211 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
212 360b0dc2 Iustin Pop
213 360b0dc2 Iustin Pop
214 1bc59f76 Michael Hanselmann
def JobQueuePurge():
215 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
216 10c2650b Iustin Pop

217 c8457ce7 Iustin Pop
  @rtype: tuple
218 c8457ce7 Iustin Pop
  @return: True, None
219 24fc781f Michael Hanselmann

220 24fc781f Michael Hanselmann
  """
221 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
222 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
223 24fc781f Michael Hanselmann
224 24fc781f Michael Hanselmann
225 bd1e4562 Iustin Pop
def GetMasterInfo():
226 bd1e4562 Iustin Pop
  """Returns master information.
227 bd1e4562 Iustin Pop

228 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
229 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
230 bd1e4562 Iustin Pop

231 bd1e4562 Iustin Pop
  @rtype: tuple
232 d8e0caa6 Manuel Franceschini
  @return: master_netdev, master_ip, master_name, primary_ip_family
233 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
234 b1b6ea87 Iustin Pop

235 b1b6ea87 Iustin Pop
  """
236 b1b6ea87 Iustin Pop
  try:
237 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
238 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
239 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
240 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
241 d8e0caa6 Manuel Franceschini
    primary_ip_family = cfg.GetPrimaryIPFamily()
242 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
243 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
244 d8e0caa6 Manuel Franceschini
  return (master_netdev, master_ip, master_node, primary_ip_family)
245 b1b6ea87 Iustin Pop
246 b1b6ea87 Iustin Pop
247 3583908a Guido Trotter
def StartMaster(start_daemons, no_voting):
248 a8083063 Iustin Pop
  """Activate local node as master node.
249 a8083063 Iustin Pop

250 91492e57 Iustin Pop
  The function will either try activate the IP address of the master
251 91492e57 Iustin Pop
  (unless someone else has it) or also start the master daemons, based
252 91492e57 Iustin Pop
  on the start_daemons parameter.
253 10c2650b Iustin Pop

254 10c2650b Iustin Pop
  @type start_daemons: boolean
255 91492e57 Iustin Pop
  @param start_daemons: whether to start the master daemons
256 91492e57 Iustin Pop
      (ganeti-masterd and ganeti-rapi), or (if false) activate the
257 91492e57 Iustin Pop
      master ip
258 3583908a Guido Trotter
  @type no_voting: boolean
259 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
260 3583908a Guido Trotter
      (if start_daemons is True), but still non-interactively
261 10c2650b Iustin Pop
  @rtype: None
262 a8083063 Iustin Pop

263 a8083063 Iustin Pop
  """
264 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
265 d8e0caa6 Manuel Franceschini
  master_netdev, master_ip, _, family = GetMasterInfo()
266 a8083063 Iustin Pop
267 396b5733 Iustin Pop
  err_msgs = []
268 91492e57 Iustin Pop
  # either start the master and rapi daemons
269 b1b6ea87 Iustin Pop
  if start_daemons:
270 3583908a Guido Trotter
    if no_voting:
271 f154a7a3 Michael Hanselmann
      masterd_args = "--no-voting --yes-do-it"
272 f154a7a3 Michael Hanselmann
    else:
273 f154a7a3 Michael Hanselmann
      masterd_args = ""
274 f154a7a3 Michael Hanselmann
275 f154a7a3 Michael Hanselmann
    env = {
276 f154a7a3 Michael Hanselmann
      "EXTRA_MASTERD_ARGS": masterd_args,
277 f154a7a3 Michael Hanselmann
      }
278 f154a7a3 Michael Hanselmann
279 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
280 f154a7a3 Michael Hanselmann
    if result.failed:
281 f154a7a3 Michael Hanselmann
      msg = "Can't start Ganeti master: %s" % result.output
282 f154a7a3 Michael Hanselmann
      logging.error(msg)
283 f154a7a3 Michael Hanselmann
      err_msgs.append(msg)
284 91492e57 Iustin Pop
  # or activate the IP
285 91492e57 Iustin Pop
  else:
286 91492e57 Iustin Pop
    if netutils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
287 8b312c1d Manuel Franceschini
      if netutils.IPAddress.Own(master_ip):
288 91492e57 Iustin Pop
        # we already have the ip:
289 91492e57 Iustin Pop
        logging.debug("Master IP already configured, doing nothing")
290 91492e57 Iustin Pop
      else:
291 91492e57 Iustin Pop
        msg = "Someone else has the master ip, not activating"
292 91492e57 Iustin Pop
        logging.error(msg)
293 91492e57 Iustin Pop
        err_msgs.append(msg)
294 91492e57 Iustin Pop
    else:
295 d8e0caa6 Manuel Franceschini
      ipcls = netutils.IP4Address
296 d8e0caa6 Manuel Franceschini
      if family == netutils.IP6Address.family:
297 d8e0caa6 Manuel Franceschini
        ipcls = netutils.IP6Address
298 e7323b5e Manuel Franceschini
299 e7323b5e Manuel Franceschini
      result = utils.RunCmd(["ip", "address", "add",
300 d8e0caa6 Manuel Franceschini
                             "%s/%d" % (master_ip, ipcls.iplen),
301 91492e57 Iustin Pop
                             "dev", master_netdev, "label",
302 91492e57 Iustin Pop
                             "%s:0" % master_netdev])
303 91492e57 Iustin Pop
      if result.failed:
304 91492e57 Iustin Pop
        msg = "Can't activate master IP: %s" % result.output
305 91492e57 Iustin Pop
        logging.error(msg)
306 91492e57 Iustin Pop
        err_msgs.append(msg)
307 91492e57 Iustin Pop
308 e7323b5e Manuel Franceschini
      # we ignore the exit code of the following cmds
309 d8e0caa6 Manuel Franceschini
      if ipcls == netutils.IP4Address:
310 e7323b5e Manuel Franceschini
        utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev, "-s",
311 e7323b5e Manuel Franceschini
                      master_ip, master_ip])
312 d8e0caa6 Manuel Franceschini
      elif ipcls == netutils.IP6Address:
313 2dc1237c Manuel Franceschini
        try:
314 2dc1237c Manuel Franceschini
          utils.RunCmd(["ndisc6", "-q", "-r 3", master_ip, master_netdev])
315 2dc1237c Manuel Franceschini
        except errors.OpExecError:
316 2dc1237c Manuel Franceschini
          # TODO: Better error reporting
317 2dc1237c Manuel Franceschini
          logging.warning("Can't execute ndisc6, please install if missing")
318 b726aff0 Iustin Pop
319 396b5733 Iustin Pop
  if err_msgs:
320 396b5733 Iustin Pop
    _Fail("; ".join(err_msgs))
321 afdc3985 Iustin Pop
322 a8083063 Iustin Pop
323 1c65840b Iustin Pop
def StopMaster(stop_daemons):
324 a8083063 Iustin Pop
  """Deactivate this node as master.
325 a8083063 Iustin Pop

326 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
327 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
328 10c2650b Iustin Pop
  stop_daemons parameter.
329 10c2650b Iustin Pop

330 10c2650b Iustin Pop
  @type stop_daemons: boolean
331 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
332 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
333 10c2650b Iustin Pop
  @rtype: None
334 a8083063 Iustin Pop

335 a8083063 Iustin Pop
  """
336 6c00d19a Iustin Pop
  # TODO: log and report back to the caller the error failures; we
337 6c00d19a Iustin Pop
  # need to decide in which case we fail the RPC for this
338 2a52a064 Iustin Pop
339 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
340 d8e0caa6 Manuel Franceschini
  master_netdev, master_ip, _, family = GetMasterInfo()
341 a8083063 Iustin Pop
342 d8e0caa6 Manuel Franceschini
  ipcls = netutils.IP4Address
343 d8e0caa6 Manuel Franceschini
  if family == netutils.IP6Address.family:
344 d8e0caa6 Manuel Franceschini
    ipcls = netutils.IP6Address
345 e7323b5e Manuel Franceschini
346 e7323b5e Manuel Franceschini
  result = utils.RunCmd(["ip", "address", "del",
347 d8e0caa6 Manuel Franceschini
                         "%s/%d" % (master_ip, ipcls.iplen),
348 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
349 a8083063 Iustin Pop
  if result.failed:
350 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
351 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
352 b1b6ea87 Iustin Pop
353 b1b6ea87 Iustin Pop
  if stop_daemons:
354 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
355 f154a7a3 Michael Hanselmann
    if result.failed:
356 f154a7a3 Michael Hanselmann
      logging.error("Could not stop Ganeti master, command %s had exitcode %s"
357 f154a7a3 Michael Hanselmann
                    " and error %s",
358 f154a7a3 Michael Hanselmann
                    result.cmd, result.exit_code, result.output)
359 a8083063 Iustin Pop
360 a8083063 Iustin Pop
361 19ddc57a René Nussbaumer
def EtcHostsModify(mode, host, ip):
362 19ddc57a René Nussbaumer
  """Modify a host entry in /etc/hosts.
363 19ddc57a René Nussbaumer

364 19ddc57a René Nussbaumer
  @param mode: The mode to operate. Either add or remove entry
365 19ddc57a René Nussbaumer
  @param host: The host to operate on
366 19ddc57a René Nussbaumer
  @param ip: The ip associated with the entry
367 19ddc57a René Nussbaumer

368 19ddc57a René Nussbaumer
  """
369 19ddc57a René Nussbaumer
  if mode == constants.ETC_HOSTS_ADD:
370 19ddc57a René Nussbaumer
    if not ip:
371 19ddc57a René Nussbaumer
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
372 19ddc57a René Nussbaumer
              " present")
373 19ddc57a René Nussbaumer
    utils.AddHostToEtcHosts(host, ip)
374 19ddc57a René Nussbaumer
  elif mode == constants.ETC_HOSTS_REMOVE:
375 19ddc57a René Nussbaumer
    if ip:
376 19ddc57a René Nussbaumer
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
377 19ddc57a René Nussbaumer
              " parameter is present")
378 19ddc57a René Nussbaumer
    utils.RemoveHostFromEtcHosts(host)
379 19ddc57a René Nussbaumer
  else:
380 19ddc57a René Nussbaumer
    RPCFail("Mode not supported")
381 19ddc57a René Nussbaumer
382 19ddc57a René Nussbaumer
383 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
384 10c2650b Iustin Pop
  """Cleans up and remove the current node.
385 10c2650b Iustin Pop

386 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
387 10c2650b Iustin Pop
  from the cluster.
388 10c2650b Iustin Pop

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

393 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
394 b989b9d9 Ken Wehr

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

430 e69d05fd Iustin Pop
  @type vgname: C{string}
431 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
432 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
433 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
434 e69d05fd Iustin Pop
      memory information
435 e69d05fd Iustin Pop
  @rtype: C{dict}
436 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
437 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
438 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
439 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
440 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
441 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
442 a8083063 Iustin Pop

443 098c0958 Michael Hanselmann
  """
444 a8083063 Iustin Pop
  outputarray = {}
445 673cd9c4 René Nussbaumer
446 cb6a0296 Iustin Pop
  if vgname is not None:
447 cb6a0296 Iustin Pop
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
448 cb6a0296 Iustin Pop
    vg_free = vg_size = None
449 cb6a0296 Iustin Pop
    if vginfo:
450 cb6a0296 Iustin Pop
      vg_free = int(round(vginfo[0][0], 0))
451 cb6a0296 Iustin Pop
      vg_size = int(round(vginfo[0][1], 0))
452 cb6a0296 Iustin Pop
    outputarray['vg_size'] = vg_size
453 cb6a0296 Iustin Pop
    outputarray['vg_free'] = vg_free
454 cb6a0296 Iustin Pop
455 cb6a0296 Iustin Pop
  if hypervisor_type is not None:
456 cb6a0296 Iustin Pop
    hyper = hypervisor.GetHypervisor(hypervisor_type)
457 cb6a0296 Iustin Pop
    hyp_info = hyper.GetNodeInfo()
458 cb6a0296 Iustin Pop
    if hyp_info is not None:
459 cb6a0296 Iustin Pop
      outputarray.update(hyp_info)
460 a8083063 Iustin Pop
461 13998ef2 Michael Hanselmann
  outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
462 3ef10550 Michael Hanselmann
463 c26a6bd2 Iustin Pop
  return outputarray
464 a8083063 Iustin Pop
465 a8083063 Iustin Pop
466 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
467 a8083063 Iustin Pop
  """Verify the status of the local node.
468 a8083063 Iustin Pop

469 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
470 e69d05fd Iustin Pop
  local node.
471 e69d05fd Iustin Pop

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

475 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
476 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
477 e69d05fd Iustin Pop
  report).
478 a8083063 Iustin Pop

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

483 e69d05fd Iustin Pop
  @type what: C{dict}
484 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
485 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
486 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
487 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
488 e69d05fd Iustin Pop
        connectivity with
489 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
490 10c2650b Iustin Pop
  @rtype: dict
491 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
492 10c2650b Iustin Pop
      values representing the result of the checks
493 a8083063 Iustin Pop

494 a8083063 Iustin Pop
  """
495 a8083063 Iustin Pop
  result = {}
496 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
497 a744b676 Manuel Franceschini
  port = netutils.GetDaemonPort(constants.NODED)
498 8964ee14 Iustin Pop
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
499 a8083063 Iustin Pop
500 8964ee14 Iustin Pop
  if constants.NV_HYPERVISOR in what and vm_capable:
501 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
502 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
503 0cf5e7f5 Iustin Pop
      try:
504 0cf5e7f5 Iustin Pop
        val = hypervisor.GetHypervisor(hv_name).Verify()
505 0cf5e7f5 Iustin Pop
      except errors.HypervisorError, err:
506 0cf5e7f5 Iustin Pop
        val = "Error while checking hypervisor: %s" % str(err)
507 0cf5e7f5 Iustin Pop
      tmp[hv_name] = val
508 25361b9a Iustin Pop
509 58a59652 Iustin Pop
  if constants.NV_HVPARAMS in what and vm_capable:
510 58a59652 Iustin Pop
    result[constants.NV_HVPARAMS] = tmp = []
511 58a59652 Iustin Pop
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
512 58a59652 Iustin Pop
      try:
513 58a59652 Iustin Pop
        logging.info("Validating hv %s, %s", hv_name, hvparms)
514 58a59652 Iustin Pop
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
515 58a59652 Iustin Pop
      except errors.HypervisorError, err:
516 58a59652 Iustin Pop
        tmp.append((source, hv_name, str(err)))
517 58a59652 Iustin Pop
518 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
519 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
520 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
521 25361b9a Iustin Pop
522 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
523 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
524 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
525 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
526 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
527 a8083063 Iustin Pop
      if not success:
528 25361b9a Iustin Pop
        tmp[node] = message
529 25361b9a Iustin Pop
530 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
531 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
532 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
533 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
534 9d4bfc96 Iustin Pop
      if name == my_name:
535 9d4bfc96 Iustin Pop
        my_pip = pip
536 9d4bfc96 Iustin Pop
        my_sip = sip
537 9d4bfc96 Iustin Pop
        break
538 9d4bfc96 Iustin Pop
    if not my_pip:
539 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
540 25361b9a Iustin Pop
                      " in the node list")
541 9d4bfc96 Iustin Pop
    else:
542 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
543 9d4bfc96 Iustin Pop
        fail = []
544 a744b676 Manuel Franceschini
        if not netutils.TcpPing(pip, port, source=my_pip):
545 9d4bfc96 Iustin Pop
          fail.append("primary")
546 9d4bfc96 Iustin Pop
        if sip != pip:
547 a744b676 Manuel Franceschini
          if not netutils.TcpPing(sip, port, source=my_sip):
548 9d4bfc96 Iustin Pop
            fail.append("secondary")
549 9d4bfc96 Iustin Pop
        if fail:
550 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
551 25361b9a Iustin Pop
                       " and ".join(fail))
552 25361b9a Iustin Pop
553 a3a5f850 Iustin Pop
  if constants.NV_MASTERIP in what:
554 a3a5f850 Iustin Pop
    # FIXME: add checks on incoming data structures (here and in the
555 a3a5f850 Iustin Pop
    # rest of the function)
556 a3a5f850 Iustin Pop
    master_name, master_ip = what[constants.NV_MASTERIP]
557 a3a5f850 Iustin Pop
    if master_name == my_name:
558 9769bb78 Manuel Franceschini
      source = constants.IP4_ADDRESS_LOCALHOST
559 a3a5f850 Iustin Pop
    else:
560 a3a5f850 Iustin Pop
      source = None
561 a744b676 Manuel Franceschini
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
562 a3a5f850 Iustin Pop
                                                  source=source)
563 a3a5f850 Iustin Pop
564 16f41f24 René Nussbaumer
  if constants.NV_OOB_PATHS in what:
565 16f41f24 René Nussbaumer
    result[constants.NV_OOB_PATHS] = tmp = []
566 16f41f24 René Nussbaumer
    for path in what[constants.NV_OOB_PATHS]:
567 16f41f24 René Nussbaumer
      try:
568 16f41f24 René Nussbaumer
        st = os.stat(path)
569 16f41f24 René Nussbaumer
      except OSError, err:
570 16f41f24 René Nussbaumer
        tmp.append("error stating out of band helper: %s" % err)
571 16f41f24 René Nussbaumer
      else:
572 16f41f24 René Nussbaumer
        if stat.S_ISREG(st.st_mode):
573 16f41f24 René Nussbaumer
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
574 16f41f24 René Nussbaumer
            tmp.append(None)
575 16f41f24 René Nussbaumer
          else:
576 16f41f24 René Nussbaumer
            tmp.append("out of band helper %s is not executable" % path)
577 16f41f24 René Nussbaumer
        else:
578 16f41f24 René Nussbaumer
          tmp.append("out of band helper %s is not a file" % path)
579 16f41f24 René Nussbaumer
580 8964ee14 Iustin Pop
  if constants.NV_LVLIST in what and vm_capable:
581 ed904904 Iustin Pop
    try:
582 84d7e26b Dmitry Chernyak
      val = GetVolumeList(utils.ListVolumeGroups().keys())
583 ed904904 Iustin Pop
    except RPCFail, err:
584 ed904904 Iustin Pop
      val = str(err)
585 ed904904 Iustin Pop
    result[constants.NV_LVLIST] = val
586 25361b9a Iustin Pop
587 8964ee14 Iustin Pop
  if constants.NV_INSTANCELIST in what and vm_capable:
588 0cf5e7f5 Iustin Pop
    # GetInstanceList can fail
589 0cf5e7f5 Iustin Pop
    try:
590 0cf5e7f5 Iustin Pop
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
591 0cf5e7f5 Iustin Pop
    except RPCFail, err:
592 0cf5e7f5 Iustin Pop
      val = str(err)
593 0cf5e7f5 Iustin Pop
    result[constants.NV_INSTANCELIST] = val
594 25361b9a Iustin Pop
595 8964ee14 Iustin Pop
  if constants.NV_VGLIST in what and vm_capable:
596 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
597 25361b9a Iustin Pop
598 8964ee14 Iustin Pop
  if constants.NV_PVLIST in what and vm_capable:
599 d091393e Iustin Pop
    result[constants.NV_PVLIST] = \
600 d091393e Iustin Pop
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
601 d091393e Iustin Pop
                                   filter_allocatable=False)
602 d091393e Iustin Pop
603 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
604 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
605 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
606 25361b9a Iustin Pop
607 8964ee14 Iustin Pop
  if constants.NV_HVINFO in what and vm_capable:
608 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
609 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
610 9d4bfc96 Iustin Pop
611 8964ee14 Iustin Pop
  if constants.NV_DRBDLIST in what and vm_capable:
612 6d2e83d5 Iustin Pop
    try:
613 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
614 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
615 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
616 f6eaed12 Iustin Pop
      used_minors = str(err)
617 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
618 6d2e83d5 Iustin Pop
619 8964ee14 Iustin Pop
  if constants.NV_DRBDHELPER in what and vm_capable:
620 7ef40fbe Luca Bigliardi
    status = True
621 7ef40fbe Luca Bigliardi
    try:
622 7ef40fbe Luca Bigliardi
      payload = bdev.BaseDRBD.GetUsermodeHelper()
623 7ef40fbe Luca Bigliardi
    except errors.BlockDeviceError, err:
624 7ef40fbe Luca Bigliardi
      logging.error("Can't get DRBD usermode helper: %s", str(err))
625 7ef40fbe Luca Bigliardi
      status = False
626 7ef40fbe Luca Bigliardi
      payload = str(err)
627 7ef40fbe Luca Bigliardi
    result[constants.NV_DRBDHELPER] = (status, payload)
628 7ef40fbe Luca Bigliardi
629 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
630 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
631 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
632 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
633 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
634 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
635 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
636 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
637 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
638 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
639 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
640 313b2dd4 Michael Hanselmann
641 313b2dd4 Michael Hanselmann
  if constants.NV_TIME in what:
642 313b2dd4 Michael Hanselmann
    result[constants.NV_TIME] = utils.SplitTime(time.time())
643 313b2dd4 Michael Hanselmann
644 8964ee14 Iustin Pop
  if constants.NV_OSLIST in what and vm_capable:
645 b0d85178 Iustin Pop
    result[constants.NV_OSLIST] = DiagnoseOS()
646 b0d85178 Iustin Pop
647 c26a6bd2 Iustin Pop
  return result
648 a8083063 Iustin Pop
649 a8083063 Iustin Pop
650 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
651 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
652 a8083063 Iustin Pop

653 84d7e26b Dmitry Chernyak
  @type vg_names: list
654 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
655 397693d3 Iustin Pop
      empty for all volume groups
656 10c2650b Iustin Pop
  @rtype: dict
657 10c2650b Iustin Pop
  @return:
658 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
659 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
660 10c2650b Iustin Pop

661 84d7e26b Dmitry Chernyak
        {'xenvg/test1': ('20.06', True, True)}
662 10c2650b Iustin Pop

663 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
664 10c2650b Iustin Pop
      details.
665 a8083063 Iustin Pop

666 a8083063 Iustin Pop
  """
667 cb2037a2 Iustin Pop
  lvs = {}
668 cb2037a2 Iustin Pop
  sep = '|'
669 397693d3 Iustin Pop
  if not vg_names:
670 397693d3 Iustin Pop
    vg_names = []
671 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
672 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
673 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
674 a8083063 Iustin Pop
  if result.failed:
675 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
676 cb2037a2 Iustin Pop
677 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
678 df4c2628 Iustin Pop
    line = line.strip()
679 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
680 df4c2628 Iustin Pop
    if not match:
681 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
682 df4c2628 Iustin Pop
      continue
683 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
684 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
685 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
686 33f2a81a Iustin Pop
    virtual = attr[0] == 'v'
687 33f2a81a Iustin Pop
    if virtual:
688 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
689 33f2a81a Iustin Pop
      # don't really hold data
690 33f2a81a Iustin Pop
      continue
691 84d7e26b Dmitry Chernyak
    lvs[vg_name+"/"+name] = (size, inactive, online)
692 cb2037a2 Iustin Pop
693 cb2037a2 Iustin Pop
  return lvs
694 a8083063 Iustin Pop
695 a8083063 Iustin Pop
696 a8083063 Iustin Pop
def ListVolumeGroups():
697 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
698 a8083063 Iustin Pop

699 10c2650b Iustin Pop
  @rtype: dict
700 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
701 10c2650b Iustin Pop
      size of the volume
702 a8083063 Iustin Pop

703 a8083063 Iustin Pop
  """
704 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
705 a8083063 Iustin Pop
706 a8083063 Iustin Pop
707 dcb93971 Michael Hanselmann
def NodeVolumes():
708 dcb93971 Michael Hanselmann
  """List all volumes on this node.
709 dcb93971 Michael Hanselmann

710 10c2650b Iustin Pop
  @rtype: list
711 10c2650b Iustin Pop
  @return:
712 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
713 10c2650b Iustin Pop
      - name: the logical volume name,
714 10c2650b Iustin Pop
      - size: the size of the logical volume
715 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
716 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
717 10c2650b Iustin Pop

718 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
719 10c2650b Iustin Pop
    error.
720 10c2650b Iustin Pop

721 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
722 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
723 10c2650b Iustin Pop
    multiple times.
724 10c2650b Iustin Pop

725 dcb93971 Michael Hanselmann
  """
726 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
727 dcb93971 Michael Hanselmann
                         "--separator=|",
728 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
729 dcb93971 Michael Hanselmann
  if result.failed:
730 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
731 10bfe6cb Iustin Pop
          result.output)
732 dcb93971 Michael Hanselmann
733 dcb93971 Michael Hanselmann
  def parse_dev(dev):
734 89e5ab02 Iustin Pop
    return dev.split('(')[0]
735 89e5ab02 Iustin Pop
736 89e5ab02 Iustin Pop
  def handle_dev(dev):
737 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
738 dcb93971 Michael Hanselmann
739 dcb93971 Michael Hanselmann
  def map_line(line):
740 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
741 89e5ab02 Iustin Pop
    return [{'name': line[0], 'size': line[1],
742 89e5ab02 Iustin Pop
             'dev': dev, 'vg': line[3]} for dev in handle_dev(line[2])]
743 89e5ab02 Iustin Pop
744 89e5ab02 Iustin Pop
  all_devs = []
745 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
746 89e5ab02 Iustin Pop
    if line.count('|') >= 3:
747 89e5ab02 Iustin Pop
      all_devs.extend(map_line(line.split('|')))
748 89e5ab02 Iustin Pop
    else:
749 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
750 89e5ab02 Iustin Pop
  return all_devs
751 dcb93971 Michael Hanselmann
752 dcb93971 Michael Hanselmann
753 a8083063 Iustin Pop
def BridgesExist(bridges_list):
754 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
755 a8083063 Iustin Pop

756 b1206984 Iustin Pop
  @rtype: boolean
757 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
758 a8083063 Iustin Pop

759 a8083063 Iustin Pop
  """
760 35c0c8da Iustin Pop
  missing = []
761 a8083063 Iustin Pop
  for bridge in bridges_list:
762 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
763 35c0c8da Iustin Pop
      missing.append(bridge)
764 a8083063 Iustin Pop
765 35c0c8da Iustin Pop
  if missing:
766 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
767 35c0c8da Iustin Pop
768 a8083063 Iustin Pop
769 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
770 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
771 a8083063 Iustin Pop

772 e69d05fd Iustin Pop
  @type hypervisor_list: list
773 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
774 e69d05fd Iustin Pop

775 e69d05fd Iustin Pop
  @rtype: list
776 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
777 10c2650b Iustin Pop
    - instance1.example.com
778 10c2650b Iustin Pop
    - instance2.example.com
779 a8083063 Iustin Pop

780 098c0958 Michael Hanselmann
  """
781 e69d05fd Iustin Pop
  results = []
782 e69d05fd Iustin Pop
  for hname in hypervisor_list:
783 e69d05fd Iustin Pop
    try:
784 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
785 e69d05fd Iustin Pop
      results.extend(names)
786 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
787 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
788 aca13712 Iustin Pop
            hname, err, exc=True)
789 a8083063 Iustin Pop
790 e69d05fd Iustin Pop
  return results
791 a8083063 Iustin Pop
792 a8083063 Iustin Pop
793 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
794 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
795 a8083063 Iustin Pop

796 e69d05fd Iustin Pop
  @type instance: string
797 e69d05fd Iustin Pop
  @param instance: the instance name
798 e69d05fd Iustin Pop
  @type hname: string
799 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
800 a8083063 Iustin Pop

801 e69d05fd Iustin Pop
  @rtype: dict
802 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
803 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
804 e69d05fd Iustin Pop
      - state: xen state of instance (string)
805 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
806 a8083063 Iustin Pop

807 098c0958 Michael Hanselmann
  """
808 a8083063 Iustin Pop
  output = {}
809 a8083063 Iustin Pop
810 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
811 a8083063 Iustin Pop
  if iinfo is not None:
812 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
813 a8083063 Iustin Pop
    output['state'] = iinfo[4]
814 a8083063 Iustin Pop
    output['time'] = iinfo[5]
815 a8083063 Iustin Pop
816 c26a6bd2 Iustin Pop
  return output
817 a8083063 Iustin Pop
818 a8083063 Iustin Pop
819 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
820 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
821 56e7640c Iustin Pop

822 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
823 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
824 56e7640c Iustin Pop

825 56e7640c Iustin Pop
  @rtype: tuple
826 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
827 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
828 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
829 56e7640c Iustin Pop

830 56e7640c Iustin Pop
  """
831 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
832 afdc3985 Iustin Pop
  iname = instance.name
833 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
834 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
835 56e7640c Iustin Pop
836 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
837 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
838 56e7640c Iustin Pop
    if not os.path.islink(link_name):
839 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
840 b8ebd37b Iustin Pop
                      iname, link_name, idx)
841 56e7640c Iustin Pop
842 56e7640c Iustin Pop
843 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
844 a8083063 Iustin Pop
  """Gather data about all instances.
845 a8083063 Iustin Pop

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

850 e69d05fd Iustin Pop
  @type hypervisor_list: list
851 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
852 e69d05fd Iustin Pop

853 955db481 Guido Trotter
  @rtype: dict
854 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
855 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
856 e69d05fd Iustin Pop
      - state: xen state of instance (string)
857 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
858 10c2650b Iustin Pop
      - vcpus: the number of vcpus
859 a8083063 Iustin Pop

860 098c0958 Michael Hanselmann
  """
861 a8083063 Iustin Pop
  output = {}
862 a8083063 Iustin Pop
863 e69d05fd Iustin Pop
  for hname in hypervisor_list:
864 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
865 e69d05fd Iustin Pop
    if iinfo:
866 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
867 f23b5ae8 Iustin Pop
        value = {
868 e69d05fd Iustin Pop
          'memory': memory,
869 e69d05fd Iustin Pop
          'vcpus': vcpus,
870 e69d05fd Iustin Pop
          'state': state,
871 e69d05fd Iustin Pop
          'time': times,
872 e69d05fd Iustin Pop
          }
873 b33b6f55 Iustin Pop
        if name in output:
874 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
875 b33b6f55 Iustin Pop
          # and not state and time which can change between the
876 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
877 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
878 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
879 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
880 2fa74ef4 Iustin Pop
                    " with different parameters", name)
881 f23b5ae8 Iustin Pop
        output[name] = value
882 a8083063 Iustin Pop
883 c26a6bd2 Iustin Pop
  return output
884 a8083063 Iustin Pop
885 a8083063 Iustin Pop
886 81a3406c Iustin Pop
def _InstanceLogName(kind, os_name, instance):
887 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
888 81a3406c Iustin Pop

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

892 81a3406c Iustin Pop
  @type kind: string
893 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
894 81a3406c Iustin Pop
  @type os_name: string
895 81a3406c Iustin Pop
  @param os_name: the os name
896 81a3406c Iustin Pop
  @type instance: string
897 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
898 81a3406c Iustin Pop

899 81a3406c Iustin Pop
  """
900 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
901 1d466a4f Michael Hanselmann
  base = ("%s-%s-%s-%s.log" %
902 1d466a4f Michael Hanselmann
          (kind, os_name, instance, utils.TimestampForFilename()))
903 81a3406c Iustin Pop
  return utils.PathJoin(constants.LOG_OS_DIR, base)
904 81a3406c Iustin Pop
905 81a3406c Iustin Pop
906 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
907 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
908 a8083063 Iustin Pop

909 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
910 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
911 e557bae9 Guido Trotter
  @type reinstall: boolean
912 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
913 4a0e011f Iustin Pop
  @type debug: integer
914 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
915 c26a6bd2 Iustin Pop
  @rtype: None
916 a8083063 Iustin Pop

917 a8083063 Iustin Pop
  """
918 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
919 255dcebd Iustin Pop
920 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
921 e557bae9 Guido Trotter
  if reinstall:
922 e557bae9 Guido Trotter
    create_env['INSTANCE_REINSTALL'] = "1"
923 a8083063 Iustin Pop
924 81a3406c Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name)
925 decd5f45 Iustin Pop
926 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
927 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
928 decd5f45 Iustin Pop
  if result.failed:
929 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
930 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
931 18682bca Iustin Pop
                  result.output)
932 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
933 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
934 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
935 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
936 decd5f45 Iustin Pop
937 decd5f45 Iustin Pop
938 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
939 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
940 decd5f45 Iustin Pop

941 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
942 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
943 d15a9ad3 Guido Trotter
  @type old_name: string
944 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
945 4a0e011f Iustin Pop
  @type debug: integer
946 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
947 10c2650b Iustin Pop
  @rtype: boolean
948 10c2650b Iustin Pop
  @return: the success of the operation
949 decd5f45 Iustin Pop

950 decd5f45 Iustin Pop
  """
951 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
952 decd5f45 Iustin Pop
953 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
954 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
955 decd5f45 Iustin Pop
956 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
957 81a3406c Iustin Pop
                             "%s-%s" % (old_name, instance.name))
958 a8083063 Iustin Pop
959 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
960 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
961 a8083063 Iustin Pop
962 a8083063 Iustin Pop
  if result.failed:
963 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
964 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
965 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
966 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
967 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
968 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
969 a8083063 Iustin Pop
970 a8083063 Iustin Pop
971 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
972 3536c792 Iustin Pop
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
973 3536c792 Iustin Pop
                        (instance_name, constants.DISK_SEPARATOR, idx))
974 5282084b Iustin Pop
975 5282084b Iustin Pop
976 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
977 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
978 9332fd8a Iustin Pop

979 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
980 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
981 9332fd8a Iustin Pop

982 9332fd8a Iustin Pop

983 5282084b Iustin Pop
  @param instance_name: the name of the target instance
984 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
985 5282084b Iustin Pop
  @param idx: the disk index
986 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
987 9332fd8a Iustin Pop

988 9332fd8a Iustin Pop
  """
989 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
990 9332fd8a Iustin Pop
  try:
991 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
992 5282084b Iustin Pop
  except OSError, err:
993 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
994 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
995 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
996 9332fd8a Iustin Pop
        os.remove(link_name)
997 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
998 9332fd8a Iustin Pop
    else:
999 9332fd8a Iustin Pop
      raise
1000 9332fd8a Iustin Pop
1001 9332fd8a Iustin Pop
  return link_name
1002 9332fd8a Iustin Pop
1003 9332fd8a Iustin Pop
1004 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1005 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1006 3c9c571d Iustin Pop

1007 3c9c571d Iustin Pop
  """
1008 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1009 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1010 5282084b Iustin Pop
    if os.path.islink(link_name):
1011 3c9c571d Iustin Pop
      try:
1012 03dfa658 Iustin Pop
        os.remove(link_name)
1013 03dfa658 Iustin Pop
      except OSError:
1014 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1015 3c9c571d Iustin Pop
1016 3c9c571d Iustin Pop
1017 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1018 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1019 a8083063 Iustin Pop

1020 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1021 a8083063 Iustin Pop
  devices must be already assembled.
1022 a8083063 Iustin Pop

1023 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1024 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1025 069cfbf1 Iustin Pop
  @rtype: list
1026 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1027 10c2650b Iustin Pop

1028 a8083063 Iustin Pop
  """
1029 a8083063 Iustin Pop
  block_devices = []
1030 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1031 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1032 a8083063 Iustin Pop
    if device is None:
1033 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1034 a8083063 Iustin Pop
                                    str(disk))
1035 a8083063 Iustin Pop
    device.Open()
1036 9332fd8a Iustin Pop
    try:
1037 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1038 9332fd8a Iustin Pop
    except OSError, e:
1039 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1040 9332fd8a Iustin Pop
                                    e.strerror)
1041 9332fd8a Iustin Pop
1042 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1043 9332fd8a Iustin Pop
1044 a8083063 Iustin Pop
  return block_devices
1045 a8083063 Iustin Pop
1046 a8083063 Iustin Pop
1047 07813a9e Iustin Pop
def StartInstance(instance):
1048 a8083063 Iustin Pop
  """Start an instance.
1049 a8083063 Iustin Pop

1050 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1051 e69d05fd Iustin Pop
  @param instance: the instance object
1052 c26a6bd2 Iustin Pop
  @rtype: None
1053 a8083063 Iustin Pop

1054 098c0958 Michael Hanselmann
  """
1055 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1056 a8083063 Iustin Pop
1057 a8083063 Iustin Pop
  if instance.name in running_instances:
1058 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1059 c26a6bd2 Iustin Pop
    return
1060 a8083063 Iustin Pop
1061 a8083063 Iustin Pop
  try:
1062 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1063 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1064 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
1065 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1066 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1067 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1068 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1069 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1070 a8083063 Iustin Pop
1071 a8083063 Iustin Pop
1072 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1073 a8083063 Iustin Pop
  """Shut an instance down.
1074 a8083063 Iustin Pop

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

1077 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1078 e69d05fd Iustin Pop
  @param instance: the instance object
1079 6263189c Guido Trotter
  @type timeout: integer
1080 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1081 c26a6bd2 Iustin Pop
  @rtype: None
1082 a8083063 Iustin Pop

1083 098c0958 Michael Hanselmann
  """
1084 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1085 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1086 c26a6bd2 Iustin Pop
  iname = instance.name
1087 a8083063 Iustin Pop
1088 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1089 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1090 c26a6bd2 Iustin Pop
    return
1091 a8083063 Iustin Pop
1092 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1093 3c0cdc83 Michael Hanselmann
    def __init__(self):
1094 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1095 a8083063 Iustin Pop
1096 3c0cdc83 Michael Hanselmann
    def __call__(self):
1097 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1098 3c0cdc83 Michael Hanselmann
        return
1099 3c0cdc83 Michael Hanselmann
1100 3c0cdc83 Michael Hanselmann
      try:
1101 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1102 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1103 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1104 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1105 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1106 3c0cdc83 Michael Hanselmann
          return
1107 3c0cdc83 Michael Hanselmann
1108 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1109 3c0cdc83 Michael Hanselmann
1110 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1111 3c0cdc83 Michael Hanselmann
1112 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1113 3c0cdc83 Michael Hanselmann
1114 3c0cdc83 Michael Hanselmann
  try:
1115 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1116 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1117 a8083063 Iustin Pop
    # the shutdown did not succeed
1118 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1119 a8083063 Iustin Pop
1120 a8083063 Iustin Pop
    try:
1121 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1122 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1123 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1124 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1125 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1126 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1127 a8083063 Iustin Pop
1128 a8083063 Iustin Pop
    time.sleep(1)
1129 3c0cdc83 Michael Hanselmann
1130 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1131 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1132 3c9c571d Iustin Pop
1133 f28ec899 Guido Trotter
  try:
1134 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1135 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1136 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1137 f28ec899 Guido Trotter
1138 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1139 a8083063 Iustin Pop
1140 a8083063 Iustin Pop
1141 17c3f802 Guido Trotter
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1142 007a2f3e Alexander Schreiber
  """Reboot an instance.
1143 007a2f3e Alexander Schreiber

1144 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1145 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1146 10c2650b Iustin Pop
  @type reboot_type: str
1147 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1148 10c2650b Iustin Pop
    constants:
1149 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1150 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1151 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1152 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1153 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1154 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1155 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1156 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1157 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1158 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1159 c26a6bd2 Iustin Pop
  @rtype: None
1160 007a2f3e Alexander Schreiber

1161 007a2f3e Alexander Schreiber
  """
1162 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1163 007a2f3e Alexander Schreiber
1164 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1165 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1166 007a2f3e Alexander Schreiber
1167 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1168 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1169 007a2f3e Alexander Schreiber
    try:
1170 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1171 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1172 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1173 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1174 007a2f3e Alexander Schreiber
    try:
1175 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1176 07813a9e Iustin Pop
      return StartInstance(instance)
1177 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1178 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1179 007a2f3e Alexander Schreiber
  else:
1180 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1181 007a2f3e Alexander Schreiber
1182 007a2f3e Alexander Schreiber
1183 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1184 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1185 6906a9d8 Guido Trotter

1186 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1187 6906a9d8 Guido Trotter
  @param instance: the instance definition
1188 6906a9d8 Guido Trotter

1189 6906a9d8 Guido Trotter
  """
1190 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1191 cd42d0ad Guido Trotter
  try:
1192 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1193 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1194 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1195 c26a6bd2 Iustin Pop
  return info
1196 6906a9d8 Guido Trotter
1197 6906a9d8 Guido Trotter
1198 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1199 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1200 6906a9d8 Guido Trotter

1201 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1202 6906a9d8 Guido Trotter
  @param instance: the instance definition
1203 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1204 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1205 6906a9d8 Guido Trotter
  @type target: string
1206 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1207 6906a9d8 Guido Trotter

1208 6906a9d8 Guido Trotter
  """
1209 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1210 cd42d0ad Guido Trotter
  try:
1211 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1212 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1213 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1214 6906a9d8 Guido Trotter
1215 6906a9d8 Guido Trotter
1216 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1217 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1218 6906a9d8 Guido Trotter

1219 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1220 6906a9d8 Guido Trotter
  @param instance: the instance definition
1221 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1222 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1223 6906a9d8 Guido Trotter
  @type success: boolean
1224 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1225 6906a9d8 Guido Trotter

1226 6906a9d8 Guido Trotter
  """
1227 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1228 cd42d0ad Guido Trotter
  try:
1229 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1230 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1231 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1232 6906a9d8 Guido Trotter
1233 6906a9d8 Guido Trotter
1234 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1235 2a10865c Iustin Pop
  """Migrates an instance to another node.
1236 2a10865c Iustin Pop

1237 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1238 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1239 9f0e6b37 Iustin Pop
  @type target: string
1240 9f0e6b37 Iustin Pop
  @param target: the target node name
1241 9f0e6b37 Iustin Pop
  @type live: boolean
1242 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1243 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1244 9f0e6b37 Iustin Pop
  @rtype: tuple
1245 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1246 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1247 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1248 9f0e6b37 Iustin Pop

1249 2a10865c Iustin Pop
  """
1250 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1251 2a10865c Iustin Pop
1252 2a10865c Iustin Pop
  try:
1253 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1254 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1255 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1256 2a10865c Iustin Pop
1257 2a10865c Iustin Pop
1258 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1259 a8083063 Iustin Pop
  """Creates a block device for an instance.
1260 a8083063 Iustin Pop

1261 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1262 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1263 b1206984 Iustin Pop
  @type size: int
1264 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1265 b1206984 Iustin Pop
  @type owner: str
1266 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1267 b1206984 Iustin Pop
      used for device cache data
1268 b1206984 Iustin Pop
  @type on_primary: boolean
1269 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1270 b1206984 Iustin Pop
  @type info: string
1271 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1272 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1273 b1206984 Iustin Pop

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

1278 a8083063 Iustin Pop
  """
1279 7260cfbe Iustin Pop
  # TODO: remove the obsolete 'size' argument
1280 7260cfbe Iustin Pop
  # pylint: disable-msg=W0613
1281 a8083063 Iustin Pop
  clist = []
1282 a8083063 Iustin Pop
  if disk.children:
1283 a8083063 Iustin Pop
    for child in disk.children:
1284 1063abd1 Iustin Pop
      try:
1285 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1286 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1287 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1288 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1289 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1290 a8083063 Iustin Pop
        # be assembled
1291 1063abd1 Iustin Pop
        try:
1292 fe267188 Iustin Pop
          # pylint: disable-msg=E1103
1293 1063abd1 Iustin Pop
          crdev.Open()
1294 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1295 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1296 a8083063 Iustin Pop
      clist.append(crdev)
1297 a8083063 Iustin Pop
1298 dab69e97 Iustin Pop
  try:
1299 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1300 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1301 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1302 6c626518 Iustin Pop
1303 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1304 1063abd1 Iustin Pop
    try:
1305 1063abd1 Iustin Pop
      device.Assemble()
1306 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1307 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1308 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1309 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1310 1063abd1 Iustin Pop
      try:
1311 1063abd1 Iustin Pop
        device.Open(force=True)
1312 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1313 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1314 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1315 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1316 a0c3fea1 Michael Hanselmann
1317 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1318 a0c3fea1 Michael Hanselmann
1319 c26a6bd2 Iustin Pop
  return device.unique_id
1320 a8083063 Iustin Pop
1321 a8083063 Iustin Pop
1322 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1323 69dd363f René Nussbaumer
  """This function actually wipes the device.
1324 69dd363f René Nussbaumer

1325 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1326 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1327 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1328 69dd363f René Nussbaumer

1329 69dd363f René Nussbaumer
  """
1330 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1331 da63bb4e René Nussbaumer
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1332 da63bb4e René Nussbaumer
         "count=%d" % size]
1333 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1334 69dd363f René Nussbaumer
1335 69dd363f René Nussbaumer
  if result.failed:
1336 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1337 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1338 69dd363f René Nussbaumer
1339 69dd363f René Nussbaumer
1340 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1341 69dd363f René Nussbaumer
  """Wipes a block device.
1342 69dd363f René Nussbaumer

1343 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1344 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1345 da63bb4e René Nussbaumer
  @type offset: int
1346 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1347 da63bb4e René Nussbaumer
  @type size: int
1348 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1349 69dd363f René Nussbaumer

1350 69dd363f René Nussbaumer
  """
1351 69dd363f René Nussbaumer
  try:
1352 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1353 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1354 da63bb4e René Nussbaumer
    rdev = None
1355 da63bb4e René Nussbaumer
1356 da63bb4e René Nussbaumer
  if not rdev:
1357 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1358 da63bb4e René Nussbaumer
1359 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1360 da63bb4e René Nussbaumer
  if offset > rdev.size:
1361 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1362 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1363 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1364 69dd363f René Nussbaumer
1365 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1366 69dd363f René Nussbaumer
1367 69dd363f René Nussbaumer
1368 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1369 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1370 5119c79e René Nussbaumer

1371 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1372 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1373 5119c79e René Nussbaumer
  @type pause: bool
1374 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1375 5119c79e René Nussbaumer

1376 5119c79e René Nussbaumer
  """
1377 5119c79e René Nussbaumer
  success = []
1378 5119c79e René Nussbaumer
  for disk in disks:
1379 5119c79e René Nussbaumer
    try:
1380 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1381 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1382 5119c79e René Nussbaumer
      rdev = None
1383 5119c79e René Nussbaumer
1384 5119c79e René Nussbaumer
    if not rdev:
1385 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1386 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1387 5119c79e René Nussbaumer
      continue
1388 5119c79e René Nussbaumer
1389 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1390 5119c79e René Nussbaumer
1391 5119c79e René Nussbaumer
    if result:
1392 5119c79e René Nussbaumer
      success.append((result, None))
1393 5119c79e René Nussbaumer
    else:
1394 5119c79e René Nussbaumer
      if pause:
1395 5119c79e René Nussbaumer
        msg = "Pause"
1396 5119c79e René Nussbaumer
      else:
1397 5119c79e René Nussbaumer
        msg = "Resume"
1398 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1399 5119c79e René Nussbaumer
1400 5119c79e René Nussbaumer
  return success
1401 5119c79e René Nussbaumer
1402 5119c79e René Nussbaumer
1403 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1404 a8083063 Iustin Pop
  """Remove a block device.
1405 a8083063 Iustin Pop

1406 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1407 10c2650b Iustin Pop

1408 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1409 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1410 10c2650b Iustin Pop
  @rtype: boolean
1411 10c2650b Iustin Pop
  @return: the success of the operation
1412 a8083063 Iustin Pop

1413 a8083063 Iustin Pop
  """
1414 e1bc0878 Iustin Pop
  msgs = []
1415 a8083063 Iustin Pop
  try:
1416 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1417 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1418 a8083063 Iustin Pop
    # probably can't attach
1419 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1420 a8083063 Iustin Pop
    rdev = None
1421 a8083063 Iustin Pop
  if rdev is not None:
1422 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1423 e1bc0878 Iustin Pop
    try:
1424 0c6c04ec Iustin Pop
      rdev.Remove()
1425 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1426 e1bc0878 Iustin Pop
      msgs.append(str(err))
1427 c26a6bd2 Iustin Pop
    if not msgs:
1428 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1429 e1bc0878 Iustin Pop
1430 a8083063 Iustin Pop
  if disk.children:
1431 a8083063 Iustin Pop
    for child in disk.children:
1432 c26a6bd2 Iustin Pop
      try:
1433 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1434 c26a6bd2 Iustin Pop
      except RPCFail, err:
1435 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1436 e1bc0878 Iustin Pop
1437 c26a6bd2 Iustin Pop
  if msgs:
1438 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1439 afdc3985 Iustin Pop
1440 a8083063 Iustin Pop
1441 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1442 a8083063 Iustin Pop
  """Activate a block device for an instance.
1443 a8083063 Iustin Pop

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

1446 10c2650b Iustin Pop
  @note: this function is called recursively.
1447 a8083063 Iustin Pop

1448 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1449 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1450 10c2650b Iustin Pop
  @type owner: str
1451 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1452 10c2650b Iustin Pop
  @type as_primary: boolean
1453 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1454 10c2650b Iustin Pop
      read/write
1455 a8083063 Iustin Pop

1456 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1457 10c2650b Iustin Pop
      was assembled)
1458 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1459 10c2650b Iustin Pop
      during the activation of the children or the device
1460 10c2650b Iustin Pop
      itself
1461 a8083063 Iustin Pop

1462 a8083063 Iustin Pop
  """
1463 a8083063 Iustin Pop
  children = []
1464 a8083063 Iustin Pop
  if disk.children:
1465 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1466 fc1dc9d7 Iustin Pop
    if mcn == -1:
1467 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1468 fc1dc9d7 Iustin Pop
    else:
1469 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1470 a8083063 Iustin Pop
    for chld_disk in disk.children:
1471 fc1dc9d7 Iustin Pop
      try:
1472 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1473 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1474 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1475 fc1dc9d7 Iustin Pop
          raise
1476 fc1dc9d7 Iustin Pop
        cdev = None
1477 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1478 1063abd1 Iustin Pop
                      str(err))
1479 fc1dc9d7 Iustin Pop
      children.append(cdev)
1480 a8083063 Iustin Pop
1481 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1482 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1483 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1484 a8083063 Iustin Pop
    result = r_dev
1485 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1486 a8083063 Iustin Pop
      r_dev.Open()
1487 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1488 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1489 3f78eef2 Iustin Pop
1490 a8083063 Iustin Pop
  else:
1491 a8083063 Iustin Pop
    result = True
1492 a8083063 Iustin Pop
  return result
1493 a8083063 Iustin Pop
1494 a8083063 Iustin Pop
1495 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
1496 a8083063 Iustin Pop
  """Activate a block device for an instance.
1497 a8083063 Iustin Pop

1498 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1499 a8083063 Iustin Pop

1500 b1206984 Iustin Pop
  @rtype: str or boolean
1501 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1502 b1206984 Iustin Pop
      C{True} for secondary nodes
1503 a8083063 Iustin Pop

1504 a8083063 Iustin Pop
  """
1505 53c14ef1 Iustin Pop
  try:
1506 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1507 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1508 fe267188 Iustin Pop
      # pylint: disable-msg=E1103
1509 53c14ef1 Iustin Pop
      result = result.dev_path
1510 c417e115 Iustin Pop
      if as_primary:
1511 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
1512 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1513 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1514 c417e115 Iustin Pop
  except OSError, err:
1515 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
1516 afdc3985 Iustin Pop
1517 c26a6bd2 Iustin Pop
  return result
1518 a8083063 Iustin Pop
1519 a8083063 Iustin Pop
1520 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1521 a8083063 Iustin Pop
  """Shut down a block device.
1522 a8083063 Iustin Pop

1523 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1524 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1525 c41eea6e Iustin Pop
  shutdown.
1526 a8083063 Iustin Pop

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

1531 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1532 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1533 10c2650b Iustin Pop
      shutdown
1534 c26a6bd2 Iustin Pop
  @rtype: None
1535 10c2650b Iustin Pop

1536 a8083063 Iustin Pop
  """
1537 cacfd1fd Iustin Pop
  msgs = []
1538 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1539 a8083063 Iustin Pop
  if r_dev is not None:
1540 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1541 cacfd1fd Iustin Pop
    try:
1542 746f7476 Iustin Pop
      r_dev.Shutdown()
1543 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1544 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1545 cacfd1fd Iustin Pop
      msgs.append(str(err))
1546 746f7476 Iustin Pop
1547 a8083063 Iustin Pop
  if disk.children:
1548 a8083063 Iustin Pop
    for child in disk.children:
1549 c26a6bd2 Iustin Pop
      try:
1550 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1551 c26a6bd2 Iustin Pop
      except RPCFail, err:
1552 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1553 746f7476 Iustin Pop
1554 c26a6bd2 Iustin Pop
  if msgs:
1555 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1556 a8083063 Iustin Pop
1557 a8083063 Iustin Pop
1558 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1559 153d9724 Iustin Pop
  """Extend a mirrored block device.
1560 a8083063 Iustin Pop

1561 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1562 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1563 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1564 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1565 c26a6bd2 Iustin Pop
  @rtype: None
1566 10c2650b Iustin Pop

1567 a8083063 Iustin Pop
  """
1568 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1569 153d9724 Iustin Pop
  if parent_bdev is None:
1570 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1571 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1572 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1573 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1574 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1575 a8083063 Iustin Pop
1576 a8083063 Iustin Pop
1577 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1578 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1579 a8083063 Iustin Pop

1580 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1581 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1582 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1583 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1584 c26a6bd2 Iustin Pop
  @rtype: None
1585 10c2650b Iustin Pop

1586 a8083063 Iustin Pop
  """
1587 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1588 153d9724 Iustin Pop
  if parent_bdev is None:
1589 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1590 e739bd57 Iustin Pop
  devs = []
1591 e739bd57 Iustin Pop
  for disk in new_cdevs:
1592 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1593 e739bd57 Iustin Pop
    if rpath is None:
1594 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1595 e739bd57 Iustin Pop
      if bd is None:
1596 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1597 e739bd57 Iustin Pop
      else:
1598 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1599 e739bd57 Iustin Pop
    else:
1600 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1601 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1602 e739bd57 Iustin Pop
      devs.append(rpath)
1603 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1604 a8083063 Iustin Pop
1605 a8083063 Iustin Pop
1606 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1607 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1608 a8083063 Iustin Pop

1609 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1610 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1611 10c2650b Iustin Pop
  @rtype: disk
1612 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1613 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1614 10c2650b Iustin Pop
      found
1615 a8083063 Iustin Pop

1616 a8083063 Iustin Pop
  """
1617 a8083063 Iustin Pop
  stats = []
1618 a8083063 Iustin Pop
  for dsk in disks:
1619 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1620 a8083063 Iustin Pop
    if rbd is None:
1621 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1622 96acbc09 Michael Hanselmann
1623 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1624 96acbc09 Michael Hanselmann
1625 c26a6bd2 Iustin Pop
  return stats
1626 a8083063 Iustin Pop
1627 a8083063 Iustin Pop
1628 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1629 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1630 c6a9dffa Michael Hanselmann

1631 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1632 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1633 c6a9dffa Michael Hanselmann
  @rtype: disk
1634 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1635 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
1636 c6a9dffa Michael Hanselmann
    otherwise
1637 c6a9dffa Michael Hanselmann

1638 c6a9dffa Michael Hanselmann
  """
1639 c6a9dffa Michael Hanselmann
  result = []
1640 c6a9dffa Michael Hanselmann
  for disk in disks:
1641 c6a9dffa Michael Hanselmann
    try:
1642 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
1643 c6a9dffa Michael Hanselmann
      if rbd is None:
1644 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
1645 c6a9dffa Michael Hanselmann
        continue
1646 c6a9dffa Michael Hanselmann
1647 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
1648 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
1649 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
1650 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
1651 c6a9dffa Michael Hanselmann
    else:
1652 c6a9dffa Michael Hanselmann
      result.append((True, status))
1653 c6a9dffa Michael Hanselmann
1654 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
1655 c6a9dffa Michael Hanselmann
1656 c6a9dffa Michael Hanselmann
  return result
1657 c6a9dffa Michael Hanselmann
1658 c6a9dffa Michael Hanselmann
1659 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1660 a8083063 Iustin Pop
  """Check if a device is activated.
1661 a8083063 Iustin Pop

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

1664 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1665 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1666 a8083063 Iustin Pop

1667 10c2650b Iustin Pop
  @return: None if the device can't be found,
1668 10c2650b Iustin Pop
      otherwise the device instance
1669 a8083063 Iustin Pop

1670 a8083063 Iustin Pop
  """
1671 a8083063 Iustin Pop
  children = []
1672 a8083063 Iustin Pop
  if disk.children:
1673 a8083063 Iustin Pop
    for chdisk in disk.children:
1674 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1675 a8083063 Iustin Pop
1676 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1677 a8083063 Iustin Pop
1678 a8083063 Iustin Pop
1679 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1680 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1681 f2e07bb4 Michael Hanselmann

1682 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1683 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1684 f2e07bb4 Michael Hanselmann

1685 f2e07bb4 Michael Hanselmann
  """
1686 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1687 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1688 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1689 f2e07bb4 Michael Hanselmann
1690 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1691 f2e07bb4 Michael Hanselmann
1692 f2e07bb4 Michael Hanselmann
  return real_disk
1693 f2e07bb4 Michael Hanselmann
1694 f2e07bb4 Michael Hanselmann
1695 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1696 a8083063 Iustin Pop
  """Check if a device is activated.
1697 a8083063 Iustin Pop

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

1700 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1701 10c2650b Iustin Pop
  @param disk: the disk to find
1702 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1703 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1704 96acbc09 Michael Hanselmann
           information
1705 a8083063 Iustin Pop

1706 a8083063 Iustin Pop
  """
1707 23829f6f Iustin Pop
  try:
1708 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1709 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1710 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1711 96acbc09 Michael Hanselmann
1712 a8083063 Iustin Pop
  if rbd is None:
1713 c26a6bd2 Iustin Pop
    return None
1714 96acbc09 Michael Hanselmann
1715 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
1716 a8083063 Iustin Pop
1717 a8083063 Iustin Pop
1718 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1719 968a7623 Iustin Pop
  """Computes the size of the given disks.
1720 968a7623 Iustin Pop

1721 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
1722 968a7623 Iustin Pop

1723 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
1724 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
1725 968a7623 Iustin Pop
  @rtype: list
1726 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
1727 968a7623 Iustin Pop
      otherwise the size
1728 968a7623 Iustin Pop

1729 968a7623 Iustin Pop
  """
1730 968a7623 Iustin Pop
  result = []
1731 968a7623 Iustin Pop
  for cf in disks:
1732 968a7623 Iustin Pop
    try:
1733 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
1734 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
1735 968a7623 Iustin Pop
      result.append(None)
1736 968a7623 Iustin Pop
      continue
1737 968a7623 Iustin Pop
    if rbd is None:
1738 968a7623 Iustin Pop
      result.append(None)
1739 968a7623 Iustin Pop
    else:
1740 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
1741 968a7623 Iustin Pop
  return result
1742 968a7623 Iustin Pop
1743 968a7623 Iustin Pop
1744 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1745 858f3d18 Iustin Pop
  """Export a block device to a remote node.
1746 858f3d18 Iustin Pop

1747 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
1748 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
1749 858f3d18 Iustin Pop
  @type dest_node: str
1750 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
1751 858f3d18 Iustin Pop
  @type dest_path: str
1752 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
1753 858f3d18 Iustin Pop
  @type cluster_name: str
1754 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1755 858f3d18 Iustin Pop
  @rtype: None
1756 858f3d18 Iustin Pop

1757 858f3d18 Iustin Pop
  """
1758 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
1759 858f3d18 Iustin Pop
1760 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
1761 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1762 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
1763 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
1764 858f3d18 Iustin Pop
1765 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
1766 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
1767 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
1768 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
1769 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
1770 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
1771 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
1772 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
1773 858f3d18 Iustin Pop
1774 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1775 858f3d18 Iustin Pop
                                                   constants.GANETI_RUNAS,
1776 858f3d18 Iustin Pop
                                                   destcmd)
1777 858f3d18 Iustin Pop
1778 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1779 858f3d18 Iustin Pop
  command = '|'.join([expcmd, utils.ShellQuoteArgs(remotecmd)])
1780 858f3d18 Iustin Pop
1781 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
1782 858f3d18 Iustin Pop
1783 858f3d18 Iustin Pop
  if result.failed:
1784 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
1785 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1786 858f3d18 Iustin Pop
1787 858f3d18 Iustin Pop
1788 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1789 a8083063 Iustin Pop
  """Write a file to the filesystem.
1790 a8083063 Iustin Pop

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

1794 10c2650b Iustin Pop
  @type file_name: str
1795 10c2650b Iustin Pop
  @param file_name: the target file name
1796 10c2650b Iustin Pop
  @type data: str
1797 10c2650b Iustin Pop
  @param data: the new contents of the file
1798 10c2650b Iustin Pop
  @type mode: int
1799 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1800 10c2650b Iustin Pop
  @type uid: int
1801 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1802 10c2650b Iustin Pop
  @type gid: int
1803 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1804 10c2650b Iustin Pop
  @type atime: float
1805 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1806 10c2650b Iustin Pop
  @type mtime: float
1807 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1808 c26a6bd2 Iustin Pop
  @rtype: None
1809 10c2650b Iustin Pop

1810 a8083063 Iustin Pop
  """
1811 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1812 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1813 a8083063 Iustin Pop
1814 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
1815 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1816 2cc6781a Iustin Pop
          file_name)
1817 a8083063 Iustin Pop
1818 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1819 12bce260 Michael Hanselmann
1820 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
1821 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
1822 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
1823 a8083063 Iustin Pop
1824 386b57af Iustin Pop
1825 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
1826 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
1827 b2f29800 René Nussbaumer

1828 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
1829 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
1830 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
1831 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
1832 b2f29800 René Nussbaumer

1833 b2f29800 René Nussbaumer
  @return: stdout
1834 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
1835 b2f29800 René Nussbaumer

1836 b2f29800 René Nussbaumer
  """
1837 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
1838 b2f29800 René Nussbaumer
1839 b2f29800 René Nussbaumer
  if result.failed:
1840 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
1841 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
1842 b2f29800 René Nussbaumer
1843 b2f29800 René Nussbaumer
  return result.stdout
1844 b2f29800 René Nussbaumer
1845 b2f29800 René Nussbaumer
1846 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1847 89b14f05 Iustin Pop
  """Update all ssconf files.
1848 89b14f05 Iustin Pop

1849 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1850 89b14f05 Iustin Pop

1851 89b14f05 Iustin Pop
  """
1852 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1853 6ddc95ec Michael Hanselmann
1854 6ddc95ec Michael Hanselmann
1855 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1856 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1857 a8083063 Iustin Pop

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

1862 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1863 10c2650b Iustin Pop
  @param err: the exception to format
1864 a8083063 Iustin Pop

1865 a8083063 Iustin Pop
  """
1866 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1867 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1868 a8083063 Iustin Pop
  else:
1869 a8083063 Iustin Pop
    detail = str(err)
1870 a8083063 Iustin Pop
  return detail
1871 a8083063 Iustin Pop
1872 5d0fe286 Iustin Pop
1873 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
1874 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1875 a8083063 Iustin Pop

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

1879 10c2650b Iustin Pop
  @type os_dir: str
1880 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
1881 8e70b181 Iustin Pop
  @rtype: tuple
1882 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
1883 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
1884 a8083063 Iustin Pop

1885 a8083063 Iustin Pop
  """
1886 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1887 a8083063 Iustin Pop
1888 a8083063 Iustin Pop
  try:
1889 a8083063 Iustin Pop
    st = os.stat(api_file)
1890 a8083063 Iustin Pop
  except EnvironmentError, err:
1891 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
1892 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1893 a8083063 Iustin Pop
1894 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1895 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
1896 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
1897 a8083063 Iustin Pop
1898 a8083063 Iustin Pop
  try:
1899 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
1900 a8083063 Iustin Pop
  except EnvironmentError, err:
1901 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
1902 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
1903 a8083063 Iustin Pop
1904 a8083063 Iustin Pop
  try:
1905 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
1906 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1907 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
1908 255dcebd Iustin Pop
                   str(err))
1909 a8083063 Iustin Pop
1910 255dcebd Iustin Pop
  return True, api_versions
1911 a8083063 Iustin Pop
1912 386b57af Iustin Pop
1913 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1914 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1915 a8083063 Iustin Pop

1916 10c2650b Iustin Pop
  @type top_dirs: list
1917 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1918 10c2650b Iustin Pop
      search (if not given defaults to
1919 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1920 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1921 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
1922 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
1923 bad78e66 Iustin Pop
      search paths, where:
1924 255dcebd Iustin Pop
          - name is the (potential) OS name
1925 255dcebd Iustin Pop
          - path is the full path to the OS
1926 255dcebd Iustin Pop
          - status True/False is the validity of the OS
1927 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
1928 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
1929 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
1930 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
1931 a8083063 Iustin Pop

1932 a8083063 Iustin Pop
  """
1933 7c3d51d4 Guido Trotter
  if top_dirs is None:
1934 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1935 a8083063 Iustin Pop
1936 a8083063 Iustin Pop
  result = []
1937 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1938 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1939 7c3d51d4 Guido Trotter
      try:
1940 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1941 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1942 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1943 7c3d51d4 Guido Trotter
        break
1944 7c3d51d4 Guido Trotter
      for name in f_names:
1945 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
1946 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1947 255dcebd Iustin Pop
        if status:
1948 255dcebd Iustin Pop
          diagnose = ""
1949 ba00557a Guido Trotter
          variants = os_inst.supported_variants
1950 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
1951 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
1952 255dcebd Iustin Pop
        else:
1953 255dcebd Iustin Pop
          diagnose = os_inst
1954 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
1955 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
1956 bad78e66 Iustin Pop
                       parameters, api_versions))
1957 a8083063 Iustin Pop
1958 c26a6bd2 Iustin Pop
  return result
1959 a8083063 Iustin Pop
1960 a8083063 Iustin Pop
1961 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
1962 a8083063 Iustin Pop
  """Create an OS instance from disk.
1963 a8083063 Iustin Pop

1964 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1965 8e70b181 Iustin Pop
  valid OS name.
1966 a8083063 Iustin Pop

1967 8ee4dc80 Guido Trotter
  @type base_dir: string
1968 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1969 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1970 255dcebd Iustin Pop
  @rtype: tuple
1971 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
1972 255dcebd Iustin Pop
      or error message
1973 7c3d51d4 Guido Trotter

1974 a8083063 Iustin Pop
  """
1975 56bcd3f4 Guido Trotter
  if base_dir is None:
1976 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1977 c34c0cfd Iustin Pop
  else:
1978 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1979 f95c81bf Iustin Pop
1980 f95c81bf Iustin Pop
  if os_dir is None:
1981 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
1982 a8083063 Iustin Pop
1983 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
1984 255dcebd Iustin Pop
  if not status:
1985 255dcebd Iustin Pop
    # push the error up
1986 255dcebd Iustin Pop
    return status, api_versions
1987 a8083063 Iustin Pop
1988 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1989 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1990 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1991 a8083063 Iustin Pop
1992 41ba4061 Guido Trotter
  # OS Files dictionary, we will populate it with the absolute path names
1993 41ba4061 Guido Trotter
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1994 a8083063 Iustin Pop
1995 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
1996 95075fba Guido Trotter
    os_files[constants.OS_VARIANTS_FILE] = ''
1997 95075fba Guido Trotter
1998 c7d04a6b Iustin Pop
  if max(api_versions) >= constants.OS_API_V20:
1999 c7d04a6b Iustin Pop
    os_files[constants.OS_PARAMETERS_FILE] = ''
2000 c7d04a6b Iustin Pop
  else:
2001 c7d04a6b Iustin Pop
    del os_files[constants.OS_SCRIPT_VERIFY]
2002 c7d04a6b Iustin Pop
2003 ea79fc15 Michael Hanselmann
  for filename in os_files:
2004 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
2005 a8083063 Iustin Pop
2006 a8083063 Iustin Pop
    try:
2007 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
2008 a8083063 Iustin Pop
    except EnvironmentError, err:
2009 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
2010 ea79fc15 Michael Hanselmann
                     (filename, os_dir, _ErrnoOrStr(err)))
2011 a8083063 Iustin Pop
2012 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2013 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
2014 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
2015 255dcebd Iustin Pop
2016 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
2017 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2018 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
2019 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
2020 0757c107 Guido Trotter
2021 845da3e8 Iustin Pop
  variants = []
2022 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
2023 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2024 95075fba Guido Trotter
    try:
2025 95075fba Guido Trotter
      variants = utils.ReadFile(variants_file).splitlines()
2026 95075fba Guido Trotter
    except EnvironmentError, err:
2027 95075fba Guido Trotter
      return False, ("Error while reading the OS variants file at %s: %s" %
2028 95075fba Guido Trotter
                     (variants_file, _ErrnoOrStr(err)))
2029 95075fba Guido Trotter
    if not variants:
2030 95075fba Guido Trotter
      return False, ("No supported os variant found")
2031 0757c107 Guido Trotter
2032 c7d04a6b Iustin Pop
  parameters = []
2033 c7d04a6b Iustin Pop
  if constants.OS_PARAMETERS_FILE in os_files:
2034 c7d04a6b Iustin Pop
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2035 c7d04a6b Iustin Pop
    try:
2036 c7d04a6b Iustin Pop
      parameters = utils.ReadFile(parameters_file).splitlines()
2037 c7d04a6b Iustin Pop
    except EnvironmentError, err:
2038 c7d04a6b Iustin Pop
      return False, ("Error while reading the OS parameters file at %s: %s" %
2039 c7d04a6b Iustin Pop
                     (parameters_file, _ErrnoOrStr(err)))
2040 c7d04a6b Iustin Pop
    parameters = [v.split(None, 1) for v in parameters]
2041 c7d04a6b Iustin Pop
2042 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
2043 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2044 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2045 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2046 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2047 40684c3a Iustin Pop
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2048 40684c3a Iustin Pop
                                                 None),
2049 95075fba Guido Trotter
                      supported_variants=variants,
2050 c7d04a6b Iustin Pop
                      supported_parameters=parameters,
2051 255dcebd Iustin Pop
                      api_versions=api_versions)
2052 255dcebd Iustin Pop
  return True, os_obj
2053 255dcebd Iustin Pop
2054 255dcebd Iustin Pop
2055 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
2056 255dcebd Iustin Pop
  """Create an OS instance from disk.
2057 255dcebd Iustin Pop

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

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

2065 255dcebd Iustin Pop
  @type base_dir: string
2066 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2067 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2068 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2069 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2070 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2071 255dcebd Iustin Pop

2072 255dcebd Iustin Pop
  """
2073 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2074 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2075 255dcebd Iustin Pop
2076 255dcebd Iustin Pop
  if not status:
2077 255dcebd Iustin Pop
    _Fail(payload)
2078 a8083063 Iustin Pop
2079 255dcebd Iustin Pop
  return payload
2080 a8083063 Iustin Pop
2081 a8083063 Iustin Pop
2082 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2083 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2084 2266edb2 Guido Trotter

2085 a025e535 Vitaly Kuznetsov
  @type os_name: str
2086 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2087 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2088 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2089 1bdcbbab Iustin Pop
  @type os_params: dict
2090 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2091 2266edb2 Guido Trotter
  @type debug: integer
2092 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2093 2266edb2 Guido Trotter
  @rtype: dict
2094 2266edb2 Guido Trotter
  @return: dict of environment variables
2095 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2096 10c2650b Iustin Pop
      cannot be found
2097 2266edb2 Guido Trotter

2098 2266edb2 Guido Trotter
  """
2099 2266edb2 Guido Trotter
  result = {}
2100 099c52ad Iustin Pop
  api_version = \
2101 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2102 d1a7d66f Guido Trotter
  result['OS_API_VERSION'] = '%d' % api_version
2103 efaa9b06 Iustin Pop
  result['OS_NAME'] = inst_os.name
2104 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
2105 efaa9b06 Iustin Pop
2106 efaa9b06 Iustin Pop
  # OS variants
2107 f11280b5 Guido Trotter
  if api_version >= constants.OS_API_V15:
2108 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2109 870dc44c Iustin Pop
    if not variant:
2110 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2111 f11280b5 Guido Trotter
    result['OS_VARIANT'] = variant
2112 efaa9b06 Iustin Pop
2113 1bdcbbab Iustin Pop
  # OS params
2114 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2115 1bdcbbab Iustin Pop
    result['OSP_%s' % pname.upper()] = pvalue
2116 1bdcbbab Iustin Pop
2117 efaa9b06 Iustin Pop
  return result
2118 efaa9b06 Iustin Pop
2119 efaa9b06 Iustin Pop
2120 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2121 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2122 efaa9b06 Iustin Pop

2123 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2124 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2125 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2126 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2127 efaa9b06 Iustin Pop
  @type debug: integer
2128 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2129 efaa9b06 Iustin Pop
  @rtype: dict
2130 efaa9b06 Iustin Pop
  @return: dict of environment variables
2131 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2132 efaa9b06 Iustin Pop
      cannot be found
2133 efaa9b06 Iustin Pop

2134 efaa9b06 Iustin Pop
  """
2135 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2136 efaa9b06 Iustin Pop
2137 f2165b8a Iustin Pop
  for attr in ["name", "os", "uuid", "ctime", "mtime"]:
2138 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2139 f2165b8a Iustin Pop
2140 efaa9b06 Iustin Pop
  result['HYPERVISOR'] = instance.hypervisor
2141 efaa9b06 Iustin Pop
  result['DISK_COUNT'] = '%d' % len(instance.disks)
2142 efaa9b06 Iustin Pop
  result['NIC_COUNT'] = '%d' % len(instance.nics)
2143 efaa9b06 Iustin Pop
2144 efaa9b06 Iustin Pop
  # Disks
2145 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2146 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2147 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
2148 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
2149 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2150 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
2151 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2152 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2153 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
2154 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2155 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
2156 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
2157 efaa9b06 Iustin Pop
2158 efaa9b06 Iustin Pop
  # NICs
2159 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2160 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
2161 2266edb2 Guido Trotter
    if nic.ip:
2162 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
2163 1ba9227f Guido Trotter
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
2164 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2165 1ba9227f Guido Trotter
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
2166 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2167 1ba9227f Guido Trotter
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
2168 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2169 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
2170 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2171 2266edb2 Guido Trotter
2172 efaa9b06 Iustin Pop
  # HV/BE params
2173 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2174 67fc3042 Iustin Pop
    for key, value in source.items():
2175 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2176 67fc3042 Iustin Pop
2177 2266edb2 Guido Trotter
  return result
2178 a8083063 Iustin Pop
2179 f2e07bb4 Michael Hanselmann
2180 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
2181 594609c0 Iustin Pop
  """Grow a stack of block devices.
2182 594609c0 Iustin Pop

2183 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2184 10c2650b Iustin Pop
  first ones to resize.
2185 594609c0 Iustin Pop

2186 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2187 10c2650b Iustin Pop
  @param disk: the disk to be grown
2188 10c2650b Iustin Pop
  @rtype: (status, result)
2189 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
2190 10c2650b Iustin Pop
      (True/False), and the errors message if status
2191 10c2650b Iustin Pop
      is False
2192 594609c0 Iustin Pop

2193 594609c0 Iustin Pop
  """
2194 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2195 594609c0 Iustin Pop
  if r_dev is None:
2196 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2197 594609c0 Iustin Pop
2198 594609c0 Iustin Pop
  try:
2199 594609c0 Iustin Pop
    r_dev.Grow(amount)
2200 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2201 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2202 594609c0 Iustin Pop
2203 594609c0 Iustin Pop
2204 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2205 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2206 a8083063 Iustin Pop

2207 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2208 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2209 a8083063 Iustin Pop

2210 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2211 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2212 e9e9263d Guido Trotter
  @rtype: string
2213 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2214 a8083063 Iustin Pop

2215 098c0958 Michael Hanselmann
  """
2216 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2217 433c63aa Iustin Pop
    if not disk.children:
2218 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2219 433c63aa Iustin Pop
            disk.unique_id)
2220 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2221 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2222 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2223 a8083063 Iustin Pop
    if r_dev is not None:
2224 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2225 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2226 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2227 a8083063 Iustin Pop
    else:
2228 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2229 a8083063 Iustin Pop
  else:
2230 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2231 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2232 a8083063 Iustin Pop
2233 a8083063 Iustin Pop
2234 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2235 a8083063 Iustin Pop
  """Write out the export configuration information.
2236 a8083063 Iustin Pop

2237 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2238 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2239 10c2650b Iustin Pop
      saving configuration
2240 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2241 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2242 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2243 a8083063 Iustin Pop

2244 c26a6bd2 Iustin Pop
  @rtype: None
2245 a8083063 Iustin Pop

2246 098c0958 Michael Hanselmann
  """
2247 c4feafe8 Iustin Pop
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2248 c4feafe8 Iustin Pop
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2249 a8083063 Iustin Pop
2250 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2251 a8083063 Iustin Pop
2252 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2253 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
2254 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2255 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2256 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
2257 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2258 a8083063 Iustin Pop
2259 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2260 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
2261 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
2262 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
2263 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
2264 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2265 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2266 3c8954ad Iustin Pop
  config.set(constants.INISECT_INS, 'hypervisor', instance.hypervisor)
2267 66f93869 Manuel Franceschini
2268 95268cc3 Iustin Pop
  nic_total = 0
2269 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2270 95268cc3 Iustin Pop
    nic_total += 1
2271 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2272 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
2273 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2274 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2275 6801eb5c Iustin Pop
      config.set(constants.INISECT_INS, 'nic%d_%s' % (nic_count, param),
2276 6801eb5c Iustin Pop
                 '%s' % nic.nicparams.get(param, None))
2277 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2278 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2279 a8083063 Iustin Pop
2280 726d7d68 Iustin Pop
  disk_total = 0
2281 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2282 19d7f90a Guido Trotter
    if disk:
2283 726d7d68 Iustin Pop
      disk_total += 1
2284 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2285 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
2286 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2287 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
2288 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2289 19d7f90a Guido Trotter
                 ('%d' % disk.size))
2290 a8083063 Iustin Pop
2291 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2292 a8083063 Iustin Pop
2293 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2294 3c8954ad Iustin Pop
2295 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2296 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2297 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2298 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2299 3c8954ad Iustin Pop
2300 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2301 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2302 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2303 3c8954ad Iustin Pop
2304 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2305 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2306 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2307 535b49cb Iustin Pop
2308 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2309 726d7d68 Iustin Pop
                  data=config.Dumps())
2310 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2311 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2312 a8083063 Iustin Pop
2313 a8083063 Iustin Pop
2314 a8083063 Iustin Pop
def ExportInfo(dest):
2315 a8083063 Iustin Pop
  """Get export configuration information.
2316 a8083063 Iustin Pop

2317 10c2650b Iustin Pop
  @type dest: str
2318 10c2650b Iustin Pop
  @param dest: directory containing the export
2319 a8083063 Iustin Pop

2320 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2321 10c2650b Iustin Pop
  @return: a serializable config file containing the
2322 10c2650b Iustin Pop
      export info
2323 a8083063 Iustin Pop

2324 a8083063 Iustin Pop
  """
2325 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2326 a8083063 Iustin Pop
2327 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2328 a8083063 Iustin Pop
  config.read(cff)
2329 a8083063 Iustin Pop
2330 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2331 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2332 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2333 a8083063 Iustin Pop
2334 c26a6bd2 Iustin Pop
  return config.Dumps()
2335 a8083063 Iustin Pop
2336 a8083063 Iustin Pop
2337 a8083063 Iustin Pop
def ListExports():
2338 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2339 098c0958 Michael Hanselmann

2340 10c2650b Iustin Pop
  @rtype: list
2341 10c2650b Iustin Pop
  @return: list of the exports
2342 10c2650b Iustin Pop

2343 a8083063 Iustin Pop
  """
2344 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
2345 b5b8309d Guido Trotter
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2346 a8083063 Iustin Pop
  else:
2347 afdc3985 Iustin Pop
    _Fail("No exports directory")
2348 a8083063 Iustin Pop
2349 a8083063 Iustin Pop
2350 a8083063 Iustin Pop
def RemoveExport(export):
2351 a8083063 Iustin Pop
  """Remove an existing export from the node.
2352 a8083063 Iustin Pop

2353 10c2650b Iustin Pop
  @type export: str
2354 10c2650b Iustin Pop
  @param export: the name of the export to remove
2355 c26a6bd2 Iustin Pop
  @rtype: None
2356 a8083063 Iustin Pop

2357 098c0958 Michael Hanselmann
  """
2358 c4feafe8 Iustin Pop
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2359 a8083063 Iustin Pop
2360 35fbcd11 Iustin Pop
  try:
2361 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2362 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2363 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2364 a8083063 Iustin Pop
2365 a8083063 Iustin Pop
2366 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2367 f3e513ad Iustin Pop
  """Rename a list of block devices.
2368 f3e513ad Iustin Pop

2369 10c2650b Iustin Pop
  @type devlist: list of tuples
2370 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2371 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2372 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2373 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2374 10c2650b Iustin Pop
      rename it to
2375 10c2650b Iustin Pop
  @rtype: boolean
2376 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2377 f3e513ad Iustin Pop

2378 f3e513ad Iustin Pop
  """
2379 6b5e3f70 Iustin Pop
  msgs = []
2380 f3e513ad Iustin Pop
  result = True
2381 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2382 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2383 f3e513ad Iustin Pop
    if dev is None:
2384 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2385 f3e513ad Iustin Pop
      result = False
2386 f3e513ad Iustin Pop
      continue
2387 f3e513ad Iustin Pop
    try:
2388 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2389 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2390 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2391 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2392 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2393 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2394 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2395 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2396 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2397 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2398 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2399 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2400 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2401 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2402 f3e513ad Iustin Pop
      result = False
2403 afdc3985 Iustin Pop
  if not result:
2404 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2405 f3e513ad Iustin Pop
2406 f3e513ad Iustin Pop
2407 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2408 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2409 778b75bb Manuel Franceschini

2410 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2411 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2412 778b75bb Manuel Franceschini
  directory are allowed.
2413 778b75bb Manuel Franceschini

2414 b1206984 Iustin Pop
  @type file_storage_dir: str
2415 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2416 d61cbe76 Iustin Pop

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

2419 778b75bb Manuel Franceschini
  """
2420 cb7c0198 Iustin Pop
  if not constants.ENABLE_FILE_STORAGE:
2421 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2422 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2423 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2424 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2425 56569f4e Michael Hanselmann
  if (os.path.commonprefix([file_storage_dir, base_file_storage_dir]) !=
2426 778b75bb Manuel Franceschini
      base_file_storage_dir):
2427 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2428 b2b8bcce Iustin Pop
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2429 778b75bb Manuel Franceschini
  return file_storage_dir
2430 778b75bb Manuel Franceschini
2431 778b75bb Manuel Franceschini
2432 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2433 778b75bb Manuel Franceschini
  """Create file storage directory.
2434 778b75bb Manuel Franceschini

2435 b1206984 Iustin Pop
  @type file_storage_dir: str
2436 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2437 778b75bb Manuel Franceschini

2438 b1206984 Iustin Pop
  @rtype: tuple
2439 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2440 b1206984 Iustin Pop
      creation was successful or not
2441 778b75bb Manuel Franceschini

2442 778b75bb Manuel Franceschini
  """
2443 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2444 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2445 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2446 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2447 b2b8bcce Iustin Pop
            file_storage_dir)
2448 778b75bb Manuel Franceschini
  else:
2449 b2b8bcce Iustin Pop
    try:
2450 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2451 b2b8bcce Iustin Pop
    except OSError, err:
2452 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2453 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2454 778b75bb Manuel Franceschini
2455 778b75bb Manuel Franceschini
2456 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2457 778b75bb Manuel Franceschini
  """Remove file storage directory.
2458 778b75bb Manuel Franceschini

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

2461 10c2650b Iustin Pop
  @type file_storage_dir: str
2462 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2463 10c2650b Iustin Pop
  @rtype: tuple (success,)
2464 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2465 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2466 778b75bb Manuel Franceschini

2467 778b75bb Manuel Franceschini
  """
2468 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2469 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2470 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2471 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2472 b2b8bcce Iustin Pop
            file_storage_dir)
2473 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2474 b2b8bcce Iustin Pop
    try:
2475 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2476 b2b8bcce Iustin Pop
    except OSError, err:
2477 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2478 b2b8bcce Iustin Pop
            file_storage_dir, err)
2479 b2b8bcce Iustin Pop
2480 778b75bb Manuel Franceschini
2481 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2482 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2483 778b75bb Manuel Franceschini

2484 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2485 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2486 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2487 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2488 10c2650b Iustin Pop
  @rtype: tuple (success,)
2489 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2490 10c2650b Iustin Pop
      whether the operation was successful
2491 778b75bb Manuel Franceschini

2492 778b75bb Manuel Franceschini
  """
2493 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2494 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2495 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2496 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2497 b2b8bcce Iustin Pop
      try:
2498 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2499 b2b8bcce Iustin Pop
      except OSError, err:
2500 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2501 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2502 778b75bb Manuel Franceschini
    else:
2503 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2504 b2b8bcce Iustin Pop
            old_file_storage_dir)
2505 b2b8bcce Iustin Pop
  else:
2506 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2507 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2508 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2509 778b75bb Manuel Franceschini
2510 778b75bb Manuel Franceschini
2511 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2512 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2513 ca52cdeb Michael Hanselmann

2514 10c2650b Iustin Pop
  @type file_name: str
2515 10c2650b Iustin Pop
  @param file_name: the file name we should check
2516 c8457ce7 Iustin Pop
  @rtype: None
2517 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2518 10c2650b Iustin Pop

2519 ca52cdeb Michael Hanselmann
  """
2520 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2521 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2522 dc31eae3 Michael Hanselmann
2523 dc31eae3 Michael Hanselmann
  if not result:
2524 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2525 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2526 dc31eae3 Michael Hanselmann
2527 dc31eae3 Michael Hanselmann
2528 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2529 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2530 dc31eae3 Michael Hanselmann

2531 3865ca48 Michael Hanselmann
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2532 10c2650b Iustin Pop
  checking.
2533 10c2650b Iustin Pop

2534 10c2650b Iustin Pop
  @type file_name: str
2535 10c2650b Iustin Pop
  @param file_name: the job file name
2536 10c2650b Iustin Pop
  @type content: str
2537 10c2650b Iustin Pop
  @param content: the new job contents
2538 10c2650b Iustin Pop
  @rtype: boolean
2539 10c2650b Iustin Pop
  @return: the success of the operation
2540 10c2650b Iustin Pop

2541 dc31eae3 Michael Hanselmann
  """
2542 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2543 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2544 ca52cdeb Michael Hanselmann
2545 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2546 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2547 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2548 ca52cdeb Michael Hanselmann
2549 ca52cdeb Michael Hanselmann
2550 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2551 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2552 af5ebcb1 Michael Hanselmann

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

2555 10c2650b Iustin Pop
  @type old: str
2556 10c2650b Iustin Pop
  @param old: the old (actual) file name
2557 10c2650b Iustin Pop
  @type new: str
2558 10c2650b Iustin Pop
  @param new: the desired file name
2559 c8457ce7 Iustin Pop
  @rtype: tuple
2560 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2561 10c2650b Iustin Pop

2562 af5ebcb1 Michael Hanselmann
  """
2563 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2564 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2565 af5ebcb1 Michael Hanselmann
2566 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2567 af5ebcb1 Michael Hanselmann
2568 af5ebcb1 Michael Hanselmann
2569 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2570 d61cbe76 Iustin Pop
  """Closes the given block devices.
2571 d61cbe76 Iustin Pop

2572 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2573 10c2650b Iustin Pop
  DRBD).
2574 10c2650b Iustin Pop

2575 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2576 b2e7666a Iustin Pop
      of this instance will be removed
2577 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2578 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2579 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2580 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2581 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2582 10c2650b Iustin Pop
      which will contain the error details in case we
2583 10c2650b Iustin Pop
      failed
2584 d61cbe76 Iustin Pop

2585 d61cbe76 Iustin Pop
  """
2586 d61cbe76 Iustin Pop
  bdevs = []
2587 d61cbe76 Iustin Pop
  for cf in disks:
2588 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2589 d61cbe76 Iustin Pop
    if rd is None:
2590 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2591 d61cbe76 Iustin Pop
    bdevs.append(rd)
2592 d61cbe76 Iustin Pop
2593 d61cbe76 Iustin Pop
  msg = []
2594 d61cbe76 Iustin Pop
  for rd in bdevs:
2595 d61cbe76 Iustin Pop
    try:
2596 d61cbe76 Iustin Pop
      rd.Close()
2597 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2598 d61cbe76 Iustin Pop
      msg.append(str(err))
2599 d61cbe76 Iustin Pop
  if msg:
2600 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2601 d61cbe76 Iustin Pop
  else:
2602 b2e7666a Iustin Pop
    if instance_name:
2603 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2604 d61cbe76 Iustin Pop
2605 d61cbe76 Iustin Pop
2606 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2607 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2608 6217e295 Iustin Pop

2609 6217e295 Iustin Pop
  @type hvname: string
2610 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2611 6217e295 Iustin Pop
  @type hvparams: dict
2612 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2613 c26a6bd2 Iustin Pop
  @rtype: None
2614 6217e295 Iustin Pop

2615 6217e295 Iustin Pop
  """
2616 6217e295 Iustin Pop
  try:
2617 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2618 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2619 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2620 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2621 6217e295 Iustin Pop
2622 6217e295 Iustin Pop
2623 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
2624 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
2625 acd9ff9e Iustin Pop

2626 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
2627 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
2628 acd9ff9e Iustin Pop
  @type parameters: list
2629 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
2630 acd9ff9e Iustin Pop

2631 acd9ff9e Iustin Pop
  """
2632 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
2633 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
2634 acd9ff9e Iustin Pop
  if delta:
2635 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
2636 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2637 acd9ff9e Iustin Pop
2638 acd9ff9e Iustin Pop
2639 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
2640 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
2641 acd9ff9e Iustin Pop

2642 acd9ff9e Iustin Pop
  @type required: boolean
2643 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
2644 acd9ff9e Iustin Pop
      failure or not
2645 acd9ff9e Iustin Pop
  @type osname: string
2646 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
2647 acd9ff9e Iustin Pop
  @type checks: list
2648 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
2649 acd9ff9e Iustin Pop
  @type osparams: dict
2650 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
2651 acd9ff9e Iustin Pop
  @rtype: boolean
2652 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
2653 acd9ff9e Iustin Pop
      found and L{required} was false
2654 acd9ff9e Iustin Pop

2655 acd9ff9e Iustin Pop
  """
2656 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2657 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
2658 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2659 acd9ff9e Iustin Pop
2660 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
2661 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
2662 acd9ff9e Iustin Pop
2663 acd9ff9e Iustin Pop
  if not status:
2664 acd9ff9e Iustin Pop
    if required:
2665 acd9ff9e Iustin Pop
      _Fail(tbv)
2666 acd9ff9e Iustin Pop
    else:
2667 acd9ff9e Iustin Pop
      return False
2668 acd9ff9e Iustin Pop
2669 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
2670 72db3fd7 Iustin Pop
    return True
2671 72db3fd7 Iustin Pop
2672 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
2673 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
2674 acd9ff9e Iustin Pop
2675 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
2676 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2677 acd9ff9e Iustin Pop
                        cwd=tbv.path)
2678 acd9ff9e Iustin Pop
  if result.failed:
2679 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
2680 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
2681 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
2682 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
2683 acd9ff9e Iustin Pop
2684 acd9ff9e Iustin Pop
  return True
2685 acd9ff9e Iustin Pop
2686 acd9ff9e Iustin Pop
2687 56aa9fd5 Iustin Pop
def DemoteFromMC():
2688 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2689 56aa9fd5 Iustin Pop

2690 56aa9fd5 Iustin Pop
  """
2691 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2692 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2693 56aa9fd5 Iustin Pop
  if master == myself:
2694 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2695 f154a7a3 Michael Hanselmann
2696 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2697 f154a7a3 Michael Hanselmann
  if not result.failed:
2698 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2699 f154a7a3 Michael Hanselmann
2700 56aa9fd5 Iustin Pop
  try:
2701 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2702 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2703 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2704 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2705 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2706 f154a7a3 Michael Hanselmann
2707 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2708 56aa9fd5 Iustin Pop
2709 56aa9fd5 Iustin Pop
2710 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
2711 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
2712 f942a838 Michael Hanselmann

2713 f942a838 Michael Hanselmann
  """
2714 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
2715 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2716 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2717 f942a838 Michael Hanselmann
2718 f942a838 Michael Hanselmann
2719 f942a838 Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2720 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
2721 f942a838 Michael Hanselmann

2722 f942a838 Michael Hanselmann
  @type validity: int
2723 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
2724 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
2725 f942a838 Michael Hanselmann
  @return: Certificate name and public part
2726 f942a838 Michael Hanselmann

2727 f942a838 Michael Hanselmann
  """
2728 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
2729 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2730 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2731 f942a838 Michael Hanselmann
2732 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2733 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
2734 f942a838 Michael Hanselmann
  try:
2735 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
2736 f942a838 Michael Hanselmann
    assert len(name) > 5
2737 f942a838 Michael Hanselmann
2738 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2739 f942a838 Michael Hanselmann
2740 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2741 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2742 f942a838 Michael Hanselmann
2743 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
2744 f942a838 Michael Hanselmann
    return (name, cert_pem)
2745 f942a838 Michael Hanselmann
  except Exception:
2746 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
2747 f942a838 Michael Hanselmann
    raise
2748 f942a838 Michael Hanselmann
2749 f942a838 Michael Hanselmann
2750 f942a838 Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2751 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
2752 f942a838 Michael Hanselmann

2753 f942a838 Michael Hanselmann
  @type name: string
2754 f942a838 Michael Hanselmann
  @param name: Certificate name
2755 f942a838 Michael Hanselmann

2756 f942a838 Michael Hanselmann
  """
2757 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2758 f942a838 Michael Hanselmann
2759 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
2760 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
2761 f942a838 Michael Hanselmann
2762 f942a838 Michael Hanselmann
  try:
2763 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
2764 f942a838 Michael Hanselmann
  except EnvironmentError, err:
2765 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
2766 f942a838 Michael Hanselmann
          cert_dir, err)
2767 f942a838 Michael Hanselmann
2768 f942a838 Michael Hanselmann
2769 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2770 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
2771 1651d116 Michael Hanselmann

2772 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
2773 1651d116 Michael Hanselmann
  @param instance: The instance object
2774 1651d116 Michael Hanselmann
  @param mode: Import/export mode
2775 1651d116 Michael Hanselmann
  @param ieio: Input/output type
2776 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
2777 1651d116 Michael Hanselmann

2778 1651d116 Michael Hanselmann
  """
2779 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2780 1651d116 Michael Hanselmann
2781 1651d116 Michael Hanselmann
  env = None
2782 1651d116 Michael Hanselmann
  prefix = None
2783 1651d116 Michael Hanselmann
  suffix = None
2784 2ad5550d Michael Hanselmann
  exp_size = None
2785 1651d116 Michael Hanselmann
2786 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
2787 1651d116 Michael Hanselmann
    (filename, ) = ieargs
2788 1651d116 Michael Hanselmann
2789 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
2790 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
2791 1651d116 Michael Hanselmann
2792 1651d116 Michael Hanselmann
    directory = os.path.normpath(os.path.dirname(filename))
2793 1651d116 Michael Hanselmann
2794 1651d116 Michael Hanselmann
    if (os.path.commonprefix([constants.EXPORT_DIR, directory]) !=
2795 1651d116 Michael Hanselmann
        constants.EXPORT_DIR):
2796 1651d116 Michael Hanselmann
      _Fail("File '%s' is not under exports directory '%s'",
2797 1651d116 Michael Hanselmann
            filename, constants.EXPORT_DIR)
2798 1651d116 Michael Hanselmann
2799 1651d116 Michael Hanselmann
    # Create directory
2800 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
2801 1651d116 Michael Hanselmann
2802 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
2803 1651d116 Michael Hanselmann
2804 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2805 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
2806 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2807 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
2808 1651d116 Michael Hanselmann
2809 2ad5550d Michael Hanselmann
      # Retrieve file size
2810 2ad5550d Michael Hanselmann
      try:
2811 2ad5550d Michael Hanselmann
        st = os.stat(filename)
2812 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
2813 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
2814 2ad5550d Michael Hanselmann
      else:
2815 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
2816 2ad5550d Michael Hanselmann
2817 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
2818 1651d116 Michael Hanselmann
    (disk, ) = ieargs
2819 1651d116 Michael Hanselmann
2820 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2821 1651d116 Michael Hanselmann
2822 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2823 1651d116 Michael Hanselmann
      # we set here a smaller block size as, due to transport buffering, more
2824 1651d116 Michael Hanselmann
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
2825 1651d116 Michael Hanselmann
      # is not already there or we pass a wrong path; we use notrunc to no
2826 1651d116 Michael Hanselmann
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
2827 1651d116 Michael Hanselmann
      # much memory; this means that at best, we flush every 64k, which will
2828 1651d116 Michael Hanselmann
      # not be very fast
2829 1651d116 Michael Hanselmann
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
2830 1651d116 Michael Hanselmann
                                    " bs=%s oflag=dsync"),
2831 1651d116 Michael Hanselmann
                                    real_disk.dev_path,
2832 1651d116 Michael Hanselmann
                                    str(64 * 1024))
2833 1651d116 Michael Hanselmann
2834 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2835 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
2836 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2837 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
2838 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
2839 1651d116 Michael Hanselmann
                                   str(disk.size))
2840 2ad5550d Michael Hanselmann
      exp_size = disk.size
2841 1651d116 Michael Hanselmann
2842 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
2843 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
2844 1651d116 Michael Hanselmann
2845 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
2846 1651d116 Michael Hanselmann
2847 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2848 1651d116 Michael Hanselmann
2849 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
2850 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
2851 1651d116 Michael Hanselmann
2852 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2853 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
2854 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
2855 1651d116 Michael Hanselmann
      script = inst_os.import_script
2856 1651d116 Michael Hanselmann
2857 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2858 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
2859 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
2860 1651d116 Michael Hanselmann
      script = inst_os.export_script
2861 1651d116 Michael Hanselmann
2862 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
2863 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
2864 1651d116 Michael Hanselmann
2865 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2866 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
2867 1651d116 Michael Hanselmann
2868 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2869 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
2870 1651d116 Michael Hanselmann
2871 2ad5550d Michael Hanselmann
    # Let script predict size
2872 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
2873 2ad5550d Michael Hanselmann
2874 1651d116 Michael Hanselmann
  else:
2875 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
2876 1651d116 Michael Hanselmann
2877 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
2878 1651d116 Michael Hanselmann
2879 1651d116 Michael Hanselmann
2880 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
2881 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
2882 1651d116 Michael Hanselmann

2883 1651d116 Michael Hanselmann
  """
2884 1651d116 Michael Hanselmann
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
2885 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
2886 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
2887 1651d116 Michael Hanselmann
2888 1651d116 Michael Hanselmann
2889 eb630f50 Michael Hanselmann
def StartImportExportDaemon(mode, opts, host, port, instance, ieio, ieioargs):
2890 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
2891 1651d116 Michael Hanselmann

2892 1651d116 Michael Hanselmann
  @param mode: Import/output mode
2893 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
2894 eb630f50 Michael Hanselmann
  @param opts: Daemon options
2895 1651d116 Michael Hanselmann
  @type host: string
2896 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
2897 1651d116 Michael Hanselmann
  @type port: int
2898 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
2899 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
2900 1651d116 Michael Hanselmann
  @param instance: Instance object
2901 1651d116 Michael Hanselmann
  @param ieio: Input/output type
2902 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
2903 1651d116 Michael Hanselmann

2904 1651d116 Michael Hanselmann
  """
2905 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
2906 1651d116 Michael Hanselmann
    prefix = "import"
2907 1651d116 Michael Hanselmann
2908 1651d116 Michael Hanselmann
    if not (host is None and port is None):
2909 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
2910 1651d116 Michael Hanselmann
2911 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
2912 1651d116 Michael Hanselmann
    prefix = "export"
2913 1651d116 Michael Hanselmann
2914 1651d116 Michael Hanselmann
    if host is None or port is None:
2915 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
2916 1651d116 Michael Hanselmann
2917 1651d116 Michael Hanselmann
  else:
2918 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
2919 1651d116 Michael Hanselmann
2920 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
2921 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
2922 1651d116 Michael Hanselmann
2923 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
2924 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
2925 1651d116 Michael Hanselmann
2926 eb630f50 Michael Hanselmann
  if opts.key_name is None:
2927 1651d116 Michael Hanselmann
    # Use server.pem
2928 1651d116 Michael Hanselmann
    key_path = constants.NODED_CERT_FILE
2929 1651d116 Michael Hanselmann
    cert_path = constants.NODED_CERT_FILE
2930 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
2931 1651d116 Michael Hanselmann
  else:
2932 1651d116 Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
2933 eb630f50 Michael Hanselmann
                                                 opts.key_name)
2934 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
2935 1651d116 Michael Hanselmann
2936 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
2937 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
2938 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
2939 63bcea2a Michael Hanselmann
2940 1651d116 Michael Hanselmann
  status_dir = _CreateImportExportStatusDir(prefix)
2941 1651d116 Michael Hanselmann
  try:
2942 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
2943 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
2944 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
2945 1651d116 Michael Hanselmann
2946 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
2947 1651d116 Michael Hanselmann
      # Use server.pem
2948 63bcea2a Michael Hanselmann
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
2949 eb630f50 Michael Hanselmann
    else:
2950 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
2951 63bcea2a Michael Hanselmann
2952 eb630f50 Michael Hanselmann
    # Write CA file
2953 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
2954 1651d116 Michael Hanselmann
2955 1651d116 Michael Hanselmann
    cmd = [
2956 1651d116 Michael Hanselmann
      constants.IMPORT_EXPORT_DAEMON,
2957 1651d116 Michael Hanselmann
      status_file, mode,
2958 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
2959 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
2960 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
2961 1651d116 Michael Hanselmann
      ]
2962 1651d116 Michael Hanselmann
2963 1651d116 Michael Hanselmann
    if host:
2964 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
2965 1651d116 Michael Hanselmann
2966 1651d116 Michael Hanselmann
    if port:
2967 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
2968 1651d116 Michael Hanselmann
2969 855d2fc7 Michael Hanselmann
    if opts.ipv6:
2970 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
2971 855d2fc7 Michael Hanselmann
    else:
2972 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
2973 855d2fc7 Michael Hanselmann
2974 a5310c2a Michael Hanselmann
    if opts.compress:
2975 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
2976 a5310c2a Michael Hanselmann
2977 af1d39b1 Michael Hanselmann
    if opts.magic:
2978 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
2979 af1d39b1 Michael Hanselmann
2980 2ad5550d Michael Hanselmann
    if exp_size is not None:
2981 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
2982 2ad5550d Michael Hanselmann
2983 1651d116 Michael Hanselmann
    if cmd_prefix:
2984 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
2985 1651d116 Michael Hanselmann
2986 1651d116 Michael Hanselmann
    if cmd_suffix:
2987 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
2988 1651d116 Michael Hanselmann
2989 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
2990 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
2991 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
2992 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
2993 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
2994 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
2995 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
2996 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
2997 4478301b Michael Hanselmann
2998 1651d116 Michael Hanselmann
    logfile = _InstanceLogName(prefix, instance.os, instance.name)
2999 1651d116 Michael Hanselmann
3000 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3001 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
3002 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3003 1651d116 Michael Hanselmann
                      output=logfile)
3004 1651d116 Michael Hanselmann
3005 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
3006 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
3007 1651d116 Michael Hanselmann
3008 1651d116 Michael Hanselmann
  except Exception:
3009 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
3010 1651d116 Michael Hanselmann
    raise
3011 1651d116 Michael Hanselmann
3012 1651d116 Michael Hanselmann
3013 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
3014 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
3015 1651d116 Michael Hanselmann

3016 1651d116 Michael Hanselmann
  @type names: sequence
3017 1651d116 Michael Hanselmann
  @param names: List of names
3018 1651d116 Michael Hanselmann
  @rtype: List of dicts
3019 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3020 1651d116 Michael Hanselmann
           status couldn't be read
3021 1651d116 Michael Hanselmann

3022 1651d116 Michael Hanselmann
  """
3023 1651d116 Michael Hanselmann
  result = []
3024 1651d116 Michael Hanselmann
3025 1651d116 Michael Hanselmann
  for name in names:
3026 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3027 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3028 1651d116 Michael Hanselmann
3029 1651d116 Michael Hanselmann
    try:
3030 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3031 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3032 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3033 1651d116 Michael Hanselmann
        raise
3034 1651d116 Michael Hanselmann
      data = None
3035 1651d116 Michael Hanselmann
3036 1651d116 Michael Hanselmann
    if not data:
3037 1651d116 Michael Hanselmann
      result.append(None)
3038 1651d116 Michael Hanselmann
      continue
3039 1651d116 Michael Hanselmann
3040 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3041 1651d116 Michael Hanselmann
3042 1651d116 Michael Hanselmann
  return result
3043 1651d116 Michael Hanselmann
3044 1651d116 Michael Hanselmann
3045 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3046 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3047 f81c4737 Michael Hanselmann

3048 f81c4737 Michael Hanselmann
  """
3049 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3050 f81c4737 Michael Hanselmann
3051 f81c4737 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3052 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3053 f81c4737 Michael Hanselmann
3054 f81c4737 Michael Hanselmann
  if pid:
3055 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3056 f81c4737 Michael Hanselmann
                 name, pid)
3057 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3058 f81c4737 Michael Hanselmann
3059 f81c4737 Michael Hanselmann
3060 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3061 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3062 1651d116 Michael Hanselmann

3063 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3064 1651d116 Michael Hanselmann
  whole status directory is removed.
3065 1651d116 Michael Hanselmann

3066 1651d116 Michael Hanselmann
  """
3067 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3068 1651d116 Michael Hanselmann
3069 1651d116 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3070 1651d116 Michael Hanselmann
3071 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3072 1651d116 Michael Hanselmann
3073 1651d116 Michael Hanselmann
  if pid:
3074 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3075 1651d116 Michael Hanselmann
                 name, pid)
3076 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3077 1651d116 Michael Hanselmann
3078 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3079 1651d116 Michael Hanselmann
3080 1651d116 Michael Hanselmann
3081 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3082 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3083 6b93ec9d Iustin Pop

3084 6b93ec9d Iustin Pop
  """
3085 6b93ec9d Iustin Pop
  # set the correct physical ID
3086 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3087 6b93ec9d Iustin Pop
  for cf in disks:
3088 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3089 6b93ec9d Iustin Pop
3090 6b93ec9d Iustin Pop
  bdevs = []
3091 6b93ec9d Iustin Pop
3092 6b93ec9d Iustin Pop
  for cf in disks:
3093 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3094 6b93ec9d Iustin Pop
    if rd is None:
3095 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3096 6b93ec9d Iustin Pop
    bdevs.append(rd)
3097 5a533f8a Iustin Pop
  return bdevs
3098 6b93ec9d Iustin Pop
3099 6b93ec9d Iustin Pop
3100 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3101 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3102 6b93ec9d Iustin Pop

3103 6b93ec9d Iustin Pop
  """
3104 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3105 6b93ec9d Iustin Pop
3106 6b93ec9d Iustin Pop
  # disconnect disks
3107 6b93ec9d Iustin Pop
  for rd in bdevs:
3108 6b93ec9d Iustin Pop
    try:
3109 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3110 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3111 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3112 2cc6781a Iustin Pop
            err, exc=True)
3113 6b93ec9d Iustin Pop
3114 6b93ec9d Iustin Pop
3115 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3116 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3117 6b93ec9d Iustin Pop

3118 6b93ec9d Iustin Pop
  """
3119 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3120 6b93ec9d Iustin Pop
3121 6b93ec9d Iustin Pop
  if multimaster:
3122 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3123 6b93ec9d Iustin Pop
      try:
3124 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3125 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3126 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3127 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3128 6b93ec9d Iustin Pop
  # needed primary mode
3129 6b93ec9d Iustin Pop
  for rd in bdevs:
3130 6b93ec9d Iustin Pop
    try:
3131 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3132 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3133 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3134 3c0cdc83 Michael Hanselmann
3135 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3136 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3137 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3138 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3139 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3140 3c0cdc83 Michael Hanselmann
3141 3c0cdc83 Michael Hanselmann
  def _Attach():
3142 6b93ec9d Iustin Pop
    all_connected = True
3143 3c0cdc83 Michael Hanselmann
3144 6b93ec9d Iustin Pop
    for rd in bdevs:
3145 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3146 3c0cdc83 Michael Hanselmann
3147 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3148 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3149 3c0cdc83 Michael Hanselmann
3150 6b93ec9d Iustin Pop
      if stats.is_standalone:
3151 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3152 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3153 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3154 6b93ec9d Iustin Pop
        try:
3155 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3156 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3157 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3158 3c0cdc83 Michael Hanselmann
3159 3c0cdc83 Michael Hanselmann
    if not all_connected:
3160 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3161 3c0cdc83 Michael Hanselmann
3162 3c0cdc83 Michael Hanselmann
  try:
3163 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3164 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3165 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3166 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3167 3c0cdc83 Michael Hanselmann
3168 6b93ec9d Iustin Pop
  if multimaster:
3169 6b93ec9d Iustin Pop
    # change to primary mode
3170 6b93ec9d Iustin Pop
    for rd in bdevs:
3171 d3da87b8 Iustin Pop
      try:
3172 d3da87b8 Iustin Pop
        rd.Open()
3173 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3174 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3175 6b93ec9d Iustin Pop
3176 6b93ec9d Iustin Pop
3177 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3178 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3179 6b93ec9d Iustin Pop

3180 6b93ec9d Iustin Pop
  """
3181 db8667b7 Iustin Pop
  def _helper(rd):
3182 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3183 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3184 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3185 db8667b7 Iustin Pop
    return stats
3186 db8667b7 Iustin Pop
3187 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3188 6b93ec9d Iustin Pop
3189 6b93ec9d Iustin Pop
  min_resync = 100
3190 6b93ec9d Iustin Pop
  alldone = True
3191 6b93ec9d Iustin Pop
  for rd in bdevs:
3192 db8667b7 Iustin Pop
    try:
3193 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3194 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3195 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3196 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3197 db8667b7 Iustin Pop
      # last check
3198 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3199 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3200 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3201 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3202 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3203 afdc3985 Iustin Pop
3204 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3205 6b93ec9d Iustin Pop
3206 6b93ec9d Iustin Pop
3207 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3208 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3209 c46b9782 Luca Bigliardi

3210 c46b9782 Luca Bigliardi
  """
3211 c46b9782 Luca Bigliardi
  try:
3212 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3213 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3214 c46b9782 Luca Bigliardi
    _Fail(str(err))
3215 c46b9782 Luca Bigliardi
3216 c46b9782 Luca Bigliardi
3217 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3218 f5118ade Iustin Pop
  """Hard-powercycle the node.
3219 f5118ade Iustin Pop

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

3223 f5118ade Iustin Pop
  """
3224 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3225 f5118ade Iustin Pop
  try:
3226 f5118ade Iustin Pop
    pid = os.fork()
3227 29921401 Iustin Pop
  except OSError:
3228 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3229 f5118ade Iustin Pop
    pid = 0
3230 f5118ade Iustin Pop
  if pid > 0:
3231 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3232 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3233 1af6ac0f Luca Bigliardi
  try:
3234 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3235 20601361 Luca Bigliardi
  except Exception: # pylint: disable-msg=W0703
3236 1af6ac0f Luca Bigliardi
    pass
3237 f5118ade Iustin Pop
  time.sleep(5)
3238 f5118ade Iustin Pop
  hyper.PowercycleNode()
3239 f5118ade Iustin Pop
3240 f5118ade Iustin Pop
3241 a8083063 Iustin Pop
class HooksRunner(object):
3242 a8083063 Iustin Pop
  """Hook runner.
3243 a8083063 Iustin Pop

3244 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3245 10c2650b Iustin Pop
  on the master side.
3246 a8083063 Iustin Pop

3247 a8083063 Iustin Pop
  """
3248 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3249 a8083063 Iustin Pop
    """Constructor for hooks runner.
3250 a8083063 Iustin Pop

3251 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
3252 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
3253 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3254 a8083063 Iustin Pop

3255 a8083063 Iustin Pop
    """
3256 a8083063 Iustin Pop
    if hooks_base_dir is None:
3257 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
3258 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3259 fe267188 Iustin Pop
    # constant
3260 fe267188 Iustin Pop
    self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
3261 a8083063 Iustin Pop
3262 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3263 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3264 a8083063 Iustin Pop

3265 10c2650b Iustin Pop
    @type hpath: str
3266 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3267 10c2650b Iustin Pop
        holds the scripts
3268 10c2650b Iustin Pop
    @type phase: str
3269 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3270 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3271 10c2650b Iustin Pop
    @type env: dict
3272 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3273 10c2650b Iustin Pop
    @rtype: list
3274 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3275 10c2650b Iustin Pop
      - script path
3276 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3277 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3278 10c2650b Iustin Pop
      - output of the script
3279 10c2650b Iustin Pop

3280 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3281 10c2650b Iustin Pop
        parameters
3282 a8083063 Iustin Pop

3283 a8083063 Iustin Pop
    """
3284 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3285 a8083063 Iustin Pop
      suffix = "pre"
3286 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3287 a8083063 Iustin Pop
      suffix = "post"
3288 a8083063 Iustin Pop
    else:
3289 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3290 3fb4f740 Iustin Pop
3291 a8083063 Iustin Pop
3292 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3293 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3294 6bb65e3a Guido Trotter
3295 6bb65e3a Guido Trotter
    results = []
3296 a9b7e346 Iustin Pop
3297 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3298 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3299 a9b7e346 Iustin Pop
      # warning at every operation
3300 a9b7e346 Iustin Pop
      return results
3301 a9b7e346 Iustin Pop
3302 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3303 a9b7e346 Iustin Pop
3304 6bb65e3a Guido Trotter
    for (relname, relstatus, runresult)  in runparts_results:
3305 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3306 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3307 a8083063 Iustin Pop
        output = ""
3308 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3309 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3310 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3311 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3312 6bb65e3a Guido Trotter
        if runresult.failed:
3313 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3314 a8083063 Iustin Pop
        else:
3315 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3316 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3317 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3318 6bb65e3a Guido Trotter
3319 6bb65e3a Guido Trotter
    return results
3320 3f78eef2 Iustin Pop
3321 3f78eef2 Iustin Pop
3322 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3323 8d528b7c Iustin Pop
  """IAllocator runner.
3324 8d528b7c Iustin Pop

3325 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3326 8d528b7c Iustin Pop
  the master side.
3327 8d528b7c Iustin Pop

3328 8d528b7c Iustin Pop
  """
3329 7e950d31 Iustin Pop
  @staticmethod
3330 7e950d31 Iustin Pop
  def Run(name, idata):
3331 8d528b7c Iustin Pop
    """Run an iallocator script.
3332 8d528b7c Iustin Pop

3333 10c2650b Iustin Pop
    @type name: str
3334 10c2650b Iustin Pop
    @param name: the iallocator script name
3335 10c2650b Iustin Pop
    @type idata: str
3336 10c2650b Iustin Pop
    @param idata: the allocator input data
3337 10c2650b Iustin Pop

3338 10c2650b Iustin Pop
    @rtype: tuple
3339 87f5c298 Iustin Pop
    @return: two element tuple of:
3340 87f5c298 Iustin Pop
       - status
3341 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3342 8d528b7c Iustin Pop

3343 8d528b7c Iustin Pop
    """
3344 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3345 8d528b7c Iustin Pop
                                  os.path.isfile)
3346 8d528b7c Iustin Pop
    if alloc_script is None:
3347 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3348 8d528b7c Iustin Pop
3349 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3350 8d528b7c Iustin Pop
    try:
3351 8d528b7c Iustin Pop
      os.write(fd, idata)
3352 8d528b7c Iustin Pop
      os.close(fd)
3353 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3354 8d528b7c Iustin Pop
      if result.failed:
3355 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3356 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3357 8d528b7c Iustin Pop
    finally:
3358 8d528b7c Iustin Pop
      os.unlink(fin_name)
3359 8d528b7c Iustin Pop
3360 c26a6bd2 Iustin Pop
    return result.stdout
3361 8d528b7c Iustin Pop
3362 8d528b7c Iustin Pop
3363 3f78eef2 Iustin Pop
class DevCacheManager(object):
3364 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3365 3f78eef2 Iustin Pop

3366 3f78eef2 Iustin Pop
  """
3367 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3368 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3369 3f78eef2 Iustin Pop
3370 3f78eef2 Iustin Pop
  @classmethod
3371 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3372 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3373 3f78eef2 Iustin Pop

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

3377 10c2650b Iustin Pop
    @type dev_path: str
3378 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3379 10c2650b Iustin Pop
    @rtype: str
3380 10c2650b Iustin Pop
    @return: the converted path name
3381 3f78eef2 Iustin Pop

3382 3f78eef2 Iustin Pop
    """
3383 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3384 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3385 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3386 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3387 3f78eef2 Iustin Pop
    return fpath
3388 3f78eef2 Iustin Pop
3389 3f78eef2 Iustin Pop
  @classmethod
3390 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3391 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3392 3f78eef2 Iustin Pop

3393 10c2650b Iustin Pop
    @type dev_path: str
3394 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3395 10c2650b Iustin Pop
    @type owner: str
3396 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3397 10c2650b Iustin Pop
    @type on_primary: bool
3398 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3399 10c2650b Iustin Pop
        node nor not
3400 10c2650b Iustin Pop
    @type iv_name: str
3401 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3402 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3403 10c2650b Iustin Pop

3404 10c2650b Iustin Pop
    @rtype: None
3405 10c2650b Iustin Pop

3406 3f78eef2 Iustin Pop
    """
3407 cf5a8306 Iustin Pop
    if dev_path is None:
3408 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3409 cf5a8306 Iustin Pop
      return
3410 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3411 3f78eef2 Iustin Pop
    if on_primary:
3412 3f78eef2 Iustin Pop
      state = "primary"
3413 3f78eef2 Iustin Pop
    else:
3414 3f78eef2 Iustin Pop
      state = "secondary"
3415 3f78eef2 Iustin Pop
    if iv_name is None:
3416 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3417 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3418 3f78eef2 Iustin Pop
    try:
3419 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3420 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3421 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3422 3f78eef2 Iustin Pop
3423 3f78eef2 Iustin Pop
  @classmethod
3424 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3425 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3426 3f78eef2 Iustin Pop

3427 3865ca48 Michael Hanselmann
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3428 10c2650b Iustin Pop
    path name and logging.
3429 10c2650b Iustin Pop

3430 10c2650b Iustin Pop
    @type dev_path: str
3431 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3432 10c2650b Iustin Pop

3433 10c2650b Iustin Pop
    @rtype: None
3434 10c2650b Iustin Pop

3435 3f78eef2 Iustin Pop
    """
3436 cf5a8306 Iustin Pop
    if dev_path is None:
3437 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3438 cf5a8306 Iustin Pop
      return
3439 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3440 3f78eef2 Iustin Pop
    try:
3441 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3442 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3443 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)