Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 82599b3e

History | View | Annotate | Download (102.4 kB)

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

644 84d7e26b Dmitry Chernyak
  @type vg_names: list
645 84d7e26b Dmitry Chernyak
  @param vg_names: the volume groups whose LVs we should list
646 10c2650b Iustin Pop
  @rtype: dict
647 10c2650b Iustin Pop
  @return:
648 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
649 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
650 10c2650b Iustin Pop

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

653 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
654 10c2650b Iustin Pop
      details.
655 a8083063 Iustin Pop

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

687 10c2650b Iustin Pop
  @rtype: dict
688 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
689 10c2650b Iustin Pop
      size of the volume
690 a8083063 Iustin Pop

691 a8083063 Iustin Pop
  """
692 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
693 a8083063 Iustin Pop
694 a8083063 Iustin Pop
695 dcb93971 Michael Hanselmann
def NodeVolumes():
696 dcb93971 Michael Hanselmann
  """List all volumes on this node.
697 dcb93971 Michael Hanselmann

698 10c2650b Iustin Pop
  @rtype: list
699 10c2650b Iustin Pop
  @return:
700 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
701 10c2650b Iustin Pop
      - name: the logical volume name,
702 10c2650b Iustin Pop
      - size: the size of the logical volume
703 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
704 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
705 10c2650b Iustin Pop

706 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
707 10c2650b Iustin Pop
    error.
708 10c2650b Iustin Pop

709 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
710 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
711 10c2650b Iustin Pop
    multiple times.
712 10c2650b Iustin Pop

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

744 b1206984 Iustin Pop
  @rtype: boolean
745 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
746 a8083063 Iustin Pop

747 a8083063 Iustin Pop
  """
748 35c0c8da Iustin Pop
  missing = []
749 a8083063 Iustin Pop
  for bridge in bridges_list:
750 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
751 35c0c8da Iustin Pop
      missing.append(bridge)
752 a8083063 Iustin Pop
753 35c0c8da Iustin Pop
  if missing:
754 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
755 35c0c8da Iustin Pop
756 a8083063 Iustin Pop
757 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
758 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
759 a8083063 Iustin Pop

760 e69d05fd Iustin Pop
  @type hypervisor_list: list
761 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
762 e69d05fd Iustin Pop

763 e69d05fd Iustin Pop
  @rtype: list
764 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
765 10c2650b Iustin Pop
    - instance1.example.com
766 10c2650b Iustin Pop
    - instance2.example.com
767 a8083063 Iustin Pop

768 098c0958 Michael Hanselmann
  """
769 e69d05fd Iustin Pop
  results = []
770 e69d05fd Iustin Pop
  for hname in hypervisor_list:
771 e69d05fd Iustin Pop
    try:
772 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
773 e69d05fd Iustin Pop
      results.extend(names)
774 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
775 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
776 aca13712 Iustin Pop
            hname, err, exc=True)
777 a8083063 Iustin Pop
778 e69d05fd Iustin Pop
  return results
779 a8083063 Iustin Pop
780 a8083063 Iustin Pop
781 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
782 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
783 a8083063 Iustin Pop

784 e69d05fd Iustin Pop
  @type instance: string
785 e69d05fd Iustin Pop
  @param instance: the instance name
786 e69d05fd Iustin Pop
  @type hname: string
787 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
788 a8083063 Iustin Pop

789 e69d05fd Iustin Pop
  @rtype: dict
790 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
791 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
792 e69d05fd Iustin Pop
      - state: xen state of instance (string)
793 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
794 a8083063 Iustin Pop

795 098c0958 Michael Hanselmann
  """
796 a8083063 Iustin Pop
  output = {}
797 a8083063 Iustin Pop
798 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
799 a8083063 Iustin Pop
  if iinfo is not None:
800 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
801 a8083063 Iustin Pop
    output['state'] = iinfo[4]
802 a8083063 Iustin Pop
    output['time'] = iinfo[5]
803 a8083063 Iustin Pop
804 c26a6bd2 Iustin Pop
  return output
805 a8083063 Iustin Pop
806 a8083063 Iustin Pop
807 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
808 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
809 56e7640c Iustin Pop

810 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
811 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
812 56e7640c Iustin Pop

813 56e7640c Iustin Pop
  @rtype: tuple
814 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
815 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
816 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
817 56e7640c Iustin Pop

818 56e7640c Iustin Pop
  """
819 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
820 afdc3985 Iustin Pop
  iname = instance.name
821 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
822 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
823 56e7640c Iustin Pop
824 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
825 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
826 56e7640c Iustin Pop
    if not os.path.islink(link_name):
827 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
828 b8ebd37b Iustin Pop
                      iname, link_name, idx)
829 56e7640c Iustin Pop
830 56e7640c Iustin Pop
831 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
832 a8083063 Iustin Pop
  """Gather data about all instances.
833 a8083063 Iustin Pop

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

838 e69d05fd Iustin Pop
  @type hypervisor_list: list
839 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
840 e69d05fd Iustin Pop

841 955db481 Guido Trotter
  @rtype: dict
842 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
843 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
844 e69d05fd Iustin Pop
      - state: xen state of instance (string)
845 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
846 10c2650b Iustin Pop
      - vcpus: the number of vcpus
847 a8083063 Iustin Pop

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

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

880 81a3406c Iustin Pop
  @type kind: string
881 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
882 81a3406c Iustin Pop
  @type os_name: string
883 81a3406c Iustin Pop
  @param os_name: the os name
884 81a3406c Iustin Pop
  @type instance: string
885 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
886 81a3406c Iustin Pop

887 81a3406c Iustin Pop
  """
888 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
889 1d466a4f Michael Hanselmann
  base = ("%s-%s-%s-%s.log" %
890 1d466a4f Michael Hanselmann
          (kind, os_name, instance, utils.TimestampForFilename()))
891 81a3406c Iustin Pop
  return utils.PathJoin(constants.LOG_OS_DIR, base)
892 81a3406c Iustin Pop
893 81a3406c Iustin Pop
894 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
895 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
896 a8083063 Iustin Pop

897 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
898 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
899 e557bae9 Guido Trotter
  @type reinstall: boolean
900 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
901 4a0e011f Iustin Pop
  @type debug: integer
902 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
903 c26a6bd2 Iustin Pop
  @rtype: None
904 a8083063 Iustin Pop

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

929 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
930 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
931 d15a9ad3 Guido Trotter
  @type old_name: string
932 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
933 4a0e011f Iustin Pop
  @type debug: integer
934 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
935 10c2650b Iustin Pop
  @rtype: boolean
936 10c2650b Iustin Pop
  @return: the success of the operation
937 decd5f45 Iustin Pop

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

967 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
968 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
969 9332fd8a Iustin Pop

970 9332fd8a Iustin Pop

971 5282084b Iustin Pop
  @param instance_name: the name of the target instance
972 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
973 5282084b Iustin Pop
  @param idx: the disk index
974 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
975 9332fd8a Iustin Pop

976 9332fd8a Iustin Pop
  """
977 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
978 9332fd8a Iustin Pop
  try:
979 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
980 5282084b Iustin Pop
  except OSError, err:
981 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
982 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
983 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
984 9332fd8a Iustin Pop
        os.remove(link_name)
985 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
986 9332fd8a Iustin Pop
    else:
987 9332fd8a Iustin Pop
      raise
988 9332fd8a Iustin Pop
989 9332fd8a Iustin Pop
  return link_name
990 9332fd8a Iustin Pop
991 9332fd8a Iustin Pop
992 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
993 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
994 3c9c571d Iustin Pop

995 3c9c571d Iustin Pop
  """
996 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
997 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
998 5282084b Iustin Pop
    if os.path.islink(link_name):
999 3c9c571d Iustin Pop
      try:
1000 03dfa658 Iustin Pop
        os.remove(link_name)
1001 03dfa658 Iustin Pop
      except OSError:
1002 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1003 3c9c571d Iustin Pop
1004 3c9c571d Iustin Pop
1005 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1006 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1007 a8083063 Iustin Pop

1008 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1009 a8083063 Iustin Pop
  devices must be already assembled.
1010 a8083063 Iustin Pop

1011 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1012 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1013 069cfbf1 Iustin Pop
  @rtype: list
1014 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1015 10c2650b Iustin Pop

1016 a8083063 Iustin Pop
  """
1017 a8083063 Iustin Pop
  block_devices = []
1018 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1019 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1020 a8083063 Iustin Pop
    if device is None:
1021 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1022 a8083063 Iustin Pop
                                    str(disk))
1023 a8083063 Iustin Pop
    device.Open()
1024 9332fd8a Iustin Pop
    try:
1025 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1026 9332fd8a Iustin Pop
    except OSError, e:
1027 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1028 9332fd8a Iustin Pop
                                    e.strerror)
1029 9332fd8a Iustin Pop
1030 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1031 9332fd8a Iustin Pop
1032 a8083063 Iustin Pop
  return block_devices
1033 a8083063 Iustin Pop
1034 a8083063 Iustin Pop
1035 07813a9e Iustin Pop
def StartInstance(instance):
1036 a8083063 Iustin Pop
  """Start an instance.
1037 a8083063 Iustin Pop

1038 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1039 e69d05fd Iustin Pop
  @param instance: the instance object
1040 c26a6bd2 Iustin Pop
  @rtype: None
1041 a8083063 Iustin Pop

1042 098c0958 Michael Hanselmann
  """
1043 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1044 a8083063 Iustin Pop
1045 a8083063 Iustin Pop
  if instance.name in running_instances:
1046 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1047 c26a6bd2 Iustin Pop
    return
1048 a8083063 Iustin Pop
1049 a8083063 Iustin Pop
  try:
1050 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1051 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1052 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
1053 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1054 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1055 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1056 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1057 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1058 a8083063 Iustin Pop
1059 a8083063 Iustin Pop
1060 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1061 a8083063 Iustin Pop
  """Shut an instance down.
1062 a8083063 Iustin Pop

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

1065 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1066 e69d05fd Iustin Pop
  @param instance: the instance object
1067 6263189c Guido Trotter
  @type timeout: integer
1068 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1069 c26a6bd2 Iustin Pop
  @rtype: None
1070 a8083063 Iustin Pop

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

1132 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1133 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1134 10c2650b Iustin Pop
  @type reboot_type: str
1135 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1136 10c2650b Iustin Pop
    constants:
1137 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1138 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1139 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1140 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1141 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1142 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1143 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1144 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1145 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1146 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1147 c26a6bd2 Iustin Pop
  @rtype: None
1148 007a2f3e Alexander Schreiber

1149 007a2f3e Alexander Schreiber
  """
1150 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1151 007a2f3e Alexander Schreiber
1152 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1153 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1154 007a2f3e Alexander Schreiber
1155 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1156 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1157 007a2f3e Alexander Schreiber
    try:
1158 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1159 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1160 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1161 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1162 007a2f3e Alexander Schreiber
    try:
1163 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1164 07813a9e Iustin Pop
      return StartInstance(instance)
1165 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1166 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1167 007a2f3e Alexander Schreiber
  else:
1168 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1169 007a2f3e Alexander Schreiber
1170 007a2f3e Alexander Schreiber
1171 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1172 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1173 6906a9d8 Guido Trotter

1174 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1175 6906a9d8 Guido Trotter
  @param instance: the instance definition
1176 6906a9d8 Guido Trotter

1177 6906a9d8 Guido Trotter
  """
1178 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1179 cd42d0ad Guido Trotter
  try:
1180 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1181 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1182 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1183 c26a6bd2 Iustin Pop
  return info
1184 6906a9d8 Guido Trotter
1185 6906a9d8 Guido Trotter
1186 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1187 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1188 6906a9d8 Guido Trotter

1189 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1190 6906a9d8 Guido Trotter
  @param instance: the instance definition
1191 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1192 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1193 6906a9d8 Guido Trotter
  @type target: string
1194 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1195 6906a9d8 Guido Trotter

1196 6906a9d8 Guido Trotter
  """
1197 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1198 cd42d0ad Guido Trotter
  try:
1199 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1200 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1201 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1202 6906a9d8 Guido Trotter
1203 6906a9d8 Guido Trotter
1204 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1205 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1206 6906a9d8 Guido Trotter

1207 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1208 6906a9d8 Guido Trotter
  @param instance: the instance definition
1209 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1210 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1211 6906a9d8 Guido Trotter
  @type success: boolean
1212 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1213 6906a9d8 Guido Trotter

1214 6906a9d8 Guido Trotter
  """
1215 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1216 cd42d0ad Guido Trotter
  try:
1217 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1218 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1219 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1220 6906a9d8 Guido Trotter
1221 6906a9d8 Guido Trotter
1222 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1223 2a10865c Iustin Pop
  """Migrates an instance to another node.
1224 2a10865c Iustin Pop

1225 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1226 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1227 9f0e6b37 Iustin Pop
  @type target: string
1228 9f0e6b37 Iustin Pop
  @param target: the target node name
1229 9f0e6b37 Iustin Pop
  @type live: boolean
1230 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1231 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1232 9f0e6b37 Iustin Pop
  @rtype: tuple
1233 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1234 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1235 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1236 9f0e6b37 Iustin Pop

1237 2a10865c Iustin Pop
  """
1238 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1239 2a10865c Iustin Pop
1240 2a10865c Iustin Pop
  try:
1241 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1242 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1243 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1244 2a10865c Iustin Pop
1245 2a10865c Iustin Pop
1246 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1247 a8083063 Iustin Pop
  """Creates a block device for an instance.
1248 a8083063 Iustin Pop

1249 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1250 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1251 b1206984 Iustin Pop
  @type size: int
1252 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1253 b1206984 Iustin Pop
  @type owner: str
1254 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1255 b1206984 Iustin Pop
      used for device cache data
1256 b1206984 Iustin Pop
  @type on_primary: boolean
1257 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1258 b1206984 Iustin Pop
  @type info: string
1259 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1260 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1261 b1206984 Iustin Pop

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

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

1313 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1314 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1315 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1316 69dd363f René Nussbaumer

1317 69dd363f René Nussbaumer
  """
1318 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1319 da63bb4e René Nussbaumer
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1320 da63bb4e René Nussbaumer
         "count=%d" % size]
1321 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1322 69dd363f René Nussbaumer
1323 69dd363f René Nussbaumer
  if result.failed:
1324 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1325 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1326 69dd363f René Nussbaumer
1327 69dd363f René Nussbaumer
1328 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1329 69dd363f René Nussbaumer
  """Wipes a block device.
1330 69dd363f René Nussbaumer

1331 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1332 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1333 da63bb4e René Nussbaumer
  @type offset: int
1334 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1335 da63bb4e René Nussbaumer
  @type size: int
1336 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1337 69dd363f René Nussbaumer

1338 69dd363f René Nussbaumer
  """
1339 69dd363f René Nussbaumer
  try:
1340 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1341 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1342 da63bb4e René Nussbaumer
    rdev = None
1343 da63bb4e René Nussbaumer
1344 da63bb4e René Nussbaumer
  if not rdev:
1345 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1346 da63bb4e René Nussbaumer
1347 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1348 da63bb4e René Nussbaumer
  if offset > rdev.size:
1349 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1350 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1351 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1352 69dd363f René Nussbaumer
1353 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1354 69dd363f René Nussbaumer
1355 69dd363f René Nussbaumer
1356 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1357 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1358 5119c79e René Nussbaumer

1359 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1360 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1361 5119c79e René Nussbaumer
  @type pause: bool
1362 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1363 5119c79e René Nussbaumer

1364 5119c79e René Nussbaumer
  """
1365 5119c79e René Nussbaumer
  success = []
1366 5119c79e René Nussbaumer
  for disk in disks:
1367 5119c79e René Nussbaumer
    try:
1368 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1369 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1370 5119c79e René Nussbaumer
      rdev = None
1371 5119c79e René Nussbaumer
1372 5119c79e René Nussbaumer
    if not rdev:
1373 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1374 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1375 5119c79e René Nussbaumer
      continue
1376 5119c79e René Nussbaumer
1377 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1378 5119c79e René Nussbaumer
1379 5119c79e René Nussbaumer
    if result:
1380 5119c79e René Nussbaumer
      success.append((result, None))
1381 5119c79e René Nussbaumer
    else:
1382 5119c79e René Nussbaumer
      if pause:
1383 5119c79e René Nussbaumer
        msg = "Pause"
1384 5119c79e René Nussbaumer
      else:
1385 5119c79e René Nussbaumer
        msg = "Resume"
1386 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1387 5119c79e René Nussbaumer
1388 5119c79e René Nussbaumer
  return success
1389 5119c79e René Nussbaumer
1390 5119c79e René Nussbaumer
1391 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1392 a8083063 Iustin Pop
  """Remove a block device.
1393 a8083063 Iustin Pop

1394 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1395 10c2650b Iustin Pop

1396 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1397 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1398 10c2650b Iustin Pop
  @rtype: boolean
1399 10c2650b Iustin Pop
  @return: the success of the operation
1400 a8083063 Iustin Pop

1401 a8083063 Iustin Pop
  """
1402 e1bc0878 Iustin Pop
  msgs = []
1403 a8083063 Iustin Pop
  try:
1404 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1405 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1406 a8083063 Iustin Pop
    # probably can't attach
1407 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1408 a8083063 Iustin Pop
    rdev = None
1409 a8083063 Iustin Pop
  if rdev is not None:
1410 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1411 e1bc0878 Iustin Pop
    try:
1412 0c6c04ec Iustin Pop
      rdev.Remove()
1413 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1414 e1bc0878 Iustin Pop
      msgs.append(str(err))
1415 c26a6bd2 Iustin Pop
    if not msgs:
1416 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1417 e1bc0878 Iustin Pop
1418 a8083063 Iustin Pop
  if disk.children:
1419 a8083063 Iustin Pop
    for child in disk.children:
1420 c26a6bd2 Iustin Pop
      try:
1421 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1422 c26a6bd2 Iustin Pop
      except RPCFail, err:
1423 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1424 e1bc0878 Iustin Pop
1425 c26a6bd2 Iustin Pop
  if msgs:
1426 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1427 afdc3985 Iustin Pop
1428 a8083063 Iustin Pop
1429 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1430 a8083063 Iustin Pop
  """Activate a block device for an instance.
1431 a8083063 Iustin Pop

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

1434 10c2650b Iustin Pop
  @note: this function is called recursively.
1435 a8083063 Iustin Pop

1436 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1437 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1438 10c2650b Iustin Pop
  @type owner: str
1439 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1440 10c2650b Iustin Pop
  @type as_primary: boolean
1441 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1442 10c2650b Iustin Pop
      read/write
1443 a8083063 Iustin Pop

1444 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1445 10c2650b Iustin Pop
      was assembled)
1446 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1447 10c2650b Iustin Pop
      during the activation of the children or the device
1448 10c2650b Iustin Pop
      itself
1449 a8083063 Iustin Pop

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

1486 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1487 a8083063 Iustin Pop

1488 b1206984 Iustin Pop
  @rtype: str or boolean
1489 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1490 b1206984 Iustin Pop
      C{True} for secondary nodes
1491 a8083063 Iustin Pop

1492 a8083063 Iustin Pop
  """
1493 53c14ef1 Iustin Pop
  try:
1494 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1495 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1496 fe267188 Iustin Pop
      # pylint: disable-msg=E1103
1497 53c14ef1 Iustin Pop
      result = result.dev_path
1498 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1499 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1500 afdc3985 Iustin Pop
1501 c26a6bd2 Iustin Pop
  return result
1502 a8083063 Iustin Pop
1503 a8083063 Iustin Pop
1504 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1505 a8083063 Iustin Pop
  """Shut down a block device.
1506 a8083063 Iustin Pop

1507 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1508 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1509 c41eea6e Iustin Pop
  shutdown.
1510 a8083063 Iustin Pop

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

1515 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1516 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1517 10c2650b Iustin Pop
      shutdown
1518 c26a6bd2 Iustin Pop
  @rtype: None
1519 10c2650b Iustin Pop

1520 a8083063 Iustin Pop
  """
1521 cacfd1fd Iustin Pop
  msgs = []
1522 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1523 a8083063 Iustin Pop
  if r_dev is not None:
1524 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1525 cacfd1fd Iustin Pop
    try:
1526 746f7476 Iustin Pop
      r_dev.Shutdown()
1527 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1528 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1529 cacfd1fd Iustin Pop
      msgs.append(str(err))
1530 746f7476 Iustin Pop
1531 a8083063 Iustin Pop
  if disk.children:
1532 a8083063 Iustin Pop
    for child in disk.children:
1533 c26a6bd2 Iustin Pop
      try:
1534 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1535 c26a6bd2 Iustin Pop
      except RPCFail, err:
1536 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1537 746f7476 Iustin Pop
1538 c26a6bd2 Iustin Pop
  if msgs:
1539 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1540 a8083063 Iustin Pop
1541 a8083063 Iustin Pop
1542 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1543 153d9724 Iustin Pop
  """Extend a mirrored block device.
1544 a8083063 Iustin Pop

1545 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1546 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1547 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1548 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1549 c26a6bd2 Iustin Pop
  @rtype: None
1550 10c2650b Iustin Pop

1551 a8083063 Iustin Pop
  """
1552 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1553 153d9724 Iustin Pop
  if parent_bdev is None:
1554 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1555 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1556 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1557 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1558 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1559 a8083063 Iustin Pop
1560 a8083063 Iustin Pop
1561 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1562 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1563 a8083063 Iustin Pop

1564 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1565 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1566 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1567 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1568 c26a6bd2 Iustin Pop
  @rtype: None
1569 10c2650b Iustin Pop

1570 a8083063 Iustin Pop
  """
1571 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1572 153d9724 Iustin Pop
  if parent_bdev is None:
1573 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1574 e739bd57 Iustin Pop
  devs = []
1575 e739bd57 Iustin Pop
  for disk in new_cdevs:
1576 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1577 e739bd57 Iustin Pop
    if rpath is None:
1578 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1579 e739bd57 Iustin Pop
      if bd is None:
1580 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1581 e739bd57 Iustin Pop
      else:
1582 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1583 e739bd57 Iustin Pop
    else:
1584 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1585 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1586 e739bd57 Iustin Pop
      devs.append(rpath)
1587 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1588 a8083063 Iustin Pop
1589 a8083063 Iustin Pop
1590 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1591 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1592 a8083063 Iustin Pop

1593 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1594 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1595 10c2650b Iustin Pop
  @rtype: disk
1596 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1597 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1598 10c2650b Iustin Pop
      found
1599 a8083063 Iustin Pop

1600 a8083063 Iustin Pop
  """
1601 a8083063 Iustin Pop
  stats = []
1602 a8083063 Iustin Pop
  for dsk in disks:
1603 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1604 a8083063 Iustin Pop
    if rbd is None:
1605 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1606 96acbc09 Michael Hanselmann
1607 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1608 96acbc09 Michael Hanselmann
1609 c26a6bd2 Iustin Pop
  return stats
1610 a8083063 Iustin Pop
1611 a8083063 Iustin Pop
1612 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1613 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1614 c6a9dffa Michael Hanselmann

1615 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1616 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1617 c6a9dffa Michael Hanselmann
  @rtype: disk
1618 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1619 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
1620 c6a9dffa Michael Hanselmann
    otherwise
1621 c6a9dffa Michael Hanselmann

1622 c6a9dffa Michael Hanselmann
  """
1623 c6a9dffa Michael Hanselmann
  result = []
1624 c6a9dffa Michael Hanselmann
  for disk in disks:
1625 c6a9dffa Michael Hanselmann
    try:
1626 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
1627 c6a9dffa Michael Hanselmann
      if rbd is None:
1628 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
1629 c6a9dffa Michael Hanselmann
        continue
1630 c6a9dffa Michael Hanselmann
1631 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
1632 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
1633 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
1634 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
1635 c6a9dffa Michael Hanselmann
    else:
1636 c6a9dffa Michael Hanselmann
      result.append((True, status))
1637 c6a9dffa Michael Hanselmann
1638 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
1639 c6a9dffa Michael Hanselmann
1640 c6a9dffa Michael Hanselmann
  return result
1641 c6a9dffa Michael Hanselmann
1642 c6a9dffa Michael Hanselmann
1643 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1644 a8083063 Iustin Pop
  """Check if a device is activated.
1645 a8083063 Iustin Pop

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

1648 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1649 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1650 a8083063 Iustin Pop

1651 10c2650b Iustin Pop
  @return: None if the device can't be found,
1652 10c2650b Iustin Pop
      otherwise the device instance
1653 a8083063 Iustin Pop

1654 a8083063 Iustin Pop
  """
1655 a8083063 Iustin Pop
  children = []
1656 a8083063 Iustin Pop
  if disk.children:
1657 a8083063 Iustin Pop
    for chdisk in disk.children:
1658 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1659 a8083063 Iustin Pop
1660 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1661 a8083063 Iustin Pop
1662 a8083063 Iustin Pop
1663 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1664 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1665 f2e07bb4 Michael Hanselmann

1666 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1667 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1668 f2e07bb4 Michael Hanselmann

1669 f2e07bb4 Michael Hanselmann
  """
1670 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1671 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1672 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1673 f2e07bb4 Michael Hanselmann
1674 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1675 f2e07bb4 Michael Hanselmann
1676 f2e07bb4 Michael Hanselmann
  return real_disk
1677 f2e07bb4 Michael Hanselmann
1678 f2e07bb4 Michael Hanselmann
1679 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1680 a8083063 Iustin Pop
  """Check if a device is activated.
1681 a8083063 Iustin Pop

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

1684 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1685 10c2650b Iustin Pop
  @param disk: the disk to find
1686 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1687 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1688 96acbc09 Michael Hanselmann
           information
1689 a8083063 Iustin Pop

1690 a8083063 Iustin Pop
  """
1691 23829f6f Iustin Pop
  try:
1692 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1693 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1694 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1695 96acbc09 Michael Hanselmann
1696 a8083063 Iustin Pop
  if rbd is None:
1697 c26a6bd2 Iustin Pop
    return None
1698 96acbc09 Michael Hanselmann
1699 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
1700 a8083063 Iustin Pop
1701 a8083063 Iustin Pop
1702 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1703 968a7623 Iustin Pop
  """Computes the size of the given disks.
1704 968a7623 Iustin Pop

1705 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
1706 968a7623 Iustin Pop

1707 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
1708 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
1709 968a7623 Iustin Pop
  @rtype: list
1710 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
1711 968a7623 Iustin Pop
      otherwise the size
1712 968a7623 Iustin Pop

1713 968a7623 Iustin Pop
  """
1714 968a7623 Iustin Pop
  result = []
1715 968a7623 Iustin Pop
  for cf in disks:
1716 968a7623 Iustin Pop
    try:
1717 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
1718 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
1719 968a7623 Iustin Pop
      result.append(None)
1720 968a7623 Iustin Pop
      continue
1721 968a7623 Iustin Pop
    if rbd is None:
1722 968a7623 Iustin Pop
      result.append(None)
1723 968a7623 Iustin Pop
    else:
1724 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
1725 968a7623 Iustin Pop
  return result
1726 968a7623 Iustin Pop
1727 968a7623 Iustin Pop
1728 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1729 858f3d18 Iustin Pop
  """Export a block device to a remote node.
1730 858f3d18 Iustin Pop

1731 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
1732 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
1733 858f3d18 Iustin Pop
  @type dest_node: str
1734 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
1735 858f3d18 Iustin Pop
  @type dest_path: str
1736 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
1737 858f3d18 Iustin Pop
  @type cluster_name: str
1738 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1739 858f3d18 Iustin Pop
  @rtype: None
1740 858f3d18 Iustin Pop

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

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

1778 10c2650b Iustin Pop
  @type file_name: str
1779 10c2650b Iustin Pop
  @param file_name: the target file name
1780 10c2650b Iustin Pop
  @type data: str
1781 10c2650b Iustin Pop
  @param data: the new contents of the file
1782 10c2650b Iustin Pop
  @type mode: int
1783 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1784 10c2650b Iustin Pop
  @type uid: int
1785 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1786 10c2650b Iustin Pop
  @type gid: int
1787 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1788 10c2650b Iustin Pop
  @type atime: float
1789 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1790 10c2650b Iustin Pop
  @type mtime: float
1791 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1792 c26a6bd2 Iustin Pop
  @rtype: None
1793 10c2650b Iustin Pop

1794 a8083063 Iustin Pop
  """
1795 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1796 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1797 a8083063 Iustin Pop
1798 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
1799 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1800 2cc6781a Iustin Pop
          file_name)
1801 a8083063 Iustin Pop
1802 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1803 12bce260 Michael Hanselmann
1804 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
1805 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
1806 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
1807 a8083063 Iustin Pop
1808 386b57af Iustin Pop
1809 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
1810 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
1811 b2f29800 René Nussbaumer

1812 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
1813 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
1814 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
1815 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
1816 b2f29800 René Nussbaumer

1817 b2f29800 René Nussbaumer
  @return: stdout
1818 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
1819 b2f29800 René Nussbaumer

1820 b2f29800 René Nussbaumer
  """
1821 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
1822 b2f29800 René Nussbaumer
1823 b2f29800 René Nussbaumer
  if result.failed:
1824 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
1825 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
1826 b2f29800 René Nussbaumer
1827 b2f29800 René Nussbaumer
  return result.stdout
1828 b2f29800 René Nussbaumer
1829 b2f29800 René Nussbaumer
1830 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1831 89b14f05 Iustin Pop
  """Update all ssconf files.
1832 89b14f05 Iustin Pop

1833 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1834 89b14f05 Iustin Pop

1835 89b14f05 Iustin Pop
  """
1836 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1837 6ddc95ec Michael Hanselmann
1838 6ddc95ec Michael Hanselmann
1839 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1840 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1841 a8083063 Iustin Pop

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

1846 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1847 10c2650b Iustin Pop
  @param err: the exception to format
1848 a8083063 Iustin Pop

1849 a8083063 Iustin Pop
  """
1850 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1851 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1852 a8083063 Iustin Pop
  else:
1853 a8083063 Iustin Pop
    detail = str(err)
1854 a8083063 Iustin Pop
  return detail
1855 a8083063 Iustin Pop
1856 5d0fe286 Iustin Pop
1857 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
1858 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1859 a8083063 Iustin Pop

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

1863 10c2650b Iustin Pop
  @type os_dir: str
1864 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
1865 8e70b181 Iustin Pop
  @rtype: tuple
1866 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
1867 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
1868 a8083063 Iustin Pop

1869 a8083063 Iustin Pop
  """
1870 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1871 a8083063 Iustin Pop
1872 a8083063 Iustin Pop
  try:
1873 a8083063 Iustin Pop
    st = os.stat(api_file)
1874 a8083063 Iustin Pop
  except EnvironmentError, err:
1875 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
1876 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1877 a8083063 Iustin Pop
1878 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1879 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
1880 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
1881 a8083063 Iustin Pop
1882 a8083063 Iustin Pop
  try:
1883 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
1884 a8083063 Iustin Pop
  except EnvironmentError, err:
1885 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
1886 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
1887 a8083063 Iustin Pop
1888 a8083063 Iustin Pop
  try:
1889 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
1890 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1891 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
1892 255dcebd Iustin Pop
                   str(err))
1893 a8083063 Iustin Pop
1894 255dcebd Iustin Pop
  return True, api_versions
1895 a8083063 Iustin Pop
1896 386b57af Iustin Pop
1897 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1898 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1899 a8083063 Iustin Pop

1900 10c2650b Iustin Pop
  @type top_dirs: list
1901 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1902 10c2650b Iustin Pop
      search (if not given defaults to
1903 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1904 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1905 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
1906 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
1907 bad78e66 Iustin Pop
      search paths, where:
1908 255dcebd Iustin Pop
          - name is the (potential) OS name
1909 255dcebd Iustin Pop
          - path is the full path to the OS
1910 255dcebd Iustin Pop
          - status True/False is the validity of the OS
1911 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
1912 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
1913 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
1914 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
1915 a8083063 Iustin Pop

1916 a8083063 Iustin Pop
  """
1917 7c3d51d4 Guido Trotter
  if top_dirs is None:
1918 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1919 a8083063 Iustin Pop
1920 a8083063 Iustin Pop
  result = []
1921 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1922 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1923 7c3d51d4 Guido Trotter
      try:
1924 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1925 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1926 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1927 7c3d51d4 Guido Trotter
        break
1928 7c3d51d4 Guido Trotter
      for name in f_names:
1929 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
1930 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1931 255dcebd Iustin Pop
        if status:
1932 255dcebd Iustin Pop
          diagnose = ""
1933 ba00557a Guido Trotter
          variants = os_inst.supported_variants
1934 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
1935 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
1936 255dcebd Iustin Pop
        else:
1937 255dcebd Iustin Pop
          diagnose = os_inst
1938 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
1939 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
1940 bad78e66 Iustin Pop
                       parameters, api_versions))
1941 a8083063 Iustin Pop
1942 c26a6bd2 Iustin Pop
  return result
1943 a8083063 Iustin Pop
1944 a8083063 Iustin Pop
1945 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
1946 a8083063 Iustin Pop
  """Create an OS instance from disk.
1947 a8083063 Iustin Pop

1948 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1949 8e70b181 Iustin Pop
  valid OS name.
1950 a8083063 Iustin Pop

1951 8ee4dc80 Guido Trotter
  @type base_dir: string
1952 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1953 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1954 255dcebd Iustin Pop
  @rtype: tuple
1955 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
1956 255dcebd Iustin Pop
      or error message
1957 7c3d51d4 Guido Trotter

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

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

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

2049 255dcebd Iustin Pop
  @type base_dir: string
2050 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2051 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2052 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2053 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2054 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2055 255dcebd Iustin Pop

2056 255dcebd Iustin Pop
  """
2057 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2058 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2059 255dcebd Iustin Pop
2060 255dcebd Iustin Pop
  if not status:
2061 255dcebd Iustin Pop
    _Fail(payload)
2062 a8083063 Iustin Pop
2063 255dcebd Iustin Pop
  return payload
2064 a8083063 Iustin Pop
2065 a8083063 Iustin Pop
2066 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2067 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2068 2266edb2 Guido Trotter

2069 a025e535 Vitaly Kuznetsov
  @type os_name: str
2070 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2071 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2072 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2073 1bdcbbab Iustin Pop
  @type os_params: dict
2074 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2075 2266edb2 Guido Trotter
  @type debug: integer
2076 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2077 2266edb2 Guido Trotter
  @rtype: dict
2078 2266edb2 Guido Trotter
  @return: dict of environment variables
2079 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2080 10c2650b Iustin Pop
      cannot be found
2081 2266edb2 Guido Trotter

2082 2266edb2 Guido Trotter
  """
2083 2266edb2 Guido Trotter
  result = {}
2084 099c52ad Iustin Pop
  api_version = \
2085 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2086 d1a7d66f Guido Trotter
  result['OS_API_VERSION'] = '%d' % api_version
2087 efaa9b06 Iustin Pop
  result['OS_NAME'] = inst_os.name
2088 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
2089 efaa9b06 Iustin Pop
2090 efaa9b06 Iustin Pop
  # OS variants
2091 f11280b5 Guido Trotter
  if api_version >= constants.OS_API_V15:
2092 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2093 870dc44c Iustin Pop
    if not variant:
2094 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2095 f11280b5 Guido Trotter
    result['OS_VARIANT'] = variant
2096 efaa9b06 Iustin Pop
2097 1bdcbbab Iustin Pop
  # OS params
2098 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2099 1bdcbbab Iustin Pop
    result['OSP_%s' % pname.upper()] = pvalue
2100 1bdcbbab Iustin Pop
2101 efaa9b06 Iustin Pop
  return result
2102 efaa9b06 Iustin Pop
2103 efaa9b06 Iustin Pop
2104 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2105 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2106 efaa9b06 Iustin Pop

2107 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2108 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2109 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2110 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2111 efaa9b06 Iustin Pop
  @type debug: integer
2112 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2113 efaa9b06 Iustin Pop
  @rtype: dict
2114 efaa9b06 Iustin Pop
  @return: dict of environment variables
2115 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2116 efaa9b06 Iustin Pop
      cannot be found
2117 efaa9b06 Iustin Pop

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

2167 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2168 10c2650b Iustin Pop
  first ones to resize.
2169 594609c0 Iustin Pop

2170 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2171 10c2650b Iustin Pop
  @param disk: the disk to be grown
2172 10c2650b Iustin Pop
  @rtype: (status, result)
2173 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
2174 10c2650b Iustin Pop
      (True/False), and the errors message if status
2175 10c2650b Iustin Pop
      is False
2176 594609c0 Iustin Pop

2177 594609c0 Iustin Pop
  """
2178 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2179 594609c0 Iustin Pop
  if r_dev is None:
2180 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2181 594609c0 Iustin Pop
2182 594609c0 Iustin Pop
  try:
2183 594609c0 Iustin Pop
    r_dev.Grow(amount)
2184 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2185 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2186 594609c0 Iustin Pop
2187 594609c0 Iustin Pop
2188 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2189 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2190 a8083063 Iustin Pop

2191 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2192 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2193 a8083063 Iustin Pop

2194 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2195 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2196 e9e9263d Guido Trotter
  @rtype: string
2197 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2198 a8083063 Iustin Pop

2199 098c0958 Michael Hanselmann
  """
2200 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2201 433c63aa Iustin Pop
    if not disk.children:
2202 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2203 433c63aa Iustin Pop
            disk.unique_id)
2204 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2205 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2206 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2207 a8083063 Iustin Pop
    if r_dev is not None:
2208 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2209 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2210 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2211 a8083063 Iustin Pop
    else:
2212 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2213 a8083063 Iustin Pop
  else:
2214 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2215 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2216 a8083063 Iustin Pop
2217 a8083063 Iustin Pop
2218 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2219 a8083063 Iustin Pop
  """Write out the export configuration information.
2220 a8083063 Iustin Pop

2221 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2222 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2223 10c2650b Iustin Pop
      saving configuration
2224 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2225 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2226 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2227 a8083063 Iustin Pop

2228 c26a6bd2 Iustin Pop
  @rtype: None
2229 a8083063 Iustin Pop

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

2301 10c2650b Iustin Pop
  @type dest: str
2302 10c2650b Iustin Pop
  @param dest: directory containing the export
2303 a8083063 Iustin Pop

2304 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2305 10c2650b Iustin Pop
  @return: a serializable config file containing the
2306 10c2650b Iustin Pop
      export info
2307 a8083063 Iustin Pop

2308 a8083063 Iustin Pop
  """
2309 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2310 a8083063 Iustin Pop
2311 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2312 a8083063 Iustin Pop
  config.read(cff)
2313 a8083063 Iustin Pop
2314 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2315 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2316 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2317 a8083063 Iustin Pop
2318 c26a6bd2 Iustin Pop
  return config.Dumps()
2319 a8083063 Iustin Pop
2320 a8083063 Iustin Pop
2321 a8083063 Iustin Pop
def ListExports():
2322 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2323 098c0958 Michael Hanselmann

2324 10c2650b Iustin Pop
  @rtype: list
2325 10c2650b Iustin Pop
  @return: list of the exports
2326 10c2650b Iustin Pop

2327 a8083063 Iustin Pop
  """
2328 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
2329 b5b8309d Guido Trotter
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2330 a8083063 Iustin Pop
  else:
2331 afdc3985 Iustin Pop
    _Fail("No exports directory")
2332 a8083063 Iustin Pop
2333 a8083063 Iustin Pop
2334 a8083063 Iustin Pop
def RemoveExport(export):
2335 a8083063 Iustin Pop
  """Remove an existing export from the node.
2336 a8083063 Iustin Pop

2337 10c2650b Iustin Pop
  @type export: str
2338 10c2650b Iustin Pop
  @param export: the name of the export to remove
2339 c26a6bd2 Iustin Pop
  @rtype: None
2340 a8083063 Iustin Pop

2341 098c0958 Michael Hanselmann
  """
2342 c4feafe8 Iustin Pop
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2343 a8083063 Iustin Pop
2344 35fbcd11 Iustin Pop
  try:
2345 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2346 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2347 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2348 a8083063 Iustin Pop
2349 a8083063 Iustin Pop
2350 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2351 f3e513ad Iustin Pop
  """Rename a list of block devices.
2352 f3e513ad Iustin Pop

2353 10c2650b Iustin Pop
  @type devlist: list of tuples
2354 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2355 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2356 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2357 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2358 10c2650b Iustin Pop
      rename it to
2359 10c2650b Iustin Pop
  @rtype: boolean
2360 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2361 f3e513ad Iustin Pop

2362 f3e513ad Iustin Pop
  """
2363 6b5e3f70 Iustin Pop
  msgs = []
2364 f3e513ad Iustin Pop
  result = True
2365 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2366 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2367 f3e513ad Iustin Pop
    if dev is None:
2368 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2369 f3e513ad Iustin Pop
      result = False
2370 f3e513ad Iustin Pop
      continue
2371 f3e513ad Iustin Pop
    try:
2372 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2373 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2374 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2375 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2376 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2377 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2378 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2379 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2380 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2381 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2382 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2383 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2384 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2385 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2386 f3e513ad Iustin Pop
      result = False
2387 afdc3985 Iustin Pop
  if not result:
2388 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2389 f3e513ad Iustin Pop
2390 f3e513ad Iustin Pop
2391 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2392 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2393 778b75bb Manuel Franceschini

2394 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2395 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2396 778b75bb Manuel Franceschini
  directory are allowed.
2397 778b75bb Manuel Franceschini

2398 b1206984 Iustin Pop
  @type file_storage_dir: str
2399 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2400 d61cbe76 Iustin Pop

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

2403 778b75bb Manuel Franceschini
  """
2404 cb7c0198 Iustin Pop
  if not constants.ENABLE_FILE_STORAGE:
2405 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2406 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2407 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2408 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2409 56569f4e Michael Hanselmann
  if (os.path.commonprefix([file_storage_dir, base_file_storage_dir]) !=
2410 778b75bb Manuel Franceschini
      base_file_storage_dir):
2411 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2412 b2b8bcce Iustin Pop
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2413 778b75bb Manuel Franceschini
  return file_storage_dir
2414 778b75bb Manuel Franceschini
2415 778b75bb Manuel Franceschini
2416 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2417 778b75bb Manuel Franceschini
  """Create file storage directory.
2418 778b75bb Manuel Franceschini

2419 b1206984 Iustin Pop
  @type file_storage_dir: str
2420 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2421 778b75bb Manuel Franceschini

2422 b1206984 Iustin Pop
  @rtype: tuple
2423 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2424 b1206984 Iustin Pop
      creation was successful or not
2425 778b75bb Manuel Franceschini

2426 778b75bb Manuel Franceschini
  """
2427 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2428 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2429 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2430 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2431 b2b8bcce Iustin Pop
            file_storage_dir)
2432 778b75bb Manuel Franceschini
  else:
2433 b2b8bcce Iustin Pop
    try:
2434 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2435 b2b8bcce Iustin Pop
    except OSError, err:
2436 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2437 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2438 778b75bb Manuel Franceschini
2439 778b75bb Manuel Franceschini
2440 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2441 778b75bb Manuel Franceschini
  """Remove file storage directory.
2442 778b75bb Manuel Franceschini

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

2445 10c2650b Iustin Pop
  @type file_storage_dir: str
2446 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2447 10c2650b Iustin Pop
  @rtype: tuple (success,)
2448 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2449 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2450 778b75bb Manuel Franceschini

2451 778b75bb Manuel Franceschini
  """
2452 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2453 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2454 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2455 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2456 b2b8bcce Iustin Pop
            file_storage_dir)
2457 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2458 b2b8bcce Iustin Pop
    try:
2459 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2460 b2b8bcce Iustin Pop
    except OSError, err:
2461 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2462 b2b8bcce Iustin Pop
            file_storage_dir, err)
2463 b2b8bcce Iustin Pop
2464 778b75bb Manuel Franceschini
2465 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2466 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2467 778b75bb Manuel Franceschini

2468 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2469 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2470 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2471 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2472 10c2650b Iustin Pop
  @rtype: tuple (success,)
2473 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2474 10c2650b Iustin Pop
      whether the operation was successful
2475 778b75bb Manuel Franceschini

2476 778b75bb Manuel Franceschini
  """
2477 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2478 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2479 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2480 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2481 b2b8bcce Iustin Pop
      try:
2482 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2483 b2b8bcce Iustin Pop
      except OSError, err:
2484 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2485 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2486 778b75bb Manuel Franceschini
    else:
2487 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2488 b2b8bcce Iustin Pop
            old_file_storage_dir)
2489 b2b8bcce Iustin Pop
  else:
2490 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2491 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2492 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2493 778b75bb Manuel Franceschini
2494 778b75bb Manuel Franceschini
2495 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2496 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2497 ca52cdeb Michael Hanselmann

2498 10c2650b Iustin Pop
  @type file_name: str
2499 10c2650b Iustin Pop
  @param file_name: the file name we should check
2500 c8457ce7 Iustin Pop
  @rtype: None
2501 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2502 10c2650b Iustin Pop

2503 ca52cdeb Michael Hanselmann
  """
2504 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2505 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2506 dc31eae3 Michael Hanselmann
2507 dc31eae3 Michael Hanselmann
  if not result:
2508 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2509 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2510 dc31eae3 Michael Hanselmann
2511 dc31eae3 Michael Hanselmann
2512 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2513 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2514 dc31eae3 Michael Hanselmann

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

2518 10c2650b Iustin Pop
  @type file_name: str
2519 10c2650b Iustin Pop
  @param file_name: the job file name
2520 10c2650b Iustin Pop
  @type content: str
2521 10c2650b Iustin Pop
  @param content: the new job contents
2522 10c2650b Iustin Pop
  @rtype: boolean
2523 10c2650b Iustin Pop
  @return: the success of the operation
2524 10c2650b Iustin Pop

2525 dc31eae3 Michael Hanselmann
  """
2526 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2527 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2528 ca52cdeb Michael Hanselmann
2529 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2530 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2531 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2532 ca52cdeb Michael Hanselmann
2533 ca52cdeb Michael Hanselmann
2534 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2535 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2536 af5ebcb1 Michael Hanselmann

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

2539 10c2650b Iustin Pop
  @type old: str
2540 10c2650b Iustin Pop
  @param old: the old (actual) file name
2541 10c2650b Iustin Pop
  @type new: str
2542 10c2650b Iustin Pop
  @param new: the desired file name
2543 c8457ce7 Iustin Pop
  @rtype: tuple
2544 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2545 10c2650b Iustin Pop

2546 af5ebcb1 Michael Hanselmann
  """
2547 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2548 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2549 af5ebcb1 Michael Hanselmann
2550 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2551 af5ebcb1 Michael Hanselmann
2552 af5ebcb1 Michael Hanselmann
2553 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2554 d61cbe76 Iustin Pop
  """Closes the given block devices.
2555 d61cbe76 Iustin Pop

2556 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2557 10c2650b Iustin Pop
  DRBD).
2558 10c2650b Iustin Pop

2559 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2560 b2e7666a Iustin Pop
      of this instance will be removed
2561 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2562 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2563 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2564 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2565 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2566 10c2650b Iustin Pop
      which will contain the error details in case we
2567 10c2650b Iustin Pop
      failed
2568 d61cbe76 Iustin Pop

2569 d61cbe76 Iustin Pop
  """
2570 d61cbe76 Iustin Pop
  bdevs = []
2571 d61cbe76 Iustin Pop
  for cf in disks:
2572 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2573 d61cbe76 Iustin Pop
    if rd is None:
2574 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2575 d61cbe76 Iustin Pop
    bdevs.append(rd)
2576 d61cbe76 Iustin Pop
2577 d61cbe76 Iustin Pop
  msg = []
2578 d61cbe76 Iustin Pop
  for rd in bdevs:
2579 d61cbe76 Iustin Pop
    try:
2580 d61cbe76 Iustin Pop
      rd.Close()
2581 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2582 d61cbe76 Iustin Pop
      msg.append(str(err))
2583 d61cbe76 Iustin Pop
  if msg:
2584 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2585 d61cbe76 Iustin Pop
  else:
2586 b2e7666a Iustin Pop
    if instance_name:
2587 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2588 d61cbe76 Iustin Pop
2589 d61cbe76 Iustin Pop
2590 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2591 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2592 6217e295 Iustin Pop

2593 6217e295 Iustin Pop
  @type hvname: string
2594 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2595 6217e295 Iustin Pop
  @type hvparams: dict
2596 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2597 c26a6bd2 Iustin Pop
  @rtype: None
2598 6217e295 Iustin Pop

2599 6217e295 Iustin Pop
  """
2600 6217e295 Iustin Pop
  try:
2601 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2602 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2603 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2604 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2605 6217e295 Iustin Pop
2606 6217e295 Iustin Pop
2607 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
2608 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
2609 acd9ff9e Iustin Pop

2610 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
2611 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
2612 acd9ff9e Iustin Pop
  @type parameters: list
2613 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
2614 acd9ff9e Iustin Pop

2615 acd9ff9e Iustin Pop
  """
2616 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
2617 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
2618 acd9ff9e Iustin Pop
  if delta:
2619 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
2620 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2621 acd9ff9e Iustin Pop
2622 acd9ff9e Iustin Pop
2623 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
2624 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
2625 acd9ff9e Iustin Pop

2626 acd9ff9e Iustin Pop
  @type required: boolean
2627 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
2628 acd9ff9e Iustin Pop
      failure or not
2629 acd9ff9e Iustin Pop
  @type osname: string
2630 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
2631 acd9ff9e Iustin Pop
  @type checks: list
2632 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
2633 acd9ff9e Iustin Pop
  @type osparams: dict
2634 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
2635 acd9ff9e Iustin Pop
  @rtype: boolean
2636 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
2637 acd9ff9e Iustin Pop
      found and L{required} was false
2638 acd9ff9e Iustin Pop

2639 acd9ff9e Iustin Pop
  """
2640 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2641 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
2642 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2643 acd9ff9e Iustin Pop
2644 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
2645 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
2646 acd9ff9e Iustin Pop
2647 acd9ff9e Iustin Pop
  if not status:
2648 acd9ff9e Iustin Pop
    if required:
2649 acd9ff9e Iustin Pop
      _Fail(tbv)
2650 acd9ff9e Iustin Pop
    else:
2651 acd9ff9e Iustin Pop
      return False
2652 acd9ff9e Iustin Pop
2653 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
2654 72db3fd7 Iustin Pop
    return True
2655 72db3fd7 Iustin Pop
2656 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
2657 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
2658 acd9ff9e Iustin Pop
2659 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
2660 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2661 acd9ff9e Iustin Pop
                        cwd=tbv.path)
2662 acd9ff9e Iustin Pop
  if result.failed:
2663 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
2664 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
2665 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
2666 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
2667 acd9ff9e Iustin Pop
2668 acd9ff9e Iustin Pop
  return True
2669 acd9ff9e Iustin Pop
2670 acd9ff9e Iustin Pop
2671 56aa9fd5 Iustin Pop
def DemoteFromMC():
2672 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2673 56aa9fd5 Iustin Pop

2674 56aa9fd5 Iustin Pop
  """
2675 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2676 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2677 56aa9fd5 Iustin Pop
  if master == myself:
2678 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2679 f154a7a3 Michael Hanselmann
2680 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2681 f154a7a3 Michael Hanselmann
  if not result.failed:
2682 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2683 f154a7a3 Michael Hanselmann
2684 56aa9fd5 Iustin Pop
  try:
2685 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2686 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2687 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2688 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2689 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2690 f154a7a3 Michael Hanselmann
2691 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2692 56aa9fd5 Iustin Pop
2693 56aa9fd5 Iustin Pop
2694 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
2695 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
2696 f942a838 Michael Hanselmann

2697 f942a838 Michael Hanselmann
  """
2698 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
2699 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2700 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2701 f942a838 Michael Hanselmann
2702 f942a838 Michael Hanselmann
2703 f942a838 Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2704 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
2705 f942a838 Michael Hanselmann

2706 f942a838 Michael Hanselmann
  @type validity: int
2707 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
2708 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
2709 f942a838 Michael Hanselmann
  @return: Certificate name and public part
2710 f942a838 Michael Hanselmann

2711 f942a838 Michael Hanselmann
  """
2712 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
2713 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2714 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2715 f942a838 Michael Hanselmann
2716 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2717 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
2718 f942a838 Michael Hanselmann
  try:
2719 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
2720 f942a838 Michael Hanselmann
    assert len(name) > 5
2721 f942a838 Michael Hanselmann
2722 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2723 f942a838 Michael Hanselmann
2724 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2725 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2726 f942a838 Michael Hanselmann
2727 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
2728 f942a838 Michael Hanselmann
    return (name, cert_pem)
2729 f942a838 Michael Hanselmann
  except Exception:
2730 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
2731 f942a838 Michael Hanselmann
    raise
2732 f942a838 Michael Hanselmann
2733 f942a838 Michael Hanselmann
2734 f942a838 Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2735 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
2736 f942a838 Michael Hanselmann

2737 f942a838 Michael Hanselmann
  @type name: string
2738 f942a838 Michael Hanselmann
  @param name: Certificate name
2739 f942a838 Michael Hanselmann

2740 f942a838 Michael Hanselmann
  """
2741 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2742 f942a838 Michael Hanselmann
2743 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
2744 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
2745 f942a838 Michael Hanselmann
2746 f942a838 Michael Hanselmann
  try:
2747 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
2748 f942a838 Michael Hanselmann
  except EnvironmentError, err:
2749 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
2750 f942a838 Michael Hanselmann
          cert_dir, err)
2751 f942a838 Michael Hanselmann
2752 f942a838 Michael Hanselmann
2753 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2754 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
2755 1651d116 Michael Hanselmann

2756 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
2757 1651d116 Michael Hanselmann
  @param instance: The instance object
2758 1651d116 Michael Hanselmann
  @param mode: Import/export mode
2759 1651d116 Michael Hanselmann
  @param ieio: Input/output type
2760 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
2761 1651d116 Michael Hanselmann

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

2867 1651d116 Michael Hanselmann
  """
2868 1651d116 Michael Hanselmann
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
2869 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
2870 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
2871 1651d116 Michael Hanselmann
2872 1651d116 Michael Hanselmann
2873 eb630f50 Michael Hanselmann
def StartImportExportDaemon(mode, opts, host, port, instance, ieio, ieioargs):
2874 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
2875 1651d116 Michael Hanselmann

2876 1651d116 Michael Hanselmann
  @param mode: Import/output mode
2877 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
2878 eb630f50 Michael Hanselmann
  @param opts: Daemon options
2879 1651d116 Michael Hanselmann
  @type host: string
2880 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
2881 1651d116 Michael Hanselmann
  @type port: int
2882 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
2883 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
2884 1651d116 Michael Hanselmann
  @param instance: Instance object
2885 1651d116 Michael Hanselmann
  @param ieio: Input/output type
2886 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
2887 1651d116 Michael Hanselmann

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

2991 1651d116 Michael Hanselmann
  @type names: sequence
2992 1651d116 Michael Hanselmann
  @param names: List of names
2993 1651d116 Michael Hanselmann
  @rtype: List of dicts
2994 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
2995 1651d116 Michael Hanselmann
           status couldn't be read
2996 1651d116 Michael Hanselmann

2997 1651d116 Michael Hanselmann
  """
2998 1651d116 Michael Hanselmann
  result = []
2999 1651d116 Michael Hanselmann
3000 1651d116 Michael Hanselmann
  for name in names:
3001 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3002 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3003 1651d116 Michael Hanselmann
3004 1651d116 Michael Hanselmann
    try:
3005 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3006 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3007 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3008 1651d116 Michael Hanselmann
        raise
3009 1651d116 Michael Hanselmann
      data = None
3010 1651d116 Michael Hanselmann
3011 1651d116 Michael Hanselmann
    if not data:
3012 1651d116 Michael Hanselmann
      result.append(None)
3013 1651d116 Michael Hanselmann
      continue
3014 1651d116 Michael Hanselmann
3015 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3016 1651d116 Michael Hanselmann
3017 1651d116 Michael Hanselmann
  return result
3018 1651d116 Michael Hanselmann
3019 1651d116 Michael Hanselmann
3020 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3021 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3022 f81c4737 Michael Hanselmann

3023 f81c4737 Michael Hanselmann
  """
3024 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3025 f81c4737 Michael Hanselmann
3026 f81c4737 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3027 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3028 f81c4737 Michael Hanselmann
3029 f81c4737 Michael Hanselmann
  if pid:
3030 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3031 f81c4737 Michael Hanselmann
                 name, pid)
3032 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3033 f81c4737 Michael Hanselmann
3034 f81c4737 Michael Hanselmann
3035 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3036 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3037 1651d116 Michael Hanselmann

3038 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3039 1651d116 Michael Hanselmann
  whole status directory is removed.
3040 1651d116 Michael Hanselmann

3041 1651d116 Michael Hanselmann
  """
3042 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3043 1651d116 Michael Hanselmann
3044 1651d116 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3045 1651d116 Michael Hanselmann
3046 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3047 1651d116 Michael Hanselmann
3048 1651d116 Michael Hanselmann
  if pid:
3049 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3050 1651d116 Michael Hanselmann
                 name, pid)
3051 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3052 1651d116 Michael Hanselmann
3053 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3054 1651d116 Michael Hanselmann
3055 1651d116 Michael Hanselmann
3056 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3057 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3058 6b93ec9d Iustin Pop

3059 6b93ec9d Iustin Pop
  """
3060 6b93ec9d Iustin Pop
  # set the correct physical ID
3061 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3062 6b93ec9d Iustin Pop
  for cf in disks:
3063 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3064 6b93ec9d Iustin Pop
3065 6b93ec9d Iustin Pop
  bdevs = []
3066 6b93ec9d Iustin Pop
3067 6b93ec9d Iustin Pop
  for cf in disks:
3068 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3069 6b93ec9d Iustin Pop
    if rd is None:
3070 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3071 6b93ec9d Iustin Pop
    bdevs.append(rd)
3072 5a533f8a Iustin Pop
  return bdevs
3073 6b93ec9d Iustin Pop
3074 6b93ec9d Iustin Pop
3075 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3076 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3077 6b93ec9d Iustin Pop

3078 6b93ec9d Iustin Pop
  """
3079 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3080 6b93ec9d Iustin Pop
3081 6b93ec9d Iustin Pop
  # disconnect disks
3082 6b93ec9d Iustin Pop
  for rd in bdevs:
3083 6b93ec9d Iustin Pop
    try:
3084 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3085 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3086 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3087 2cc6781a Iustin Pop
            err, exc=True)
3088 6b93ec9d Iustin Pop
3089 6b93ec9d Iustin Pop
3090 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3091 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3092 6b93ec9d Iustin Pop

3093 6b93ec9d Iustin Pop
  """
3094 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3095 6b93ec9d Iustin Pop
3096 6b93ec9d Iustin Pop
  if multimaster:
3097 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3098 6b93ec9d Iustin Pop
      try:
3099 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3100 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3101 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3102 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3103 6b93ec9d Iustin Pop
  # needed primary mode
3104 6b93ec9d Iustin Pop
  for rd in bdevs:
3105 6b93ec9d Iustin Pop
    try:
3106 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3107 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3108 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3109 3c0cdc83 Michael Hanselmann
3110 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3111 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3112 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3113 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3114 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3115 3c0cdc83 Michael Hanselmann
3116 3c0cdc83 Michael Hanselmann
  def _Attach():
3117 6b93ec9d Iustin Pop
    all_connected = True
3118 3c0cdc83 Michael Hanselmann
3119 6b93ec9d Iustin Pop
    for rd in bdevs:
3120 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3121 3c0cdc83 Michael Hanselmann
3122 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3123 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3124 3c0cdc83 Michael Hanselmann
3125 6b93ec9d Iustin Pop
      if stats.is_standalone:
3126 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3127 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3128 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3129 6b93ec9d Iustin Pop
        try:
3130 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3131 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3132 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3133 3c0cdc83 Michael Hanselmann
3134 3c0cdc83 Michael Hanselmann
    if not all_connected:
3135 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3136 3c0cdc83 Michael Hanselmann
3137 3c0cdc83 Michael Hanselmann
  try:
3138 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3139 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3140 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3141 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3142 3c0cdc83 Michael Hanselmann
3143 6b93ec9d Iustin Pop
  if multimaster:
3144 6b93ec9d Iustin Pop
    # change to primary mode
3145 6b93ec9d Iustin Pop
    for rd in bdevs:
3146 d3da87b8 Iustin Pop
      try:
3147 d3da87b8 Iustin Pop
        rd.Open()
3148 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3149 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3150 6b93ec9d Iustin Pop
3151 6b93ec9d Iustin Pop
3152 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3153 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3154 6b93ec9d Iustin Pop

3155 6b93ec9d Iustin Pop
  """
3156 db8667b7 Iustin Pop
  def _helper(rd):
3157 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3158 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3159 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3160 db8667b7 Iustin Pop
    return stats
3161 db8667b7 Iustin Pop
3162 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3163 6b93ec9d Iustin Pop
3164 6b93ec9d Iustin Pop
  min_resync = 100
3165 6b93ec9d Iustin Pop
  alldone = True
3166 6b93ec9d Iustin Pop
  for rd in bdevs:
3167 db8667b7 Iustin Pop
    try:
3168 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3169 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3170 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3171 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3172 db8667b7 Iustin Pop
      # last check
3173 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3174 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3175 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3176 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3177 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3178 afdc3985 Iustin Pop
3179 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3180 6b93ec9d Iustin Pop
3181 6b93ec9d Iustin Pop
3182 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3183 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3184 c46b9782 Luca Bigliardi

3185 c46b9782 Luca Bigliardi
  """
3186 c46b9782 Luca Bigliardi
  try:
3187 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3188 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3189 c46b9782 Luca Bigliardi
    _Fail(str(err))
3190 c46b9782 Luca Bigliardi
3191 c46b9782 Luca Bigliardi
3192 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3193 f5118ade Iustin Pop
  """Hard-powercycle the node.
3194 f5118ade Iustin Pop

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

3198 f5118ade Iustin Pop
  """
3199 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3200 f5118ade Iustin Pop
  try:
3201 f5118ade Iustin Pop
    pid = os.fork()
3202 29921401 Iustin Pop
  except OSError:
3203 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3204 f5118ade Iustin Pop
    pid = 0
3205 f5118ade Iustin Pop
  if pid > 0:
3206 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3207 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3208 1af6ac0f Luca Bigliardi
  try:
3209 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3210 20601361 Luca Bigliardi
  except Exception: # pylint: disable-msg=W0703
3211 1af6ac0f Luca Bigliardi
    pass
3212 f5118ade Iustin Pop
  time.sleep(5)
3213 f5118ade Iustin Pop
  hyper.PowercycleNode()
3214 f5118ade Iustin Pop
3215 f5118ade Iustin Pop
3216 a8083063 Iustin Pop
class HooksRunner(object):
3217 a8083063 Iustin Pop
  """Hook runner.
3218 a8083063 Iustin Pop

3219 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3220 10c2650b Iustin Pop
  on the master side.
3221 a8083063 Iustin Pop

3222 a8083063 Iustin Pop
  """
3223 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3224 a8083063 Iustin Pop
    """Constructor for hooks runner.
3225 a8083063 Iustin Pop

3226 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
3227 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
3228 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3229 a8083063 Iustin Pop

3230 a8083063 Iustin Pop
    """
3231 a8083063 Iustin Pop
    if hooks_base_dir is None:
3232 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
3233 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3234 fe267188 Iustin Pop
    # constant
3235 fe267188 Iustin Pop
    self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
3236 a8083063 Iustin Pop
3237 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3238 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3239 a8083063 Iustin Pop

3240 10c2650b Iustin Pop
    @type hpath: str
3241 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3242 10c2650b Iustin Pop
        holds the scripts
3243 10c2650b Iustin Pop
    @type phase: str
3244 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3245 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3246 10c2650b Iustin Pop
    @type env: dict
3247 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3248 10c2650b Iustin Pop
    @rtype: list
3249 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3250 10c2650b Iustin Pop
      - script path
3251 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3252 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3253 10c2650b Iustin Pop
      - output of the script
3254 10c2650b Iustin Pop

3255 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3256 10c2650b Iustin Pop
        parameters
3257 a8083063 Iustin Pop

3258 a8083063 Iustin Pop
    """
3259 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3260 a8083063 Iustin Pop
      suffix = "pre"
3261 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3262 a8083063 Iustin Pop
      suffix = "post"
3263 a8083063 Iustin Pop
    else:
3264 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3265 3fb4f740 Iustin Pop
3266 a8083063 Iustin Pop
3267 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3268 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3269 6bb65e3a Guido Trotter
3270 6bb65e3a Guido Trotter
    results = []
3271 a9b7e346 Iustin Pop
3272 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3273 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3274 a9b7e346 Iustin Pop
      # warning at every operation
3275 a9b7e346 Iustin Pop
      return results
3276 a9b7e346 Iustin Pop
3277 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3278 a9b7e346 Iustin Pop
3279 6bb65e3a Guido Trotter
    for (relname, relstatus, runresult)  in runparts_results:
3280 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3281 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3282 a8083063 Iustin Pop
        output = ""
3283 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3284 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3285 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3286 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3287 6bb65e3a Guido Trotter
        if runresult.failed:
3288 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3289 a8083063 Iustin Pop
        else:
3290 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3291 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3292 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3293 6bb65e3a Guido Trotter
3294 6bb65e3a Guido Trotter
    return results
3295 3f78eef2 Iustin Pop
3296 3f78eef2 Iustin Pop
3297 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3298 8d528b7c Iustin Pop
  """IAllocator runner.
3299 8d528b7c Iustin Pop

3300 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3301 8d528b7c Iustin Pop
  the master side.
3302 8d528b7c Iustin Pop

3303 8d528b7c Iustin Pop
  """
3304 7e950d31 Iustin Pop
  @staticmethod
3305 7e950d31 Iustin Pop
  def Run(name, idata):
3306 8d528b7c Iustin Pop
    """Run an iallocator script.
3307 8d528b7c Iustin Pop

3308 10c2650b Iustin Pop
    @type name: str
3309 10c2650b Iustin Pop
    @param name: the iallocator script name
3310 10c2650b Iustin Pop
    @type idata: str
3311 10c2650b Iustin Pop
    @param idata: the allocator input data
3312 10c2650b Iustin Pop

3313 10c2650b Iustin Pop
    @rtype: tuple
3314 87f5c298 Iustin Pop
    @return: two element tuple of:
3315 87f5c298 Iustin Pop
       - status
3316 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3317 8d528b7c Iustin Pop

3318 8d528b7c Iustin Pop
    """
3319 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3320 8d528b7c Iustin Pop
                                  os.path.isfile)
3321 8d528b7c Iustin Pop
    if alloc_script is None:
3322 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3323 8d528b7c Iustin Pop
3324 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3325 8d528b7c Iustin Pop
    try:
3326 8d528b7c Iustin Pop
      os.write(fd, idata)
3327 8d528b7c Iustin Pop
      os.close(fd)
3328 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3329 8d528b7c Iustin Pop
      if result.failed:
3330 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3331 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3332 8d528b7c Iustin Pop
    finally:
3333 8d528b7c Iustin Pop
      os.unlink(fin_name)
3334 8d528b7c Iustin Pop
3335 c26a6bd2 Iustin Pop
    return result.stdout
3336 8d528b7c Iustin Pop
3337 8d528b7c Iustin Pop
3338 3f78eef2 Iustin Pop
class DevCacheManager(object):
3339 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3340 3f78eef2 Iustin Pop

3341 3f78eef2 Iustin Pop
  """
3342 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3343 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3344 3f78eef2 Iustin Pop
3345 3f78eef2 Iustin Pop
  @classmethod
3346 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3347 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3348 3f78eef2 Iustin Pop

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

3352 10c2650b Iustin Pop
    @type dev_path: str
3353 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3354 10c2650b Iustin Pop
    @rtype: str
3355 10c2650b Iustin Pop
    @return: the converted path name
3356 3f78eef2 Iustin Pop

3357 3f78eef2 Iustin Pop
    """
3358 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3359 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3360 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3361 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3362 3f78eef2 Iustin Pop
    return fpath
3363 3f78eef2 Iustin Pop
3364 3f78eef2 Iustin Pop
  @classmethod
3365 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3366 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3367 3f78eef2 Iustin Pop

3368 10c2650b Iustin Pop
    @type dev_path: str
3369 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3370 10c2650b Iustin Pop
    @type owner: str
3371 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3372 10c2650b Iustin Pop
    @type on_primary: bool
3373 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3374 10c2650b Iustin Pop
        node nor not
3375 10c2650b Iustin Pop
    @type iv_name: str
3376 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3377 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3378 10c2650b Iustin Pop

3379 10c2650b Iustin Pop
    @rtype: None
3380 10c2650b Iustin Pop

3381 3f78eef2 Iustin Pop
    """
3382 cf5a8306 Iustin Pop
    if dev_path is None:
3383 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3384 cf5a8306 Iustin Pop
      return
3385 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3386 3f78eef2 Iustin Pop
    if on_primary:
3387 3f78eef2 Iustin Pop
      state = "primary"
3388 3f78eef2 Iustin Pop
    else:
3389 3f78eef2 Iustin Pop
      state = "secondary"
3390 3f78eef2 Iustin Pop
    if iv_name is None:
3391 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3392 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3393 3f78eef2 Iustin Pop
    try:
3394 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3395 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3396 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3397 3f78eef2 Iustin Pop
3398 3f78eef2 Iustin Pop
  @classmethod
3399 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3400 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3401 3f78eef2 Iustin Pop

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

3405 10c2650b Iustin Pop
    @type dev_path: str
3406 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3407 10c2650b Iustin Pop

3408 10c2650b Iustin Pop
    @rtype: None
3409 10c2650b Iustin Pop

3410 3f78eef2 Iustin Pop
    """
3411 cf5a8306 Iustin Pop
    if dev_path is None:
3412 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3413 cf5a8306 Iustin Pop
      return
3414 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3415 3f78eef2 Iustin Pop
    try:
3416 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3417 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3418 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)