Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ c79198a0

History | View | Annotate | Download (111.1 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 397693d3 Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 360b0dc2 Iustin Pop
"""Functions used by the node daemon
23 360b0dc2 Iustin Pop

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

29 360b0dc2 Iustin Pop
"""
30 a8083063 Iustin Pop
31 b459a848 Andrea Spadaccini
# pylint: disable=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 0fa481f5 Andrea Spadaccini
from ganeti import mcpu
64 a8083063 Iustin Pop
65 a8083063 Iustin Pop
66 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
67 714ea7ca Iustin Pop
_ALLOWED_CLEAN_DIRS = frozenset([
68 714ea7ca Iustin Pop
  constants.DATA_DIR,
69 714ea7ca Iustin Pop
  constants.JOB_QUEUE_ARCHIVE_DIR,
70 714ea7ca Iustin Pop
  constants.QUEUE_DIR,
71 f942a838 Michael Hanselmann
  constants.CRYPTO_KEYS_DIR,
72 714ea7ca Iustin Pop
  ])
73 f942a838 Michael Hanselmann
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
74 f942a838 Michael Hanselmann
_X509_KEY_FILE = "key"
75 f942a838 Michael Hanselmann
_X509_CERT_FILE = "cert"
76 1651d116 Michael Hanselmann
_IES_STATUS_FILE = "status"
77 1651d116 Michael Hanselmann
_IES_PID_FILE = "pid"
78 1651d116 Michael Hanselmann
_IES_CA_FILE = "ca"
79 13998ef2 Michael Hanselmann
80 0b5303da Iustin Pop
#: Valid LVS output line regex
81 84d7e26b Dmitry Chernyak
_LVSLINE_REGEX = re.compile("^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
82 0b5303da Iustin Pop
83 13998ef2 Michael Hanselmann
84 2cc6781a Iustin Pop
class RPCFail(Exception):
85 2cc6781a Iustin Pop
  """Class denoting RPC failure.
86 2cc6781a Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

220 c8457ce7 Iustin Pop
  @rtype: tuple
221 c8457ce7 Iustin Pop
  @return: True, None
222 24fc781f Michael Hanselmann

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

231 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
232 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
233 bd1e4562 Iustin Pop

234 bd1e4562 Iustin Pop
  @rtype: tuple
235 909b3a0e Andrea Spadaccini
  @return: master_netdev, master_ip, master_name, primary_ip_family,
236 909b3a0e Andrea Spadaccini
    master_netmask
237 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
238 b1b6ea87 Iustin Pop

239 b1b6ea87 Iustin Pop
  """
240 b1b6ea87 Iustin Pop
  try:
241 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
242 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
243 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
244 5a8648eb Andrea Spadaccini
    master_netmask = cfg.GetMasterNetmask()
245 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
246 d8e0caa6 Manuel Franceschini
    primary_ip_family = cfg.GetPrimaryIPFamily()
247 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
248 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
249 909b3a0e Andrea Spadaccini
  return (master_netdev, master_ip, master_node, primary_ip_family,
250 909b3a0e Andrea Spadaccini
      master_netmask)
251 b1b6ea87 Iustin Pop
252 b1b6ea87 Iustin Pop
253 0fa481f5 Andrea Spadaccini
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
254 0fa481f5 Andrea Spadaccini
  """Decorator that runs hooks before and after the decorated function.
255 0fa481f5 Andrea Spadaccini

256 0fa481f5 Andrea Spadaccini
  @type hook_opcode: string
257 0fa481f5 Andrea Spadaccini
  @param hook_opcode: opcode of the hook
258 0fa481f5 Andrea Spadaccini
  @type hooks_path: string
259 0fa481f5 Andrea Spadaccini
  @param hooks_path: path of the hooks
260 0fa481f5 Andrea Spadaccini
  @type env_builder_fn: function
261 0fa481f5 Andrea Spadaccini
  @param env_builder_fn: function that returns a dictionary containing the
262 0fa481f5 Andrea Spadaccini
    environment variables for the hooks.
263 0fa481f5 Andrea Spadaccini
  @raise RPCFail: in case of pre-hook failure
264 0fa481f5 Andrea Spadaccini

265 0fa481f5 Andrea Spadaccini
  """
266 0fa481f5 Andrea Spadaccini
  def decorator(fn):
267 0fa481f5 Andrea Spadaccini
    def wrapper(*args, **kwargs):
268 0fa481f5 Andrea Spadaccini
      _, myself = ssconf.GetMasterAndMyself()
269 0fa481f5 Andrea Spadaccini
      nodes = ([myself], [myself])  # these hooks run locally
270 0fa481f5 Andrea Spadaccini
271 0fa481f5 Andrea Spadaccini
      cfg = _GetConfig()
272 0fa481f5 Andrea Spadaccini
      hr = HooksRunner()
273 0fa481f5 Andrea Spadaccini
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
274 0fa481f5 Andrea Spadaccini
                            None, env_builder_fn, logging.warning,
275 0fa481f5 Andrea Spadaccini
                            cfg.GetClusterName(), cfg.GetMasterNode())
276 0fa481f5 Andrea Spadaccini
277 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
278 0fa481f5 Andrea Spadaccini
      result = fn(*args, **kwargs)
279 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_POST)
280 0fa481f5 Andrea Spadaccini
281 0fa481f5 Andrea Spadaccini
      return result
282 0fa481f5 Andrea Spadaccini
    return wrapper
283 0fa481f5 Andrea Spadaccini
  return decorator
284 0fa481f5 Andrea Spadaccini
285 0fa481f5 Andrea Spadaccini
286 3a3e4f1e Andrea Spadaccini
def _BuildMasterIpEnv():
287 2d88fdd3 Andrea Spadaccini
  """Builds environment variables for master IP hooks.
288 2d88fdd3 Andrea Spadaccini

289 2d88fdd3 Andrea Spadaccini
  """
290 3a3e4f1e Andrea Spadaccini
  master_netdev, master_ip, _, family, master_netmask = GetMasterInfo()
291 3a3e4f1e Andrea Spadaccini
  version = str(netutils.IPAddress.GetVersionFromAddressFamily(family))
292 2d88fdd3 Andrea Spadaccini
  env = {
293 3a3e4f1e Andrea Spadaccini
    "MASTER_NETDEV": master_netdev,
294 3a3e4f1e Andrea Spadaccini
    "MASTER_IP": master_ip,
295 3a3e4f1e Andrea Spadaccini
    "MASTER_NETMASK": master_netmask,
296 3a3e4f1e Andrea Spadaccini
    "CLUSTER_IP_VERSION": version,
297 2d88fdd3 Andrea Spadaccini
  }
298 2d88fdd3 Andrea Spadaccini
299 2d88fdd3 Andrea Spadaccini
  return env
300 2d88fdd3 Andrea Spadaccini
301 2d88fdd3 Andrea Spadaccini
302 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
303 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
304 c79198a0 Andrea Spadaccini
def ActivateMasterIp(master_params):
305 fb460cf7 Andrea Spadaccini
  """Activate the IP address of the master daemon.
306 fb460cf7 Andrea Spadaccini

307 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
308 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
309 8da2bd43 Andrea Spadaccini

310 fb460cf7 Andrea Spadaccini
  """
311 fb460cf7 Andrea Spadaccini
  err_msg = None
312 c79198a0 Andrea Spadaccini
  if netutils.TcpPing(master_params.ip, constants.DEFAULT_NODED_PORT):
313 c79198a0 Andrea Spadaccini
    if netutils.IPAddress.Own(master_params.ip):
314 fb460cf7 Andrea Spadaccini
      # we already have the ip:
315 fb460cf7 Andrea Spadaccini
      logging.debug("Master IP already configured, doing nothing")
316 fb460cf7 Andrea Spadaccini
    else:
317 fb460cf7 Andrea Spadaccini
      err_msg = "Someone else has the master ip, not activating"
318 fb460cf7 Andrea Spadaccini
      logging.error(err_msg)
319 fb460cf7 Andrea Spadaccini
  else:
320 c79198a0 Andrea Spadaccini
    ipcls = netutils.IPAddress.GetClassFromIpFamily(master_params.ip_family)
321 fb460cf7 Andrea Spadaccini
322 fb460cf7 Andrea Spadaccini
    result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
323 c79198a0 Andrea Spadaccini
                           "%s/%s" % (master_params.ip, master_params.netmask),
324 c79198a0 Andrea Spadaccini
                           "dev", master_params.netdev, "label",
325 c79198a0 Andrea Spadaccini
                           "%s:0" % master_params.netdev])
326 fb460cf7 Andrea Spadaccini
    if result.failed:
327 fb460cf7 Andrea Spadaccini
      err_msg = "Can't activate master IP: %s" % result.output
328 fb460cf7 Andrea Spadaccini
      logging.error(err_msg)
329 fb460cf7 Andrea Spadaccini
330 9888b9e6 Andrea Spadaccini
    else:
331 9888b9e6 Andrea Spadaccini
      # we ignore the exit code of the following cmds
332 9888b9e6 Andrea Spadaccini
      if ipcls == netutils.IP4Address:
333 c79198a0 Andrea Spadaccini
        utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_params.netdev,
334 c79198a0 Andrea Spadaccini
                      "-s", master_params.ip, master_params.ip])
335 9888b9e6 Andrea Spadaccini
      elif ipcls == netutils.IP6Address:
336 9888b9e6 Andrea Spadaccini
        try:
337 c79198a0 Andrea Spadaccini
          utils.RunCmd(["ndisc6", "-q", "-r 3", master_params.ip,
338 c79198a0 Andrea Spadaccini
                        master_params.netdev])
339 9888b9e6 Andrea Spadaccini
        except errors.OpExecError:
340 9888b9e6 Andrea Spadaccini
          # TODO: Better error reporting
341 9888b9e6 Andrea Spadaccini
          logging.warning("Can't execute ndisc6, please install if missing")
342 fb460cf7 Andrea Spadaccini
343 fb460cf7 Andrea Spadaccini
  if err_msg:
344 fb460cf7 Andrea Spadaccini
    _Fail(err_msg)
345 fb460cf7 Andrea Spadaccini
346 fb460cf7 Andrea Spadaccini
347 fb460cf7 Andrea Spadaccini
def StartMasterDaemons(no_voting):
348 a8083063 Iustin Pop
  """Activate local node as master node.
349 a8083063 Iustin Pop

350 fb460cf7 Andrea Spadaccini
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
351 10c2650b Iustin Pop

352 3583908a Guido Trotter
  @type no_voting: boolean
353 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
354 fb460cf7 Andrea Spadaccini
      but still non-interactively
355 10c2650b Iustin Pop
  @rtype: None
356 a8083063 Iustin Pop

357 a8083063 Iustin Pop
  """
358 a8083063 Iustin Pop
359 fb460cf7 Andrea Spadaccini
  if no_voting:
360 fb460cf7 Andrea Spadaccini
    masterd_args = "--no-voting --yes-do-it"
361 fb460cf7 Andrea Spadaccini
  else:
362 fb460cf7 Andrea Spadaccini
    masterd_args = ""
363 f154a7a3 Michael Hanselmann
364 fb460cf7 Andrea Spadaccini
  env = {
365 fb460cf7 Andrea Spadaccini
    "EXTRA_MASTERD_ARGS": masterd_args,
366 fb460cf7 Andrea Spadaccini
    }
367 fb460cf7 Andrea Spadaccini
368 fb460cf7 Andrea Spadaccini
  result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
369 fb460cf7 Andrea Spadaccini
  if result.failed:
370 fb460cf7 Andrea Spadaccini
    msg = "Can't start Ganeti master: %s" % result.output
371 fb460cf7 Andrea Spadaccini
    logging.error(msg)
372 fb460cf7 Andrea Spadaccini
    _Fail(msg)
373 f154a7a3 Michael Hanselmann
374 fb460cf7 Andrea Spadaccini
375 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
376 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
377 c79198a0 Andrea Spadaccini
def DeactivateMasterIp(master_params):
378 fb460cf7 Andrea Spadaccini
  """Deactivate the master IP on this node.
379 a8083063 Iustin Pop

380 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
381 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
382 96e0d5cc Andrea Spadaccini

383 a8083063 Iustin Pop
  """
384 6c00d19a Iustin Pop
  # TODO: log and report back to the caller the error failures; we
385 6c00d19a Iustin Pop
  # need to decide in which case we fail the RPC for this
386 2a52a064 Iustin Pop
387 c4dfb0b6 Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
388 c79198a0 Andrea Spadaccini
                         "%s/%s" % (master_params.ip, master_params.netmask),
389 c79198a0 Andrea Spadaccini
                         "dev", master_params.netdev])
390 a8083063 Iustin Pop
  if result.failed:
391 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
392 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
393 b1b6ea87 Iustin Pop
394 fb460cf7 Andrea Spadaccini
395 fb460cf7 Andrea Spadaccini
def StopMasterDaemons():
396 fb460cf7 Andrea Spadaccini
  """Stop the master daemons on this node.
397 fb460cf7 Andrea Spadaccini

398 fb460cf7 Andrea Spadaccini
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
399 fb460cf7 Andrea Spadaccini

400 fb460cf7 Andrea Spadaccini
  @rtype: None
401 fb460cf7 Andrea Spadaccini

402 fb460cf7 Andrea Spadaccini
  """
403 fb460cf7 Andrea Spadaccini
  # TODO: log and report back to the caller the error failures; we
404 fb460cf7 Andrea Spadaccini
  # need to decide in which case we fail the RPC for this
405 fb460cf7 Andrea Spadaccini
406 fb460cf7 Andrea Spadaccini
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
407 fb460cf7 Andrea Spadaccini
  if result.failed:
408 fb460cf7 Andrea Spadaccini
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
409 fb460cf7 Andrea Spadaccini
                  " and error %s",
410 fb460cf7 Andrea Spadaccini
                  result.cmd, result.exit_code, result.output)
411 a8083063 Iustin Pop
412 a8083063 Iustin Pop
413 41e079ce Andrea Spadaccini
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
414 5a8648eb Andrea Spadaccini
  """Change the netmask of the master IP.
415 5a8648eb Andrea Spadaccini

416 41e079ce Andrea Spadaccini
  @param old_netmask: the old value of the netmask
417 41e079ce Andrea Spadaccini
  @param netmask: the new value of the netmask
418 41e079ce Andrea Spadaccini
  @param master_ip: the master IP
419 41e079ce Andrea Spadaccini
  @param master_netdev: the master network device
420 41e079ce Andrea Spadaccini

421 5a8648eb Andrea Spadaccini
  """
422 5a8648eb Andrea Spadaccini
  if old_netmask == netmask:
423 5a8648eb Andrea Spadaccini
    return
424 5a8648eb Andrea Spadaccini
425 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
426 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, netmask),
427 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
428 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
429 5a8648eb Andrea Spadaccini
  if result.failed:
430 5a8648eb Andrea Spadaccini
    _Fail("Could not change the master IP netmask")
431 5a8648eb Andrea Spadaccini
432 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
433 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, old_netmask),
434 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
435 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
436 5a8648eb Andrea Spadaccini
  if result.failed:
437 5a8648eb Andrea Spadaccini
    _Fail("Could not change the master IP netmask")
438 5a8648eb Andrea Spadaccini
439 5a8648eb Andrea Spadaccini
440 19ddc57a René Nussbaumer
def EtcHostsModify(mode, host, ip):
441 19ddc57a René Nussbaumer
  """Modify a host entry in /etc/hosts.
442 19ddc57a René Nussbaumer

443 19ddc57a René Nussbaumer
  @param mode: The mode to operate. Either add or remove entry
444 19ddc57a René Nussbaumer
  @param host: The host to operate on
445 19ddc57a René Nussbaumer
  @param ip: The ip associated with the entry
446 19ddc57a René Nussbaumer

447 19ddc57a René Nussbaumer
  """
448 19ddc57a René Nussbaumer
  if mode == constants.ETC_HOSTS_ADD:
449 19ddc57a René Nussbaumer
    if not ip:
450 19ddc57a René Nussbaumer
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
451 19ddc57a René Nussbaumer
              " present")
452 19ddc57a René Nussbaumer
    utils.AddHostToEtcHosts(host, ip)
453 19ddc57a René Nussbaumer
  elif mode == constants.ETC_HOSTS_REMOVE:
454 19ddc57a René Nussbaumer
    if ip:
455 19ddc57a René Nussbaumer
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
456 19ddc57a René Nussbaumer
              " parameter is present")
457 19ddc57a René Nussbaumer
    utils.RemoveHostFromEtcHosts(host)
458 19ddc57a René Nussbaumer
  else:
459 19ddc57a René Nussbaumer
    RPCFail("Mode not supported")
460 19ddc57a René Nussbaumer
461 19ddc57a René Nussbaumer
462 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
463 10c2650b Iustin Pop
  """Cleans up and remove the current node.
464 10c2650b Iustin Pop

465 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
466 10c2650b Iustin Pop
  from the cluster.
467 10c2650b Iustin Pop

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

472 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
473 b989b9d9 Ken Wehr

474 a8083063 Iustin Pop
  """
475 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
476 f942a838 Michael Hanselmann
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
477 1bc59f76 Michael Hanselmann
  JobQueuePurge()
478 f78346f5 Michael Hanselmann
479 b989b9d9 Ken Wehr
  if modify_ssh_setup:
480 b989b9d9 Ken Wehr
    try:
481 b989b9d9 Ken Wehr
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
482 7900ed01 Iustin Pop
483 b989b9d9 Ken Wehr
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
484 a8083063 Iustin Pop
485 b989b9d9 Ken Wehr
      utils.RemoveFile(priv_key)
486 b989b9d9 Ken Wehr
      utils.RemoveFile(pub_key)
487 b989b9d9 Ken Wehr
    except errors.OpExecError:
488 b989b9d9 Ken Wehr
      logging.exception("Error while processing ssh files")
489 a8083063 Iustin Pop
490 ed008420 Guido Trotter
  try:
491 6b7d5878 Michael Hanselmann
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
492 ed008420 Guido Trotter
    utils.RemoveFile(constants.RAPI_CERT_FILE)
493 bfe86c76 Andrea Spadaccini
    utils.RemoveFile(constants.SPICE_CERT_FILE)
494 bfe86c76 Andrea Spadaccini
    utils.RemoveFile(constants.SPICE_CACERT_FILE)
495 168c1de2 Michael Hanselmann
    utils.RemoveFile(constants.NODED_CERT_FILE)
496 b459a848 Andrea Spadaccini
  except: # pylint: disable=W0702
497 ed008420 Guido Trotter
    logging.exception("Error while removing cluster secrets")
498 ed008420 Guido Trotter
499 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
500 f154a7a3 Michael Hanselmann
  if result.failed:
501 f154a7a3 Michael Hanselmann
    logging.error("Command %s failed with exitcode %s and error %s",
502 f154a7a3 Michael Hanselmann
                  result.cmd, result.exit_code, result.output)
503 ed008420 Guido Trotter
504 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
505 d0c8c01d Iustin Pop
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
506 6d8b6238 Guido Trotter
507 a8083063 Iustin Pop
508 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
509 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
510 a8083063 Iustin Pop

511 e69d05fd Iustin Pop
  @type vgname: C{string}
512 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
513 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
514 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
515 e69d05fd Iustin Pop
      memory information
516 e69d05fd Iustin Pop
  @rtype: C{dict}
517 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
518 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
519 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
520 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
521 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
522 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
523 34fbc862 Andrea Spadaccini
      - hv_version: the hypervisor version, if available
524 a8083063 Iustin Pop

525 098c0958 Michael Hanselmann
  """
526 a8083063 Iustin Pop
  outputarray = {}
527 673cd9c4 René Nussbaumer
528 cb6a0296 Iustin Pop
  if vgname is not None:
529 cb6a0296 Iustin Pop
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
530 cb6a0296 Iustin Pop
    vg_free = vg_size = None
531 cb6a0296 Iustin Pop
    if vginfo:
532 cb6a0296 Iustin Pop
      vg_free = int(round(vginfo[0][0], 0))
533 cb6a0296 Iustin Pop
      vg_size = int(round(vginfo[0][1], 0))
534 d0c8c01d Iustin Pop
    outputarray["vg_size"] = vg_size
535 d0c8c01d Iustin Pop
    outputarray["vg_free"] = vg_free
536 cb6a0296 Iustin Pop
537 cb6a0296 Iustin Pop
  if hypervisor_type is not None:
538 cb6a0296 Iustin Pop
    hyper = hypervisor.GetHypervisor(hypervisor_type)
539 cb6a0296 Iustin Pop
    hyp_info = hyper.GetNodeInfo()
540 cb6a0296 Iustin Pop
    if hyp_info is not None:
541 cb6a0296 Iustin Pop
      outputarray.update(hyp_info)
542 a8083063 Iustin Pop
543 13998ef2 Michael Hanselmann
  outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
544 3ef10550 Michael Hanselmann
545 c26a6bd2 Iustin Pop
  return outputarray
546 a8083063 Iustin Pop
547 a8083063 Iustin Pop
548 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
549 a8083063 Iustin Pop
  """Verify the status of the local node.
550 a8083063 Iustin Pop

551 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
552 e69d05fd Iustin Pop
  local node.
553 e69d05fd Iustin Pop

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

557 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
558 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
559 e69d05fd Iustin Pop
  report).
560 a8083063 Iustin Pop

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

565 e69d05fd Iustin Pop
  @type what: C{dict}
566 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
567 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
568 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
569 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
570 e69d05fd Iustin Pop
        connectivity with
571 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
572 10c2650b Iustin Pop
  @rtype: dict
573 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
574 10c2650b Iustin Pop
      values representing the result of the checks
575 a8083063 Iustin Pop

576 a8083063 Iustin Pop
  """
577 a8083063 Iustin Pop
  result = {}
578 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
579 a744b676 Manuel Franceschini
  port = netutils.GetDaemonPort(constants.NODED)
580 8964ee14 Iustin Pop
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
581 a8083063 Iustin Pop
582 8964ee14 Iustin Pop
  if constants.NV_HYPERVISOR in what and vm_capable:
583 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
584 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
585 0cf5e7f5 Iustin Pop
      try:
586 0cf5e7f5 Iustin Pop
        val = hypervisor.GetHypervisor(hv_name).Verify()
587 0cf5e7f5 Iustin Pop
      except errors.HypervisorError, err:
588 0cf5e7f5 Iustin Pop
        val = "Error while checking hypervisor: %s" % str(err)
589 0cf5e7f5 Iustin Pop
      tmp[hv_name] = val
590 25361b9a Iustin Pop
591 58a59652 Iustin Pop
  if constants.NV_HVPARAMS in what and vm_capable:
592 58a59652 Iustin Pop
    result[constants.NV_HVPARAMS] = tmp = []
593 58a59652 Iustin Pop
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
594 58a59652 Iustin Pop
      try:
595 58a59652 Iustin Pop
        logging.info("Validating hv %s, %s", hv_name, hvparms)
596 58a59652 Iustin Pop
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
597 58a59652 Iustin Pop
      except errors.HypervisorError, err:
598 58a59652 Iustin Pop
        tmp.append((source, hv_name, str(err)))
599 58a59652 Iustin Pop
600 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
601 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
602 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
603 25361b9a Iustin Pop
604 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
605 64c7b383 Michael Hanselmann
    (nodes, bynode) = what[constants.NV_NODELIST]
606 64c7b383 Michael Hanselmann
607 64c7b383 Michael Hanselmann
    # Add nodes from other groups (different for each node)
608 64c7b383 Michael Hanselmann
    try:
609 64c7b383 Michael Hanselmann
      nodes.extend(bynode[my_name])
610 64c7b383 Michael Hanselmann
    except KeyError:
611 64c7b383 Michael Hanselmann
      pass
612 64c7b383 Michael Hanselmann
613 64c7b383 Michael Hanselmann
    # Use a random order
614 64c7b383 Michael Hanselmann
    random.shuffle(nodes)
615 64c7b383 Michael Hanselmann
616 64c7b383 Michael Hanselmann
    # Try to contact all nodes
617 64c7b383 Michael Hanselmann
    val = {}
618 64c7b383 Michael Hanselmann
    for node in nodes:
619 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
620 a8083063 Iustin Pop
      if not success:
621 64c7b383 Michael Hanselmann
        val[node] = message
622 64c7b383 Michael Hanselmann
623 64c7b383 Michael Hanselmann
    result[constants.NV_NODELIST] = val
624 25361b9a Iustin Pop
625 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
626 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
627 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
628 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
629 9d4bfc96 Iustin Pop
      if name == my_name:
630 9d4bfc96 Iustin Pop
        my_pip = pip
631 9d4bfc96 Iustin Pop
        my_sip = sip
632 9d4bfc96 Iustin Pop
        break
633 9d4bfc96 Iustin Pop
    if not my_pip:
634 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
635 25361b9a Iustin Pop
                      " in the node list")
636 9d4bfc96 Iustin Pop
    else:
637 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
638 9d4bfc96 Iustin Pop
        fail = []
639 a744b676 Manuel Franceschini
        if not netutils.TcpPing(pip, port, source=my_pip):
640 9d4bfc96 Iustin Pop
          fail.append("primary")
641 9d4bfc96 Iustin Pop
        if sip != pip:
642 a744b676 Manuel Franceschini
          if not netutils.TcpPing(sip, port, source=my_sip):
643 9d4bfc96 Iustin Pop
            fail.append("secondary")
644 9d4bfc96 Iustin Pop
        if fail:
645 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
646 25361b9a Iustin Pop
                       " and ".join(fail))
647 25361b9a Iustin Pop
648 a3a5f850 Iustin Pop
  if constants.NV_MASTERIP in what:
649 a3a5f850 Iustin Pop
    # FIXME: add checks on incoming data structures (here and in the
650 a3a5f850 Iustin Pop
    # rest of the function)
651 a3a5f850 Iustin Pop
    master_name, master_ip = what[constants.NV_MASTERIP]
652 a3a5f850 Iustin Pop
    if master_name == my_name:
653 9769bb78 Manuel Franceschini
      source = constants.IP4_ADDRESS_LOCALHOST
654 a3a5f850 Iustin Pop
    else:
655 a3a5f850 Iustin Pop
      source = None
656 a744b676 Manuel Franceschini
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
657 a3a5f850 Iustin Pop
                                                  source=source)
658 a3a5f850 Iustin Pop
659 16f41f24 René Nussbaumer
  if constants.NV_OOB_PATHS in what:
660 16f41f24 René Nussbaumer
    result[constants.NV_OOB_PATHS] = tmp = []
661 16f41f24 René Nussbaumer
    for path in what[constants.NV_OOB_PATHS]:
662 16f41f24 René Nussbaumer
      try:
663 16f41f24 René Nussbaumer
        st = os.stat(path)
664 16f41f24 René Nussbaumer
      except OSError, err:
665 16f41f24 René Nussbaumer
        tmp.append("error stating out of band helper: %s" % err)
666 16f41f24 René Nussbaumer
      else:
667 16f41f24 René Nussbaumer
        if stat.S_ISREG(st.st_mode):
668 16f41f24 René Nussbaumer
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
669 16f41f24 René Nussbaumer
            tmp.append(None)
670 16f41f24 René Nussbaumer
          else:
671 16f41f24 René Nussbaumer
            tmp.append("out of band helper %s is not executable" % path)
672 16f41f24 René Nussbaumer
        else:
673 16f41f24 René Nussbaumer
          tmp.append("out of band helper %s is not a file" % path)
674 16f41f24 René Nussbaumer
675 8964ee14 Iustin Pop
  if constants.NV_LVLIST in what and vm_capable:
676 ed904904 Iustin Pop
    try:
677 84d7e26b Dmitry Chernyak
      val = GetVolumeList(utils.ListVolumeGroups().keys())
678 ed904904 Iustin Pop
    except RPCFail, err:
679 ed904904 Iustin Pop
      val = str(err)
680 ed904904 Iustin Pop
    result[constants.NV_LVLIST] = val
681 25361b9a Iustin Pop
682 8964ee14 Iustin Pop
  if constants.NV_INSTANCELIST in what and vm_capable:
683 0cf5e7f5 Iustin Pop
    # GetInstanceList can fail
684 0cf5e7f5 Iustin Pop
    try:
685 0cf5e7f5 Iustin Pop
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
686 0cf5e7f5 Iustin Pop
    except RPCFail, err:
687 0cf5e7f5 Iustin Pop
      val = str(err)
688 0cf5e7f5 Iustin Pop
    result[constants.NV_INSTANCELIST] = val
689 25361b9a Iustin Pop
690 8964ee14 Iustin Pop
  if constants.NV_VGLIST in what and vm_capable:
691 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
692 25361b9a Iustin Pop
693 8964ee14 Iustin Pop
  if constants.NV_PVLIST in what and vm_capable:
694 d091393e Iustin Pop
    result[constants.NV_PVLIST] = \
695 d091393e Iustin Pop
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
696 d091393e Iustin Pop
                                   filter_allocatable=False)
697 d091393e Iustin Pop
698 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
699 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
700 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
701 25361b9a Iustin Pop
702 8964ee14 Iustin Pop
  if constants.NV_HVINFO in what and vm_capable:
703 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
704 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
705 9d4bfc96 Iustin Pop
706 8964ee14 Iustin Pop
  if constants.NV_DRBDLIST in what and vm_capable:
707 6d2e83d5 Iustin Pop
    try:
708 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
709 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
710 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
711 f6eaed12 Iustin Pop
      used_minors = str(err)
712 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
713 6d2e83d5 Iustin Pop
714 8964ee14 Iustin Pop
  if constants.NV_DRBDHELPER in what and vm_capable:
715 7ef40fbe Luca Bigliardi
    status = True
716 7ef40fbe Luca Bigliardi
    try:
717 7ef40fbe Luca Bigliardi
      payload = bdev.BaseDRBD.GetUsermodeHelper()
718 7ef40fbe Luca Bigliardi
    except errors.BlockDeviceError, err:
719 7ef40fbe Luca Bigliardi
      logging.error("Can't get DRBD usermode helper: %s", str(err))
720 7ef40fbe Luca Bigliardi
      status = False
721 7ef40fbe Luca Bigliardi
      payload = str(err)
722 7ef40fbe Luca Bigliardi
    result[constants.NV_DRBDHELPER] = (status, payload)
723 7ef40fbe Luca Bigliardi
724 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
725 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
726 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
727 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
728 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
729 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
730 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
731 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
732 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
733 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
734 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
735 313b2dd4 Michael Hanselmann
736 313b2dd4 Michael Hanselmann
  if constants.NV_TIME in what:
737 313b2dd4 Michael Hanselmann
    result[constants.NV_TIME] = utils.SplitTime(time.time())
738 313b2dd4 Michael Hanselmann
739 8964ee14 Iustin Pop
  if constants.NV_OSLIST in what and vm_capable:
740 b0d85178 Iustin Pop
    result[constants.NV_OSLIST] = DiagnoseOS()
741 b0d85178 Iustin Pop
742 20d317d4 Iustin Pop
  if constants.NV_BRIDGES in what and vm_capable:
743 20d317d4 Iustin Pop
    result[constants.NV_BRIDGES] = [bridge
744 20d317d4 Iustin Pop
                                    for bridge in what[constants.NV_BRIDGES]
745 20d317d4 Iustin Pop
                                    if not utils.BridgeExists(bridge)]
746 c26a6bd2 Iustin Pop
  return result
747 a8083063 Iustin Pop
748 a8083063 Iustin Pop
749 2be7273c Apollon Oikonomopoulos
def GetBlockDevSizes(devices):
750 2be7273c Apollon Oikonomopoulos
  """Return the size of the given block devices
751 2be7273c Apollon Oikonomopoulos

752 2be7273c Apollon Oikonomopoulos
  @type devices: list
753 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
754 2be7273c Apollon Oikonomopoulos
  @rtype: dict
755 2be7273c Apollon Oikonomopoulos
  @return:
756 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
757 2be7273c Apollon Oikonomopoulos
    size in MiB.
758 2be7273c Apollon Oikonomopoulos

759 2be7273c Apollon Oikonomopoulos
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
760 2be7273c Apollon Oikonomopoulos

761 2be7273c Apollon Oikonomopoulos
  """
762 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
763 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
764 2be7273c Apollon Oikonomopoulos
765 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
766 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
767 2be7273c Apollon Oikonomopoulos
      continue
768 2be7273c Apollon Oikonomopoulos
769 2be7273c Apollon Oikonomopoulos
    try:
770 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
771 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
772 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
773 2be7273c Apollon Oikonomopoulos
      continue
774 2be7273c Apollon Oikonomopoulos
775 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
776 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
777 2be7273c Apollon Oikonomopoulos
      if result.failed:
778 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
779 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
780 2be7273c Apollon Oikonomopoulos
        continue
781 2be7273c Apollon Oikonomopoulos
782 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
783 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
784 2be7273c Apollon Oikonomopoulos
  return blockdevs
785 2be7273c Apollon Oikonomopoulos
786 2be7273c Apollon Oikonomopoulos
787 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
788 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
789 a8083063 Iustin Pop

790 84d7e26b Dmitry Chernyak
  @type vg_names: list
791 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
792 397693d3 Iustin Pop
      empty for all volume groups
793 10c2650b Iustin Pop
  @rtype: dict
794 10c2650b Iustin Pop
  @return:
795 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
796 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
797 10c2650b Iustin Pop

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

800 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
801 10c2650b Iustin Pop
      details.
802 a8083063 Iustin Pop

803 a8083063 Iustin Pop
  """
804 cb2037a2 Iustin Pop
  lvs = {}
805 d0c8c01d Iustin Pop
  sep = "|"
806 397693d3 Iustin Pop
  if not vg_names:
807 397693d3 Iustin Pop
    vg_names = []
808 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
809 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
810 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
811 a8083063 Iustin Pop
  if result.failed:
812 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
813 cb2037a2 Iustin Pop
814 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
815 df4c2628 Iustin Pop
    line = line.strip()
816 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
817 df4c2628 Iustin Pop
    if not match:
818 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
819 df4c2628 Iustin Pop
      continue
820 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
821 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
822 d0c8c01d Iustin Pop
    online = attr[5] == "o"
823 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
824 33f2a81a Iustin Pop
    if virtual:
825 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
826 33f2a81a Iustin Pop
      # don't really hold data
827 33f2a81a Iustin Pop
      continue
828 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
829 cb2037a2 Iustin Pop
830 cb2037a2 Iustin Pop
  return lvs
831 a8083063 Iustin Pop
832 a8083063 Iustin Pop
833 a8083063 Iustin Pop
def ListVolumeGroups():
834 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
835 a8083063 Iustin Pop

836 10c2650b Iustin Pop
  @rtype: dict
837 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
838 10c2650b Iustin Pop
      size of the volume
839 a8083063 Iustin Pop

840 a8083063 Iustin Pop
  """
841 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
842 a8083063 Iustin Pop
843 a8083063 Iustin Pop
844 dcb93971 Michael Hanselmann
def NodeVolumes():
845 dcb93971 Michael Hanselmann
  """List all volumes on this node.
846 dcb93971 Michael Hanselmann

847 10c2650b Iustin Pop
  @rtype: list
848 10c2650b Iustin Pop
  @return:
849 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
850 10c2650b Iustin Pop
      - name: the logical volume name,
851 10c2650b Iustin Pop
      - size: the size of the logical volume
852 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
853 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
854 10c2650b Iustin Pop

855 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
856 10c2650b Iustin Pop
    error.
857 10c2650b Iustin Pop

858 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
859 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
860 10c2650b Iustin Pop
    multiple times.
861 10c2650b Iustin Pop

862 dcb93971 Michael Hanselmann
  """
863 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
864 dcb93971 Michael Hanselmann
                         "--separator=|",
865 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
866 dcb93971 Michael Hanselmann
  if result.failed:
867 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
868 10bfe6cb Iustin Pop
          result.output)
869 dcb93971 Michael Hanselmann
870 dcb93971 Michael Hanselmann
  def parse_dev(dev):
871 d0c8c01d Iustin Pop
    return dev.split("(")[0]
872 89e5ab02 Iustin Pop
873 89e5ab02 Iustin Pop
  def handle_dev(dev):
874 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
875 dcb93971 Michael Hanselmann
876 dcb93971 Michael Hanselmann
  def map_line(line):
877 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
878 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
879 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
880 89e5ab02 Iustin Pop
881 89e5ab02 Iustin Pop
  all_devs = []
882 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
883 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
884 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
885 89e5ab02 Iustin Pop
    else:
886 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
887 89e5ab02 Iustin Pop
  return all_devs
888 dcb93971 Michael Hanselmann
889 dcb93971 Michael Hanselmann
890 a8083063 Iustin Pop
def BridgesExist(bridges_list):
891 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
892 a8083063 Iustin Pop

893 b1206984 Iustin Pop
  @rtype: boolean
894 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
895 a8083063 Iustin Pop

896 a8083063 Iustin Pop
  """
897 35c0c8da Iustin Pop
  missing = []
898 a8083063 Iustin Pop
  for bridge in bridges_list:
899 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
900 35c0c8da Iustin Pop
      missing.append(bridge)
901 a8083063 Iustin Pop
902 35c0c8da Iustin Pop
  if missing:
903 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
904 35c0c8da Iustin Pop
905 a8083063 Iustin Pop
906 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
907 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
908 a8083063 Iustin Pop

909 e69d05fd Iustin Pop
  @type hypervisor_list: list
910 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
911 e69d05fd Iustin Pop

912 e69d05fd Iustin Pop
  @rtype: list
913 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
914 10c2650b Iustin Pop
    - instance1.example.com
915 10c2650b Iustin Pop
    - instance2.example.com
916 a8083063 Iustin Pop

917 098c0958 Michael Hanselmann
  """
918 e69d05fd Iustin Pop
  results = []
919 e69d05fd Iustin Pop
  for hname in hypervisor_list:
920 e69d05fd Iustin Pop
    try:
921 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
922 e69d05fd Iustin Pop
      results.extend(names)
923 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
924 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
925 aca13712 Iustin Pop
            hname, err, exc=True)
926 a8083063 Iustin Pop
927 e69d05fd Iustin Pop
  return results
928 a8083063 Iustin Pop
929 a8083063 Iustin Pop
930 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
931 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
932 a8083063 Iustin Pop

933 e69d05fd Iustin Pop
  @type instance: string
934 e69d05fd Iustin Pop
  @param instance: the instance name
935 e69d05fd Iustin Pop
  @type hname: string
936 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
937 a8083063 Iustin Pop

938 e69d05fd Iustin Pop
  @rtype: dict
939 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
940 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
941 e69d05fd Iustin Pop
      - state: xen state of instance (string)
942 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
943 a8083063 Iustin Pop

944 098c0958 Michael Hanselmann
  """
945 a8083063 Iustin Pop
  output = {}
946 a8083063 Iustin Pop
947 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
948 a8083063 Iustin Pop
  if iinfo is not None:
949 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
950 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
951 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
952 a8083063 Iustin Pop
953 c26a6bd2 Iustin Pop
  return output
954 a8083063 Iustin Pop
955 a8083063 Iustin Pop
956 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
957 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
958 56e7640c Iustin Pop

959 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
960 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
961 56e7640c Iustin Pop

962 56e7640c Iustin Pop
  @rtype: tuple
963 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
964 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
965 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
966 56e7640c Iustin Pop

967 56e7640c Iustin Pop
  """
968 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
969 afdc3985 Iustin Pop
  iname = instance.name
970 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
971 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
972 56e7640c Iustin Pop
973 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
974 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
975 56e7640c Iustin Pop
    if not os.path.islink(link_name):
976 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
977 b8ebd37b Iustin Pop
                      iname, link_name, idx)
978 56e7640c Iustin Pop
979 56e7640c Iustin Pop
980 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
981 a8083063 Iustin Pop
  """Gather data about all instances.
982 a8083063 Iustin Pop

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

987 e69d05fd Iustin Pop
  @type hypervisor_list: list
988 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
989 e69d05fd Iustin Pop

990 955db481 Guido Trotter
  @rtype: dict
991 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
992 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
993 e69d05fd Iustin Pop
      - state: xen state of instance (string)
994 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
995 10c2650b Iustin Pop
      - vcpus: the number of vcpus
996 a8083063 Iustin Pop

997 098c0958 Michael Hanselmann
  """
998 a8083063 Iustin Pop
  output = {}
999 a8083063 Iustin Pop
1000 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1001 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1002 e69d05fd Iustin Pop
    if iinfo:
1003 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1004 f23b5ae8 Iustin Pop
        value = {
1005 d0c8c01d Iustin Pop
          "memory": memory,
1006 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1007 d0c8c01d Iustin Pop
          "state": state,
1008 d0c8c01d Iustin Pop
          "time": times,
1009 e69d05fd Iustin Pop
          }
1010 b33b6f55 Iustin Pop
        if name in output:
1011 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1012 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1013 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1014 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1015 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1016 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1017 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1018 f23b5ae8 Iustin Pop
        output[name] = value
1019 a8083063 Iustin Pop
1020 c26a6bd2 Iustin Pop
  return output
1021 a8083063 Iustin Pop
1022 a8083063 Iustin Pop
1023 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1024 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1025 81a3406c Iustin Pop

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

1029 81a3406c Iustin Pop
  @type kind: string
1030 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1031 81a3406c Iustin Pop
  @type os_name: string
1032 81a3406c Iustin Pop
  @param os_name: the os name
1033 81a3406c Iustin Pop
  @type instance: string
1034 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1035 6aa7a354 Iustin Pop
  @type component: string or None
1036 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1037 6aa7a354 Iustin Pop
      transferred
1038 81a3406c Iustin Pop

1039 81a3406c Iustin Pop
  """
1040 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1041 6aa7a354 Iustin Pop
  if component:
1042 6aa7a354 Iustin Pop
    assert "/" not in component
1043 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1044 6aa7a354 Iustin Pop
  else:
1045 6aa7a354 Iustin Pop
    c_msg = ""
1046 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1047 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1048 81a3406c Iustin Pop
  return utils.PathJoin(constants.LOG_OS_DIR, base)
1049 81a3406c Iustin Pop
1050 81a3406c Iustin Pop
1051 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1052 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1053 a8083063 Iustin Pop

1054 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1055 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1056 e557bae9 Guido Trotter
  @type reinstall: boolean
1057 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1058 4a0e011f Iustin Pop
  @type debug: integer
1059 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1060 c26a6bd2 Iustin Pop
  @rtype: None
1061 a8083063 Iustin Pop

1062 a8083063 Iustin Pop
  """
1063 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1064 255dcebd Iustin Pop
1065 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1066 e557bae9 Guido Trotter
  if reinstall:
1067 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1068 a8083063 Iustin Pop
1069 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1070 decd5f45 Iustin Pop
1071 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1072 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1073 decd5f45 Iustin Pop
  if result.failed:
1074 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1075 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1076 18682bca Iustin Pop
                  result.output)
1077 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1078 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1079 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1080 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1081 decd5f45 Iustin Pop
1082 decd5f45 Iustin Pop
1083 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1084 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1085 decd5f45 Iustin Pop

1086 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1087 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1088 d15a9ad3 Guido Trotter
  @type old_name: string
1089 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1090 4a0e011f Iustin Pop
  @type debug: integer
1091 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1092 10c2650b Iustin Pop
  @rtype: boolean
1093 10c2650b Iustin Pop
  @return: the success of the operation
1094 decd5f45 Iustin Pop

1095 decd5f45 Iustin Pop
  """
1096 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1097 decd5f45 Iustin Pop
1098 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1099 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1100 decd5f45 Iustin Pop
1101 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1102 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1103 a8083063 Iustin Pop
1104 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1105 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1106 a8083063 Iustin Pop
1107 a8083063 Iustin Pop
  if result.failed:
1108 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1109 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1110 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1111 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1112 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1113 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1114 a8083063 Iustin Pop
1115 a8083063 Iustin Pop
1116 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
1117 3536c792 Iustin Pop
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1118 3536c792 Iustin Pop
                        (instance_name, constants.DISK_SEPARATOR, idx))
1119 5282084b Iustin Pop
1120 5282084b Iustin Pop
1121 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1122 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1123 9332fd8a Iustin Pop

1124 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1125 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1126 9332fd8a Iustin Pop

1127 9332fd8a Iustin Pop

1128 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1129 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1130 5282084b Iustin Pop
  @param idx: the disk index
1131 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1132 9332fd8a Iustin Pop

1133 9332fd8a Iustin Pop
  """
1134 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1135 9332fd8a Iustin Pop
  try:
1136 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1137 5282084b Iustin Pop
  except OSError, err:
1138 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1139 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1140 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1141 9332fd8a Iustin Pop
        os.remove(link_name)
1142 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1143 9332fd8a Iustin Pop
    else:
1144 9332fd8a Iustin Pop
      raise
1145 9332fd8a Iustin Pop
1146 9332fd8a Iustin Pop
  return link_name
1147 9332fd8a Iustin Pop
1148 9332fd8a Iustin Pop
1149 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1150 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1151 3c9c571d Iustin Pop

1152 3c9c571d Iustin Pop
  """
1153 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1154 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1155 5282084b Iustin Pop
    if os.path.islink(link_name):
1156 3c9c571d Iustin Pop
      try:
1157 03dfa658 Iustin Pop
        os.remove(link_name)
1158 03dfa658 Iustin Pop
      except OSError:
1159 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1160 3c9c571d Iustin Pop
1161 3c9c571d Iustin Pop
1162 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1163 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1164 a8083063 Iustin Pop

1165 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1166 a8083063 Iustin Pop
  devices must be already assembled.
1167 a8083063 Iustin Pop

1168 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1169 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1170 069cfbf1 Iustin Pop
  @rtype: list
1171 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1172 10c2650b Iustin Pop

1173 a8083063 Iustin Pop
  """
1174 a8083063 Iustin Pop
  block_devices = []
1175 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1176 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1177 a8083063 Iustin Pop
    if device is None:
1178 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1179 a8083063 Iustin Pop
                                    str(disk))
1180 a8083063 Iustin Pop
    device.Open()
1181 9332fd8a Iustin Pop
    try:
1182 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1183 9332fd8a Iustin Pop
    except OSError, e:
1184 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1185 9332fd8a Iustin Pop
                                    e.strerror)
1186 9332fd8a Iustin Pop
1187 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1188 9332fd8a Iustin Pop
1189 a8083063 Iustin Pop
  return block_devices
1190 a8083063 Iustin Pop
1191 a8083063 Iustin Pop
1192 323f9095 Stephen Shirley
def StartInstance(instance, startup_paused):
1193 a8083063 Iustin Pop
  """Start an instance.
1194 a8083063 Iustin Pop

1195 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1196 e69d05fd Iustin Pop
  @param instance: the instance object
1197 323f9095 Stephen Shirley
  @type startup_paused: bool
1198 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1199 c26a6bd2 Iustin Pop
  @rtype: None
1200 a8083063 Iustin Pop

1201 098c0958 Michael Hanselmann
  """
1202 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1203 a8083063 Iustin Pop
1204 a8083063 Iustin Pop
  if instance.name in running_instances:
1205 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1206 c26a6bd2 Iustin Pop
    return
1207 a8083063 Iustin Pop
1208 a8083063 Iustin Pop
  try:
1209 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1210 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1211 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1212 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1213 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1214 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1215 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1216 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1217 a8083063 Iustin Pop
1218 a8083063 Iustin Pop
1219 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1220 a8083063 Iustin Pop
  """Shut an instance down.
1221 a8083063 Iustin Pop

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

1224 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1225 e69d05fd Iustin Pop
  @param instance: the instance object
1226 6263189c Guido Trotter
  @type timeout: integer
1227 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1228 c26a6bd2 Iustin Pop
  @rtype: None
1229 a8083063 Iustin Pop

1230 098c0958 Michael Hanselmann
  """
1231 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1232 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1233 c26a6bd2 Iustin Pop
  iname = instance.name
1234 a8083063 Iustin Pop
1235 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1236 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1237 c26a6bd2 Iustin Pop
    return
1238 a8083063 Iustin Pop
1239 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1240 3c0cdc83 Michael Hanselmann
    def __init__(self):
1241 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1242 a8083063 Iustin Pop
1243 3c0cdc83 Michael Hanselmann
    def __call__(self):
1244 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1245 3c0cdc83 Michael Hanselmann
        return
1246 3c0cdc83 Michael Hanselmann
1247 3c0cdc83 Michael Hanselmann
      try:
1248 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1249 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1250 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1251 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1252 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1253 3c0cdc83 Michael Hanselmann
          return
1254 3c0cdc83 Michael Hanselmann
1255 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1256 3c0cdc83 Michael Hanselmann
1257 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1258 3c0cdc83 Michael Hanselmann
1259 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1260 3c0cdc83 Michael Hanselmann
1261 3c0cdc83 Michael Hanselmann
  try:
1262 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1263 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1264 a8083063 Iustin Pop
    # the shutdown did not succeed
1265 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1266 a8083063 Iustin Pop
1267 a8083063 Iustin Pop
    try:
1268 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1269 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1270 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1271 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1272 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1273 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1274 a8083063 Iustin Pop
1275 a8083063 Iustin Pop
    time.sleep(1)
1276 3c0cdc83 Michael Hanselmann
1277 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1278 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1279 3c9c571d Iustin Pop
1280 f28ec899 Guido Trotter
  try:
1281 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1282 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1283 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1284 f28ec899 Guido Trotter
1285 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1286 a8083063 Iustin Pop
1287 a8083063 Iustin Pop
1288 17c3f802 Guido Trotter
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1289 007a2f3e Alexander Schreiber
  """Reboot an instance.
1290 007a2f3e Alexander Schreiber

1291 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1292 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1293 10c2650b Iustin Pop
  @type reboot_type: str
1294 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1295 10c2650b Iustin Pop
    constants:
1296 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1297 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1298 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1299 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1300 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1301 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1302 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1303 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1304 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1305 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1306 c26a6bd2 Iustin Pop
  @rtype: None
1307 007a2f3e Alexander Schreiber

1308 007a2f3e Alexander Schreiber
  """
1309 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1310 007a2f3e Alexander Schreiber
1311 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1312 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1313 007a2f3e Alexander Schreiber
1314 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1315 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1316 007a2f3e Alexander Schreiber
    try:
1317 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1318 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1319 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1320 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1321 007a2f3e Alexander Schreiber
    try:
1322 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1323 82bc21e2 Stephen Shirley
      return StartInstance(instance, False)
1324 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1325 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1326 007a2f3e Alexander Schreiber
  else:
1327 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1328 007a2f3e Alexander Schreiber
1329 007a2f3e Alexander Schreiber
1330 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1331 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1332 6906a9d8 Guido Trotter

1333 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1334 6906a9d8 Guido Trotter
  @param instance: the instance definition
1335 6906a9d8 Guido Trotter

1336 6906a9d8 Guido Trotter
  """
1337 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1338 cd42d0ad Guido Trotter
  try:
1339 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1340 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1341 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1342 c26a6bd2 Iustin Pop
  return info
1343 6906a9d8 Guido Trotter
1344 6906a9d8 Guido Trotter
1345 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1346 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1347 6906a9d8 Guido Trotter

1348 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1349 6906a9d8 Guido Trotter
  @param instance: the instance definition
1350 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1351 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1352 6906a9d8 Guido Trotter
  @type target: string
1353 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1354 6906a9d8 Guido Trotter

1355 6906a9d8 Guido Trotter
  """
1356 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1357 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1358 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1359 77fcff4a Apollon Oikonomopoulos
    # in any way
1360 77fcff4a Apollon Oikonomopoulos
    try:
1361 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1362 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1363 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1364 77fcff4a Apollon Oikonomopoulos
1365 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1366 cd42d0ad Guido Trotter
  try:
1367 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1368 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1369 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1370 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1371 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1372 6906a9d8 Guido Trotter
1373 6906a9d8 Guido Trotter
1374 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1375 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1376 6906a9d8 Guido Trotter

1377 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1378 6906a9d8 Guido Trotter
  @param instance: the instance definition
1379 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1380 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1381 6906a9d8 Guido Trotter
  @type success: boolean
1382 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1383 6906a9d8 Guido Trotter

1384 6906a9d8 Guido Trotter
  """
1385 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1386 cd42d0ad Guido Trotter
  try:
1387 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1388 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1389 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1390 6906a9d8 Guido Trotter
1391 6906a9d8 Guido Trotter
1392 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1393 2a10865c Iustin Pop
  """Migrates an instance to another node.
1394 2a10865c Iustin Pop

1395 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1396 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1397 9f0e6b37 Iustin Pop
  @type target: string
1398 9f0e6b37 Iustin Pop
  @param target: the target node name
1399 9f0e6b37 Iustin Pop
  @type live: boolean
1400 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1401 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1402 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1403 9f0e6b37 Iustin Pop

1404 2a10865c Iustin Pop
  """
1405 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1406 2a10865c Iustin Pop
1407 2a10865c Iustin Pop
  try:
1408 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1409 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1410 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1411 2a10865c Iustin Pop
1412 2a10865c Iustin Pop
1413 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1414 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1415 6a1434d7 Andrea Spadaccini

1416 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1417 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1418 6a1434d7 Andrea Spadaccini
  @type success: bool
1419 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1420 6a1434d7 Andrea Spadaccini
  @type live: bool
1421 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1422 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1423 6a1434d7 Andrea Spadaccini

1424 6a1434d7 Andrea Spadaccini
  """
1425 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1426 6a1434d7 Andrea Spadaccini
1427 6a1434d7 Andrea Spadaccini
  try:
1428 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1429 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1430 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1431 6a1434d7 Andrea Spadaccini
          exc=True)
1432 6a1434d7 Andrea Spadaccini
1433 6a1434d7 Andrea Spadaccini
1434 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1435 6a1434d7 Andrea Spadaccini
  """Get the migration status
1436 6a1434d7 Andrea Spadaccini

1437 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1438 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1439 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1440 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1441 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1442 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1443 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1444 6a1434d7 Andrea Spadaccini

1445 6a1434d7 Andrea Spadaccini
  """
1446 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1447 6a1434d7 Andrea Spadaccini
  try:
1448 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1449 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1450 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1451 6a1434d7 Andrea Spadaccini
1452 6a1434d7 Andrea Spadaccini
1453 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1454 a8083063 Iustin Pop
  """Creates a block device for an instance.
1455 a8083063 Iustin Pop

1456 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1457 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1458 b1206984 Iustin Pop
  @type size: int
1459 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1460 b1206984 Iustin Pop
  @type owner: str
1461 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1462 b1206984 Iustin Pop
      used for device cache data
1463 b1206984 Iustin Pop
  @type on_primary: boolean
1464 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1465 b1206984 Iustin Pop
  @type info: string
1466 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1467 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1468 b1206984 Iustin Pop

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

1473 a8083063 Iustin Pop
  """
1474 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
1475 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
1476 a8083063 Iustin Pop
  clist = []
1477 a8083063 Iustin Pop
  if disk.children:
1478 a8083063 Iustin Pop
    for child in disk.children:
1479 1063abd1 Iustin Pop
      try:
1480 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1481 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1482 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1483 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1484 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1485 a8083063 Iustin Pop
        # be assembled
1486 1063abd1 Iustin Pop
        try:
1487 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
1488 1063abd1 Iustin Pop
          crdev.Open()
1489 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1490 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1491 a8083063 Iustin Pop
      clist.append(crdev)
1492 a8083063 Iustin Pop
1493 dab69e97 Iustin Pop
  try:
1494 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1495 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1496 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1497 6c626518 Iustin Pop
1498 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1499 1063abd1 Iustin Pop
    try:
1500 1063abd1 Iustin Pop
      device.Assemble()
1501 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1502 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1503 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1504 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1505 1063abd1 Iustin Pop
      try:
1506 1063abd1 Iustin Pop
        device.Open(force=True)
1507 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1508 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1509 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1510 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1511 a0c3fea1 Michael Hanselmann
1512 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1513 a0c3fea1 Michael Hanselmann
1514 c26a6bd2 Iustin Pop
  return device.unique_id
1515 a8083063 Iustin Pop
1516 a8083063 Iustin Pop
1517 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1518 69dd363f René Nussbaumer
  """This function actually wipes the device.
1519 69dd363f René Nussbaumer

1520 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1521 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1522 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1523 69dd363f René Nussbaumer

1524 69dd363f René Nussbaumer
  """
1525 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1526 da63bb4e René Nussbaumer
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1527 da63bb4e René Nussbaumer
         "count=%d" % size]
1528 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1529 69dd363f René Nussbaumer
1530 69dd363f René Nussbaumer
  if result.failed:
1531 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1532 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1533 69dd363f René Nussbaumer
1534 69dd363f René Nussbaumer
1535 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1536 69dd363f René Nussbaumer
  """Wipes a block device.
1537 69dd363f René Nussbaumer

1538 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1539 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1540 da63bb4e René Nussbaumer
  @type offset: int
1541 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1542 da63bb4e René Nussbaumer
  @type size: int
1543 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1544 69dd363f René Nussbaumer

1545 69dd363f René Nussbaumer
  """
1546 69dd363f René Nussbaumer
  try:
1547 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1548 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1549 da63bb4e René Nussbaumer
    rdev = None
1550 da63bb4e René Nussbaumer
1551 da63bb4e René Nussbaumer
  if not rdev:
1552 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1553 da63bb4e René Nussbaumer
1554 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1555 da63bb4e René Nussbaumer
  if offset > rdev.size:
1556 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1557 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1558 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1559 69dd363f René Nussbaumer
1560 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1561 69dd363f René Nussbaumer
1562 69dd363f René Nussbaumer
1563 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1564 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1565 5119c79e René Nussbaumer

1566 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1567 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1568 5119c79e René Nussbaumer
  @type pause: bool
1569 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1570 5119c79e René Nussbaumer

1571 5119c79e René Nussbaumer
  """
1572 5119c79e René Nussbaumer
  success = []
1573 5119c79e René Nussbaumer
  for disk in disks:
1574 5119c79e René Nussbaumer
    try:
1575 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1576 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1577 5119c79e René Nussbaumer
      rdev = None
1578 5119c79e René Nussbaumer
1579 5119c79e René Nussbaumer
    if not rdev:
1580 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1581 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1582 5119c79e René Nussbaumer
      continue
1583 5119c79e René Nussbaumer
1584 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1585 5119c79e René Nussbaumer
1586 5119c79e René Nussbaumer
    if result:
1587 5119c79e René Nussbaumer
      success.append((result, None))
1588 5119c79e René Nussbaumer
    else:
1589 5119c79e René Nussbaumer
      if pause:
1590 5119c79e René Nussbaumer
        msg = "Pause"
1591 5119c79e René Nussbaumer
      else:
1592 5119c79e René Nussbaumer
        msg = "Resume"
1593 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1594 5119c79e René Nussbaumer
1595 5119c79e René Nussbaumer
  return success
1596 5119c79e René Nussbaumer
1597 5119c79e René Nussbaumer
1598 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1599 a8083063 Iustin Pop
  """Remove a block device.
1600 a8083063 Iustin Pop

1601 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1602 10c2650b Iustin Pop

1603 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1604 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1605 10c2650b Iustin Pop
  @rtype: boolean
1606 10c2650b Iustin Pop
  @return: the success of the operation
1607 a8083063 Iustin Pop

1608 a8083063 Iustin Pop
  """
1609 e1bc0878 Iustin Pop
  msgs = []
1610 a8083063 Iustin Pop
  try:
1611 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1612 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1613 a8083063 Iustin Pop
    # probably can't attach
1614 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1615 a8083063 Iustin Pop
    rdev = None
1616 a8083063 Iustin Pop
  if rdev is not None:
1617 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1618 e1bc0878 Iustin Pop
    try:
1619 0c6c04ec Iustin Pop
      rdev.Remove()
1620 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1621 e1bc0878 Iustin Pop
      msgs.append(str(err))
1622 c26a6bd2 Iustin Pop
    if not msgs:
1623 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1624 e1bc0878 Iustin Pop
1625 a8083063 Iustin Pop
  if disk.children:
1626 a8083063 Iustin Pop
    for child in disk.children:
1627 c26a6bd2 Iustin Pop
      try:
1628 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1629 c26a6bd2 Iustin Pop
      except RPCFail, err:
1630 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1631 e1bc0878 Iustin Pop
1632 c26a6bd2 Iustin Pop
  if msgs:
1633 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1634 afdc3985 Iustin Pop
1635 a8083063 Iustin Pop
1636 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1637 a8083063 Iustin Pop
  """Activate a block device for an instance.
1638 a8083063 Iustin Pop

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

1641 10c2650b Iustin Pop
  @note: this function is called recursively.
1642 a8083063 Iustin Pop

1643 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1644 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1645 10c2650b Iustin Pop
  @type owner: str
1646 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1647 10c2650b Iustin Pop
  @type as_primary: boolean
1648 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1649 10c2650b Iustin Pop
      read/write
1650 a8083063 Iustin Pop

1651 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1652 10c2650b Iustin Pop
      was assembled)
1653 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1654 10c2650b Iustin Pop
      during the activation of the children or the device
1655 10c2650b Iustin Pop
      itself
1656 a8083063 Iustin Pop

1657 a8083063 Iustin Pop
  """
1658 a8083063 Iustin Pop
  children = []
1659 a8083063 Iustin Pop
  if disk.children:
1660 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1661 fc1dc9d7 Iustin Pop
    if mcn == -1:
1662 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1663 fc1dc9d7 Iustin Pop
    else:
1664 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1665 a8083063 Iustin Pop
    for chld_disk in disk.children:
1666 fc1dc9d7 Iustin Pop
      try:
1667 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1668 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1669 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1670 fc1dc9d7 Iustin Pop
          raise
1671 fc1dc9d7 Iustin Pop
        cdev = None
1672 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1673 1063abd1 Iustin Pop
                      str(err))
1674 fc1dc9d7 Iustin Pop
      children.append(cdev)
1675 a8083063 Iustin Pop
1676 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1677 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1678 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1679 a8083063 Iustin Pop
    result = r_dev
1680 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1681 a8083063 Iustin Pop
      r_dev.Open()
1682 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1683 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1684 3f78eef2 Iustin Pop
1685 a8083063 Iustin Pop
  else:
1686 a8083063 Iustin Pop
    result = True
1687 a8083063 Iustin Pop
  return result
1688 a8083063 Iustin Pop
1689 a8083063 Iustin Pop
1690 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
1691 a8083063 Iustin Pop
  """Activate a block device for an instance.
1692 a8083063 Iustin Pop

1693 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1694 a8083063 Iustin Pop

1695 b1206984 Iustin Pop
  @rtype: str or boolean
1696 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1697 b1206984 Iustin Pop
      C{True} for secondary nodes
1698 a8083063 Iustin Pop

1699 a8083063 Iustin Pop
  """
1700 53c14ef1 Iustin Pop
  try:
1701 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1702 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1703 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
1704 53c14ef1 Iustin Pop
      result = result.dev_path
1705 c417e115 Iustin Pop
      if as_primary:
1706 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
1707 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1708 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1709 c417e115 Iustin Pop
  except OSError, err:
1710 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
1711 afdc3985 Iustin Pop
1712 c26a6bd2 Iustin Pop
  return result
1713 a8083063 Iustin Pop
1714 a8083063 Iustin Pop
1715 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1716 a8083063 Iustin Pop
  """Shut down a block device.
1717 a8083063 Iustin Pop

1718 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1719 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1720 c41eea6e Iustin Pop
  shutdown.
1721 a8083063 Iustin Pop

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

1726 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1727 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1728 10c2650b Iustin Pop
      shutdown
1729 c26a6bd2 Iustin Pop
  @rtype: None
1730 10c2650b Iustin Pop

1731 a8083063 Iustin Pop
  """
1732 cacfd1fd Iustin Pop
  msgs = []
1733 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1734 a8083063 Iustin Pop
  if r_dev is not None:
1735 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1736 cacfd1fd Iustin Pop
    try:
1737 746f7476 Iustin Pop
      r_dev.Shutdown()
1738 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1739 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1740 cacfd1fd Iustin Pop
      msgs.append(str(err))
1741 746f7476 Iustin Pop
1742 a8083063 Iustin Pop
  if disk.children:
1743 a8083063 Iustin Pop
    for child in disk.children:
1744 c26a6bd2 Iustin Pop
      try:
1745 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1746 c26a6bd2 Iustin Pop
      except RPCFail, err:
1747 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1748 746f7476 Iustin Pop
1749 c26a6bd2 Iustin Pop
  if msgs:
1750 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1751 a8083063 Iustin Pop
1752 a8083063 Iustin Pop
1753 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1754 153d9724 Iustin Pop
  """Extend a mirrored block device.
1755 a8083063 Iustin Pop

1756 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1757 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1758 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1759 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1760 c26a6bd2 Iustin Pop
  @rtype: None
1761 10c2650b Iustin Pop

1762 a8083063 Iustin Pop
  """
1763 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1764 153d9724 Iustin Pop
  if parent_bdev is None:
1765 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1766 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1767 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1768 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1769 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1770 a8083063 Iustin Pop
1771 a8083063 Iustin Pop
1772 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1773 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1774 a8083063 Iustin Pop

1775 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1776 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1777 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1778 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1779 c26a6bd2 Iustin Pop
  @rtype: None
1780 10c2650b Iustin Pop

1781 a8083063 Iustin Pop
  """
1782 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1783 153d9724 Iustin Pop
  if parent_bdev is None:
1784 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1785 e739bd57 Iustin Pop
  devs = []
1786 e739bd57 Iustin Pop
  for disk in new_cdevs:
1787 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1788 e739bd57 Iustin Pop
    if rpath is None:
1789 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1790 e739bd57 Iustin Pop
      if bd is None:
1791 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1792 e739bd57 Iustin Pop
      else:
1793 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1794 e739bd57 Iustin Pop
    else:
1795 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1796 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1797 e739bd57 Iustin Pop
      devs.append(rpath)
1798 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1799 a8083063 Iustin Pop
1800 a8083063 Iustin Pop
1801 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1802 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1803 a8083063 Iustin Pop

1804 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1805 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1806 10c2650b Iustin Pop
  @rtype: disk
1807 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1808 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1809 10c2650b Iustin Pop
      found
1810 a8083063 Iustin Pop

1811 a8083063 Iustin Pop
  """
1812 a8083063 Iustin Pop
  stats = []
1813 a8083063 Iustin Pop
  for dsk in disks:
1814 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1815 a8083063 Iustin Pop
    if rbd is None:
1816 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1817 96acbc09 Michael Hanselmann
1818 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1819 96acbc09 Michael Hanselmann
1820 c26a6bd2 Iustin Pop
  return stats
1821 a8083063 Iustin Pop
1822 a8083063 Iustin Pop
1823 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1824 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1825 c6a9dffa Michael Hanselmann

1826 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1827 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1828 c6a9dffa Michael Hanselmann
  @rtype: disk
1829 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1830 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
1831 c6a9dffa Michael Hanselmann
    otherwise
1832 c6a9dffa Michael Hanselmann

1833 c6a9dffa Michael Hanselmann
  """
1834 c6a9dffa Michael Hanselmann
  result = []
1835 c6a9dffa Michael Hanselmann
  for disk in disks:
1836 c6a9dffa Michael Hanselmann
    try:
1837 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
1838 c6a9dffa Michael Hanselmann
      if rbd is None:
1839 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
1840 c6a9dffa Michael Hanselmann
        continue
1841 c6a9dffa Michael Hanselmann
1842 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
1843 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
1844 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
1845 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
1846 c6a9dffa Michael Hanselmann
    else:
1847 c6a9dffa Michael Hanselmann
      result.append((True, status))
1848 c6a9dffa Michael Hanselmann
1849 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
1850 c6a9dffa Michael Hanselmann
1851 c6a9dffa Michael Hanselmann
  return result
1852 c6a9dffa Michael Hanselmann
1853 c6a9dffa Michael Hanselmann
1854 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1855 a8083063 Iustin Pop
  """Check if a device is activated.
1856 a8083063 Iustin Pop

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

1859 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1860 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1861 a8083063 Iustin Pop

1862 10c2650b Iustin Pop
  @return: None if the device can't be found,
1863 10c2650b Iustin Pop
      otherwise the device instance
1864 a8083063 Iustin Pop

1865 a8083063 Iustin Pop
  """
1866 a8083063 Iustin Pop
  children = []
1867 a8083063 Iustin Pop
  if disk.children:
1868 a8083063 Iustin Pop
    for chdisk in disk.children:
1869 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1870 a8083063 Iustin Pop
1871 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1872 a8083063 Iustin Pop
1873 a8083063 Iustin Pop
1874 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1875 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1876 f2e07bb4 Michael Hanselmann

1877 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1878 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1879 f2e07bb4 Michael Hanselmann

1880 f2e07bb4 Michael Hanselmann
  """
1881 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1882 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1883 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1884 f2e07bb4 Michael Hanselmann
1885 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1886 f2e07bb4 Michael Hanselmann
1887 f2e07bb4 Michael Hanselmann
  return real_disk
1888 f2e07bb4 Michael Hanselmann
1889 f2e07bb4 Michael Hanselmann
1890 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1891 a8083063 Iustin Pop
  """Check if a device is activated.
1892 a8083063 Iustin Pop

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

1895 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1896 10c2650b Iustin Pop
  @param disk: the disk to find
1897 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1898 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1899 96acbc09 Michael Hanselmann
           information
1900 a8083063 Iustin Pop

1901 a8083063 Iustin Pop
  """
1902 23829f6f Iustin Pop
  try:
1903 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1904 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1905 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1906 96acbc09 Michael Hanselmann
1907 a8083063 Iustin Pop
  if rbd is None:
1908 c26a6bd2 Iustin Pop
    return None
1909 96acbc09 Michael Hanselmann
1910 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
1911 a8083063 Iustin Pop
1912 a8083063 Iustin Pop
1913 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1914 968a7623 Iustin Pop
  """Computes the size of the given disks.
1915 968a7623 Iustin Pop

1916 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
1917 968a7623 Iustin Pop

1918 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
1919 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
1920 968a7623 Iustin Pop
  @rtype: list
1921 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
1922 968a7623 Iustin Pop
      otherwise the size
1923 968a7623 Iustin Pop

1924 968a7623 Iustin Pop
  """
1925 968a7623 Iustin Pop
  result = []
1926 968a7623 Iustin Pop
  for cf in disks:
1927 968a7623 Iustin Pop
    try:
1928 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
1929 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
1930 968a7623 Iustin Pop
      result.append(None)
1931 968a7623 Iustin Pop
      continue
1932 968a7623 Iustin Pop
    if rbd is None:
1933 968a7623 Iustin Pop
      result.append(None)
1934 968a7623 Iustin Pop
    else:
1935 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
1936 968a7623 Iustin Pop
  return result
1937 968a7623 Iustin Pop
1938 968a7623 Iustin Pop
1939 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1940 858f3d18 Iustin Pop
  """Export a block device to a remote node.
1941 858f3d18 Iustin Pop

1942 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
1943 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
1944 858f3d18 Iustin Pop
  @type dest_node: str
1945 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
1946 858f3d18 Iustin Pop
  @type dest_path: str
1947 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
1948 858f3d18 Iustin Pop
  @type cluster_name: str
1949 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1950 858f3d18 Iustin Pop
  @rtype: None
1951 858f3d18 Iustin Pop

1952 858f3d18 Iustin Pop
  """
1953 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
1954 858f3d18 Iustin Pop
1955 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
1956 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1957 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
1958 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
1959 858f3d18 Iustin Pop
1960 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
1961 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
1962 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
1963 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
1964 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
1965 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
1966 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
1967 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
1968 858f3d18 Iustin Pop
1969 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1970 858f3d18 Iustin Pop
                                                   constants.GANETI_RUNAS,
1971 858f3d18 Iustin Pop
                                                   destcmd)
1972 858f3d18 Iustin Pop
1973 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1974 d0c8c01d Iustin Pop
  command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
1975 858f3d18 Iustin Pop
1976 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
1977 858f3d18 Iustin Pop
1978 858f3d18 Iustin Pop
  if result.failed:
1979 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
1980 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1981 858f3d18 Iustin Pop
1982 858f3d18 Iustin Pop
1983 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1984 a8083063 Iustin Pop
  """Write a file to the filesystem.
1985 a8083063 Iustin Pop

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

1989 10c2650b Iustin Pop
  @type file_name: str
1990 10c2650b Iustin Pop
  @param file_name: the target file name
1991 10c2650b Iustin Pop
  @type data: str
1992 10c2650b Iustin Pop
  @param data: the new contents of the file
1993 10c2650b Iustin Pop
  @type mode: int
1994 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1995 9a914f7a René Nussbaumer
  @type uid: string
1996 9a914f7a René Nussbaumer
  @param uid: the owner of the file
1997 9a914f7a René Nussbaumer
  @type gid: string
1998 9a914f7a René Nussbaumer
  @param gid: the group of the file
1999 10c2650b Iustin Pop
  @type atime: float
2000 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2001 10c2650b Iustin Pop
  @type mtime: float
2002 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2003 c26a6bd2 Iustin Pop
  @rtype: None
2004 10c2650b Iustin Pop

2005 a8083063 Iustin Pop
  """
2006 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2007 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2008 a8083063 Iustin Pop
2009 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2010 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2011 2cc6781a Iustin Pop
          file_name)
2012 a8083063 Iustin Pop
2013 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2014 12bce260 Michael Hanselmann
2015 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2016 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2017 9a914f7a René Nussbaumer
2018 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2019 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2020 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2021 9a914f7a René Nussbaumer
2022 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2023 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2024 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2025 a8083063 Iustin Pop
2026 386b57af Iustin Pop
2027 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2028 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2029 b2f29800 René Nussbaumer

2030 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2031 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2032 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2033 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2034 b2f29800 René Nussbaumer

2035 b2f29800 René Nussbaumer
  @return: stdout
2036 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2037 b2f29800 René Nussbaumer

2038 b2f29800 René Nussbaumer
  """
2039 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2040 b2f29800 René Nussbaumer
2041 b2f29800 René Nussbaumer
  if result.failed:
2042 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2043 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2044 b2f29800 René Nussbaumer
2045 b2f29800 René Nussbaumer
  return result.stdout
2046 b2f29800 René Nussbaumer
2047 b2f29800 René Nussbaumer
2048 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
2049 89b14f05 Iustin Pop
  """Update all ssconf files.
2050 89b14f05 Iustin Pop

2051 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
2052 89b14f05 Iustin Pop

2053 89b14f05 Iustin Pop
  """
2054 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
2055 6ddc95ec Michael Hanselmann
2056 6ddc95ec Michael Hanselmann
2057 a8083063 Iustin Pop
def _ErrnoOrStr(err):
2058 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
2059 a8083063 Iustin Pop

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

2064 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
2065 10c2650b Iustin Pop
  @param err: the exception to format
2066 a8083063 Iustin Pop

2067 a8083063 Iustin Pop
  """
2068 d0c8c01d Iustin Pop
  if hasattr(err, "errno"):
2069 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
2070 a8083063 Iustin Pop
  else:
2071 a8083063 Iustin Pop
    detail = str(err)
2072 a8083063 Iustin Pop
  return detail
2073 a8083063 Iustin Pop
2074 5d0fe286 Iustin Pop
2075 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2076 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2077 a8083063 Iustin Pop

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

2081 10c2650b Iustin Pop
  @type os_dir: str
2082 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2083 8e70b181 Iustin Pop
  @rtype: tuple
2084 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2085 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2086 a8083063 Iustin Pop

2087 a8083063 Iustin Pop
  """
2088 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2089 a8083063 Iustin Pop
2090 a8083063 Iustin Pop
  try:
2091 a8083063 Iustin Pop
    st = os.stat(api_file)
2092 a8083063 Iustin Pop
  except EnvironmentError, err:
2093 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2094 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
2095 a8083063 Iustin Pop
2096 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2097 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2098 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2099 a8083063 Iustin Pop
2100 a8083063 Iustin Pop
  try:
2101 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2102 a8083063 Iustin Pop
  except EnvironmentError, err:
2103 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2104 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
2105 a8083063 Iustin Pop
2106 a8083063 Iustin Pop
  try:
2107 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2108 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2109 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2110 255dcebd Iustin Pop
                   str(err))
2111 a8083063 Iustin Pop
2112 255dcebd Iustin Pop
  return True, api_versions
2113 a8083063 Iustin Pop
2114 386b57af Iustin Pop
2115 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2116 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2117 a8083063 Iustin Pop

2118 10c2650b Iustin Pop
  @type top_dirs: list
2119 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2120 10c2650b Iustin Pop
      search (if not given defaults to
2121 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
2122 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2123 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2124 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2125 bad78e66 Iustin Pop
      search paths, where:
2126 255dcebd Iustin Pop
          - name is the (potential) OS name
2127 255dcebd Iustin Pop
          - path is the full path to the OS
2128 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2129 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2130 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2131 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2132 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2133 a8083063 Iustin Pop

2134 a8083063 Iustin Pop
  """
2135 7c3d51d4 Guido Trotter
  if top_dirs is None:
2136 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
2137 a8083063 Iustin Pop
2138 a8083063 Iustin Pop
  result = []
2139 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2140 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2141 7c3d51d4 Guido Trotter
      try:
2142 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2143 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2144 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2145 7c3d51d4 Guido Trotter
        break
2146 7c3d51d4 Guido Trotter
      for name in f_names:
2147 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2148 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2149 255dcebd Iustin Pop
        if status:
2150 255dcebd Iustin Pop
          diagnose = ""
2151 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2152 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2153 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2154 255dcebd Iustin Pop
        else:
2155 255dcebd Iustin Pop
          diagnose = os_inst
2156 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2157 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2158 bad78e66 Iustin Pop
                       parameters, api_versions))
2159 a8083063 Iustin Pop
2160 c26a6bd2 Iustin Pop
  return result
2161 a8083063 Iustin Pop
2162 a8083063 Iustin Pop
2163 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2164 a8083063 Iustin Pop
  """Create an OS instance from disk.
2165 a8083063 Iustin Pop

2166 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2167 8e70b181 Iustin Pop
  valid OS name.
2168 a8083063 Iustin Pop

2169 8ee4dc80 Guido Trotter
  @type base_dir: string
2170 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2171 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2172 255dcebd Iustin Pop
  @rtype: tuple
2173 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2174 255dcebd Iustin Pop
      or error message
2175 7c3d51d4 Guido Trotter

2176 a8083063 Iustin Pop
  """
2177 56bcd3f4 Guido Trotter
  if base_dir is None:
2178 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2179 c34c0cfd Iustin Pop
  else:
2180 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2181 f95c81bf Iustin Pop
2182 f95c81bf Iustin Pop
  if os_dir is None:
2183 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
2184 a8083063 Iustin Pop
2185 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2186 255dcebd Iustin Pop
  if not status:
2187 255dcebd Iustin Pop
    # push the error up
2188 255dcebd Iustin Pop
    return status, api_versions
2189 a8083063 Iustin Pop
2190 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2191 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2192 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2193 a8083063 Iustin Pop
2194 35007011 Iustin Pop
  # OS Files dictionary, we will populate it with the absolute path
2195 35007011 Iustin Pop
  # names; if the value is True, then it is a required file, otherwise
2196 35007011 Iustin Pop
  # an optional one
2197 35007011 Iustin Pop
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2198 a8083063 Iustin Pop
2199 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
2200 35007011 Iustin Pop
    os_files[constants.OS_VARIANTS_FILE] = False
2201 95075fba Guido Trotter
2202 c7d04a6b Iustin Pop
  if max(api_versions) >= constants.OS_API_V20:
2203 35007011 Iustin Pop
    os_files[constants.OS_PARAMETERS_FILE] = True
2204 c7d04a6b Iustin Pop
  else:
2205 c7d04a6b Iustin Pop
    del os_files[constants.OS_SCRIPT_VERIFY]
2206 c7d04a6b Iustin Pop
2207 35007011 Iustin Pop
  for (filename, required) in os_files.items():
2208 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
2209 a8083063 Iustin Pop
2210 a8083063 Iustin Pop
    try:
2211 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
2212 a8083063 Iustin Pop
    except EnvironmentError, err:
2213 35007011 Iustin Pop
      if err.errno == errno.ENOENT and not required:
2214 35007011 Iustin Pop
        del os_files[filename]
2215 35007011 Iustin Pop
        continue
2216 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
2217 ea79fc15 Michael Hanselmann
                     (filename, os_dir, _ErrnoOrStr(err)))
2218 a8083063 Iustin Pop
2219 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2220 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
2221 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
2222 255dcebd Iustin Pop
2223 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
2224 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2225 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
2226 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
2227 0757c107 Guido Trotter
2228 845da3e8 Iustin Pop
  variants = []
2229 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
2230 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2231 95075fba Guido Trotter
    try:
2232 95075fba Guido Trotter
      variants = utils.ReadFile(variants_file).splitlines()
2233 95075fba Guido Trotter
    except EnvironmentError, err:
2234 35007011 Iustin Pop
      # we accept missing files, but not other errors
2235 35007011 Iustin Pop
      if err.errno != errno.ENOENT:
2236 35007011 Iustin Pop
        return False, ("Error while reading the OS variants file at %s: %s" %
2237 35007011 Iustin Pop
                       (variants_file, _ErrnoOrStr(err)))
2238 0757c107 Guido Trotter
2239 c7d04a6b Iustin Pop
  parameters = []
2240 c7d04a6b Iustin Pop
  if constants.OS_PARAMETERS_FILE in os_files:
2241 c7d04a6b Iustin Pop
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2242 c7d04a6b Iustin Pop
    try:
2243 c7d04a6b Iustin Pop
      parameters = utils.ReadFile(parameters_file).splitlines()
2244 c7d04a6b Iustin Pop
    except EnvironmentError, err:
2245 c7d04a6b Iustin Pop
      return False, ("Error while reading the OS parameters file at %s: %s" %
2246 c7d04a6b Iustin Pop
                     (parameters_file, _ErrnoOrStr(err)))
2247 c7d04a6b Iustin Pop
    parameters = [v.split(None, 1) for v in parameters]
2248 c7d04a6b Iustin Pop
2249 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
2250 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2251 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2252 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2253 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2254 40684c3a Iustin Pop
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2255 40684c3a Iustin Pop
                                                 None),
2256 95075fba Guido Trotter
                      supported_variants=variants,
2257 c7d04a6b Iustin Pop
                      supported_parameters=parameters,
2258 255dcebd Iustin Pop
                      api_versions=api_versions)
2259 255dcebd Iustin Pop
  return True, os_obj
2260 255dcebd Iustin Pop
2261 255dcebd Iustin Pop
2262 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
2263 255dcebd Iustin Pop
  """Create an OS instance from disk.
2264 255dcebd Iustin Pop

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

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

2272 255dcebd Iustin Pop
  @type base_dir: string
2273 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2274 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2275 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2276 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2277 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2278 255dcebd Iustin Pop

2279 255dcebd Iustin Pop
  """
2280 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2281 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2282 255dcebd Iustin Pop
2283 255dcebd Iustin Pop
  if not status:
2284 255dcebd Iustin Pop
    _Fail(payload)
2285 a8083063 Iustin Pop
2286 255dcebd Iustin Pop
  return payload
2287 a8083063 Iustin Pop
2288 a8083063 Iustin Pop
2289 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2290 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2291 2266edb2 Guido Trotter

2292 a025e535 Vitaly Kuznetsov
  @type os_name: str
2293 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2294 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2295 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2296 1bdcbbab Iustin Pop
  @type os_params: dict
2297 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2298 2266edb2 Guido Trotter
  @type debug: integer
2299 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2300 2266edb2 Guido Trotter
  @rtype: dict
2301 2266edb2 Guido Trotter
  @return: dict of environment variables
2302 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2303 10c2650b Iustin Pop
      cannot be found
2304 2266edb2 Guido Trotter

2305 2266edb2 Guido Trotter
  """
2306 2266edb2 Guido Trotter
  result = {}
2307 099c52ad Iustin Pop
  api_version = \
2308 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2309 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2310 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2311 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2312 efaa9b06 Iustin Pop
2313 efaa9b06 Iustin Pop
  # OS variants
2314 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2315 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2316 870dc44c Iustin Pop
    if not variant:
2317 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2318 35007011 Iustin Pop
  else:
2319 35007011 Iustin Pop
    variant = ""
2320 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2321 efaa9b06 Iustin Pop
2322 1bdcbbab Iustin Pop
  # OS params
2323 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2324 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2325 1bdcbbab Iustin Pop
2326 efaa9b06 Iustin Pop
  return result
2327 efaa9b06 Iustin Pop
2328 efaa9b06 Iustin Pop
2329 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2330 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2331 efaa9b06 Iustin Pop

2332 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2333 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2334 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2335 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2336 efaa9b06 Iustin Pop
  @type debug: integer
2337 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2338 efaa9b06 Iustin Pop
  @rtype: dict
2339 efaa9b06 Iustin Pop
  @return: dict of environment variables
2340 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2341 efaa9b06 Iustin Pop
      cannot be found
2342 efaa9b06 Iustin Pop

2343 efaa9b06 Iustin Pop
  """
2344 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2345 efaa9b06 Iustin Pop
2346 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2347 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2348 f2165b8a Iustin Pop
2349 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2350 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2351 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2352 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2353 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2354 efaa9b06 Iustin Pop
2355 efaa9b06 Iustin Pop
  # Disks
2356 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2357 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2358 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2359 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2360 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2361 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2362 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2363 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2364 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2365 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2366 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2367 d0c8c01d Iustin Pop
        "file:%s" % disk.physical_id[0]
2368 efaa9b06 Iustin Pop
2369 efaa9b06 Iustin Pop
  # NICs
2370 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2371 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2372 2266edb2 Guido Trotter
    if nic.ip:
2373 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2374 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2375 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2376 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2377 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2378 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2379 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2380 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2381 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2382 2266edb2 Guido Trotter
2383 efaa9b06 Iustin Pop
  # HV/BE params
2384 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2385 67fc3042 Iustin Pop
    for key, value in source.items():
2386 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2387 67fc3042 Iustin Pop
2388 2266edb2 Guido Trotter
  return result
2389 a8083063 Iustin Pop
2390 f2e07bb4 Michael Hanselmann
2391 a59faf4b Iustin Pop
def BlockdevGrow(disk, amount, dryrun):
2392 594609c0 Iustin Pop
  """Grow a stack of block devices.
2393 594609c0 Iustin Pop

2394 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2395 10c2650b Iustin Pop
  first ones to resize.
2396 594609c0 Iustin Pop

2397 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2398 10c2650b Iustin Pop
  @param disk: the disk to be grown
2399 a59faf4b Iustin Pop
  @type amount: integer
2400 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2401 a59faf4b Iustin Pop
  @type dryrun: boolean
2402 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2403 a59faf4b Iustin Pop
      only, without actually increasing the size
2404 10c2650b Iustin Pop
  @rtype: (status, result)
2405 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2406 a59faf4b Iustin Pop
      the errors message if status is False
2407 594609c0 Iustin Pop

2408 594609c0 Iustin Pop
  """
2409 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2410 594609c0 Iustin Pop
  if r_dev is None:
2411 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2412 594609c0 Iustin Pop
2413 594609c0 Iustin Pop
  try:
2414 a59faf4b Iustin Pop
    r_dev.Grow(amount, dryrun)
2415 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2416 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2417 594609c0 Iustin Pop
2418 594609c0 Iustin Pop
2419 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2420 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2421 a8083063 Iustin Pop

2422 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2423 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2424 a8083063 Iustin Pop

2425 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2426 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2427 e9e9263d Guido Trotter
  @rtype: string
2428 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2429 a8083063 Iustin Pop

2430 098c0958 Michael Hanselmann
  """
2431 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2432 433c63aa Iustin Pop
    if not disk.children:
2433 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2434 433c63aa Iustin Pop
            disk.unique_id)
2435 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2436 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2437 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2438 a8083063 Iustin Pop
    if r_dev is not None:
2439 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2440 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2441 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2442 a8083063 Iustin Pop
    else:
2443 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2444 a8083063 Iustin Pop
  else:
2445 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2446 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2447 a8083063 Iustin Pop
2448 a8083063 Iustin Pop
2449 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2450 a8083063 Iustin Pop
  """Write out the export configuration information.
2451 a8083063 Iustin Pop

2452 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2453 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2454 10c2650b Iustin Pop
      saving configuration
2455 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2456 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2457 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2458 a8083063 Iustin Pop

2459 c26a6bd2 Iustin Pop
  @rtype: None
2460 a8083063 Iustin Pop

2461 098c0958 Michael Hanselmann
  """
2462 c4feafe8 Iustin Pop
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2463 c4feafe8 Iustin Pop
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2464 a8083063 Iustin Pop
2465 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2466 a8083063 Iustin Pop
2467 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2468 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
2469 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2470 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2471 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
2472 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2473 a8083063 Iustin Pop
2474 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2475 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
2476 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
2477 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
2478 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2479 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2480 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2481 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2482 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2483 66f93869 Manuel Franceschini
2484 95268cc3 Iustin Pop
  nic_total = 0
2485 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2486 95268cc3 Iustin Pop
    nic_total += 1
2487 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
2488 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
2489 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2490 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2491 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2492 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
2493 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2494 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2495 a8083063 Iustin Pop
2496 726d7d68 Iustin Pop
  disk_total = 0
2497 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2498 19d7f90a Guido Trotter
    if disk:
2499 726d7d68 Iustin Pop
      disk_total += 1
2500 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2501 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
2502 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2503 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
2504 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2505 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
2506 d0c8c01d Iustin Pop
2507 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2508 a8083063 Iustin Pop
2509 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2510 3c8954ad Iustin Pop
2511 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2512 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2513 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2514 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2515 3c8954ad Iustin Pop
2516 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2517 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2518 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2519 3c8954ad Iustin Pop
2520 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2521 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2522 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2523 535b49cb Iustin Pop
2524 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2525 726d7d68 Iustin Pop
                  data=config.Dumps())
2526 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2527 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2528 a8083063 Iustin Pop
2529 a8083063 Iustin Pop
2530 a8083063 Iustin Pop
def ExportInfo(dest):
2531 a8083063 Iustin Pop
  """Get export configuration information.
2532 a8083063 Iustin Pop

2533 10c2650b Iustin Pop
  @type dest: str
2534 10c2650b Iustin Pop
  @param dest: directory containing the export
2535 a8083063 Iustin Pop

2536 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2537 10c2650b Iustin Pop
  @return: a serializable config file containing the
2538 10c2650b Iustin Pop
      export info
2539 a8083063 Iustin Pop

2540 a8083063 Iustin Pop
  """
2541 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2542 a8083063 Iustin Pop
2543 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2544 a8083063 Iustin Pop
  config.read(cff)
2545 a8083063 Iustin Pop
2546 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2547 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2548 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2549 a8083063 Iustin Pop
2550 c26a6bd2 Iustin Pop
  return config.Dumps()
2551 a8083063 Iustin Pop
2552 a8083063 Iustin Pop
2553 a8083063 Iustin Pop
def ListExports():
2554 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2555 098c0958 Michael Hanselmann

2556 10c2650b Iustin Pop
  @rtype: list
2557 10c2650b Iustin Pop
  @return: list of the exports
2558 10c2650b Iustin Pop

2559 a8083063 Iustin Pop
  """
2560 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
2561 b5b8309d Guido Trotter
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2562 a8083063 Iustin Pop
  else:
2563 afdc3985 Iustin Pop
    _Fail("No exports directory")
2564 a8083063 Iustin Pop
2565 a8083063 Iustin Pop
2566 a8083063 Iustin Pop
def RemoveExport(export):
2567 a8083063 Iustin Pop
  """Remove an existing export from the node.
2568 a8083063 Iustin Pop

2569 10c2650b Iustin Pop
  @type export: str
2570 10c2650b Iustin Pop
  @param export: the name of the export to remove
2571 c26a6bd2 Iustin Pop
  @rtype: None
2572 a8083063 Iustin Pop

2573 098c0958 Michael Hanselmann
  """
2574 c4feafe8 Iustin Pop
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2575 a8083063 Iustin Pop
2576 35fbcd11 Iustin Pop
  try:
2577 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2578 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2579 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2580 a8083063 Iustin Pop
2581 a8083063 Iustin Pop
2582 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2583 f3e513ad Iustin Pop
  """Rename a list of block devices.
2584 f3e513ad Iustin Pop

2585 10c2650b Iustin Pop
  @type devlist: list of tuples
2586 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2587 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2588 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2589 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2590 10c2650b Iustin Pop
      rename it to
2591 10c2650b Iustin Pop
  @rtype: boolean
2592 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2593 f3e513ad Iustin Pop

2594 f3e513ad Iustin Pop
  """
2595 6b5e3f70 Iustin Pop
  msgs = []
2596 f3e513ad Iustin Pop
  result = True
2597 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2598 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2599 f3e513ad Iustin Pop
    if dev is None:
2600 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2601 f3e513ad Iustin Pop
      result = False
2602 f3e513ad Iustin Pop
      continue
2603 f3e513ad Iustin Pop
    try:
2604 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2605 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2606 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2607 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2608 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2609 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2610 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2611 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2612 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2613 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2614 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2615 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2616 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2617 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2618 f3e513ad Iustin Pop
      result = False
2619 afdc3985 Iustin Pop
  if not result:
2620 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2621 f3e513ad Iustin Pop
2622 f3e513ad Iustin Pop
2623 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2624 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2625 778b75bb Manuel Franceschini

2626 4b97f902 Apollon Oikonomopoulos
  Checks wheter the given fs_dir is within the cluster-wide default
2627 4b97f902 Apollon Oikonomopoulos
  file_storage_dir or the shared_file_storage_dir, which are stored in
2628 4b97f902 Apollon Oikonomopoulos
  SimpleStore. Only paths under those directories are allowed.
2629 778b75bb Manuel Franceschini

2630 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2631 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2632 d61cbe76 Iustin Pop

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

2635 778b75bb Manuel Franceschini
  """
2636 cb7c0198 Iustin Pop
  if not constants.ENABLE_FILE_STORAGE:
2637 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2638 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2639 4b97f902 Apollon Oikonomopoulos
  fs_dir = os.path.normpath(fs_dir)
2640 4b97f902 Apollon Oikonomopoulos
  base_fstore = cfg.GetFileStorageDir()
2641 4b97f902 Apollon Oikonomopoulos
  base_shared = cfg.GetSharedFileStorageDir()
2642 cf00dba0 René Nussbaumer
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2643 cf00dba0 René Nussbaumer
          utils.IsBelowDir(base_shared, fs_dir)):
2644 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2645 4b97f902 Apollon Oikonomopoulos
          " storage directory '%s' or shared storage directory '%s'",
2646 4b97f902 Apollon Oikonomopoulos
          fs_dir, base_fstore, base_shared)
2647 4b97f902 Apollon Oikonomopoulos
  return fs_dir
2648 778b75bb Manuel Franceschini
2649 778b75bb Manuel Franceschini
2650 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2651 778b75bb Manuel Franceschini
  """Create file storage directory.
2652 778b75bb Manuel Franceschini

2653 b1206984 Iustin Pop
  @type file_storage_dir: str
2654 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2655 778b75bb Manuel Franceschini

2656 b1206984 Iustin Pop
  @rtype: tuple
2657 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2658 b1206984 Iustin Pop
      creation was successful or not
2659 778b75bb Manuel Franceschini

2660 778b75bb Manuel Franceschini
  """
2661 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2662 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2663 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2664 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2665 b2b8bcce Iustin Pop
            file_storage_dir)
2666 778b75bb Manuel Franceschini
  else:
2667 b2b8bcce Iustin Pop
    try:
2668 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2669 b2b8bcce Iustin Pop
    except OSError, err:
2670 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2671 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2672 778b75bb Manuel Franceschini
2673 778b75bb Manuel Franceschini
2674 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2675 778b75bb Manuel Franceschini
  """Remove file storage directory.
2676 778b75bb Manuel Franceschini

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

2679 10c2650b Iustin Pop
  @type file_storage_dir: str
2680 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2681 10c2650b Iustin Pop
  @rtype: tuple (success,)
2682 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2683 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2684 778b75bb Manuel Franceschini

2685 778b75bb Manuel Franceschini
  """
2686 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2687 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2688 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2689 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2690 b2b8bcce Iustin Pop
            file_storage_dir)
2691 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2692 b2b8bcce Iustin Pop
    try:
2693 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2694 b2b8bcce Iustin Pop
    except OSError, err:
2695 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2696 b2b8bcce Iustin Pop
            file_storage_dir, err)
2697 b2b8bcce Iustin Pop
2698 778b75bb Manuel Franceschini
2699 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2700 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2701 778b75bb Manuel Franceschini

2702 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2703 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2704 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2705 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2706 10c2650b Iustin Pop
  @rtype: tuple (success,)
2707 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2708 10c2650b Iustin Pop
      whether the operation was successful
2709 778b75bb Manuel Franceschini

2710 778b75bb Manuel Franceschini
  """
2711 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2712 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2713 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2714 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2715 b2b8bcce Iustin Pop
      try:
2716 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2717 b2b8bcce Iustin Pop
      except OSError, err:
2718 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2719 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2720 778b75bb Manuel Franceschini
    else:
2721 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2722 b2b8bcce Iustin Pop
            old_file_storage_dir)
2723 b2b8bcce Iustin Pop
  else:
2724 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2725 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2726 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2727 778b75bb Manuel Franceschini
2728 778b75bb Manuel Franceschini
2729 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2730 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2731 ca52cdeb Michael Hanselmann

2732 10c2650b Iustin Pop
  @type file_name: str
2733 10c2650b Iustin Pop
  @param file_name: the file name we should check
2734 c8457ce7 Iustin Pop
  @rtype: None
2735 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2736 10c2650b Iustin Pop

2737 ca52cdeb Michael Hanselmann
  """
2738 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2739 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2740 dc31eae3 Michael Hanselmann
2741 dc31eae3 Michael Hanselmann
  if not result:
2742 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2743 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2744 dc31eae3 Michael Hanselmann
2745 dc31eae3 Michael Hanselmann
2746 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2747 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2748 dc31eae3 Michael Hanselmann

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

2752 10c2650b Iustin Pop
  @type file_name: str
2753 10c2650b Iustin Pop
  @param file_name: the job file name
2754 10c2650b Iustin Pop
  @type content: str
2755 10c2650b Iustin Pop
  @param content: the new job contents
2756 10c2650b Iustin Pop
  @rtype: boolean
2757 10c2650b Iustin Pop
  @return: the success of the operation
2758 10c2650b Iustin Pop

2759 dc31eae3 Michael Hanselmann
  """
2760 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2761 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2762 ca52cdeb Michael Hanselmann
2763 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2764 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2765 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2766 ca52cdeb Michael Hanselmann
2767 ca52cdeb Michael Hanselmann
2768 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2769 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2770 af5ebcb1 Michael Hanselmann

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

2773 10c2650b Iustin Pop
  @type old: str
2774 10c2650b Iustin Pop
  @param old: the old (actual) file name
2775 10c2650b Iustin Pop
  @type new: str
2776 10c2650b Iustin Pop
  @param new: the desired file name
2777 c8457ce7 Iustin Pop
  @rtype: tuple
2778 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2779 10c2650b Iustin Pop

2780 af5ebcb1 Michael Hanselmann
  """
2781 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2782 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2783 af5ebcb1 Michael Hanselmann
2784 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
2785 8e5a705d René Nussbaumer
2786 8e5a705d René Nussbaumer
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2787 8e5a705d René Nussbaumer
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2788 af5ebcb1 Michael Hanselmann
2789 af5ebcb1 Michael Hanselmann
2790 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2791 d61cbe76 Iustin Pop
  """Closes the given block devices.
2792 d61cbe76 Iustin Pop

2793 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2794 10c2650b Iustin Pop
  DRBD).
2795 10c2650b Iustin Pop

2796 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2797 b2e7666a Iustin Pop
      of this instance will be removed
2798 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2799 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2800 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2801 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2802 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2803 10c2650b Iustin Pop
      which will contain the error details in case we
2804 10c2650b Iustin Pop
      failed
2805 d61cbe76 Iustin Pop

2806 d61cbe76 Iustin Pop
  """
2807 d61cbe76 Iustin Pop
  bdevs = []
2808 d61cbe76 Iustin Pop
  for cf in disks:
2809 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2810 d61cbe76 Iustin Pop
    if rd is None:
2811 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2812 d61cbe76 Iustin Pop
    bdevs.append(rd)
2813 d61cbe76 Iustin Pop
2814 d61cbe76 Iustin Pop
  msg = []
2815 d61cbe76 Iustin Pop
  for rd in bdevs:
2816 d61cbe76 Iustin Pop
    try:
2817 d61cbe76 Iustin Pop
      rd.Close()
2818 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2819 d61cbe76 Iustin Pop
      msg.append(str(err))
2820 d61cbe76 Iustin Pop
  if msg:
2821 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2822 d61cbe76 Iustin Pop
  else:
2823 b2e7666a Iustin Pop
    if instance_name:
2824 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2825 d61cbe76 Iustin Pop
2826 d61cbe76 Iustin Pop
2827 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2828 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2829 6217e295 Iustin Pop

2830 6217e295 Iustin Pop
  @type hvname: string
2831 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2832 6217e295 Iustin Pop
  @type hvparams: dict
2833 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2834 c26a6bd2 Iustin Pop
  @rtype: None
2835 6217e295 Iustin Pop

2836 6217e295 Iustin Pop
  """
2837 6217e295 Iustin Pop
  try:
2838 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2839 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2840 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2841 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2842 6217e295 Iustin Pop
2843 6217e295 Iustin Pop
2844 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
2845 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
2846 acd9ff9e Iustin Pop

2847 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
2848 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
2849 acd9ff9e Iustin Pop
  @type parameters: list
2850 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
2851 acd9ff9e Iustin Pop

2852 acd9ff9e Iustin Pop
  """
2853 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
2854 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
2855 acd9ff9e Iustin Pop
  if delta:
2856 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
2857 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2858 acd9ff9e Iustin Pop
2859 acd9ff9e Iustin Pop
2860 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
2861 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
2862 acd9ff9e Iustin Pop

2863 acd9ff9e Iustin Pop
  @type required: boolean
2864 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
2865 acd9ff9e Iustin Pop
      failure or not
2866 acd9ff9e Iustin Pop
  @type osname: string
2867 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
2868 acd9ff9e Iustin Pop
  @type checks: list
2869 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
2870 acd9ff9e Iustin Pop
  @type osparams: dict
2871 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
2872 acd9ff9e Iustin Pop
  @rtype: boolean
2873 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
2874 acd9ff9e Iustin Pop
      found and L{required} was false
2875 acd9ff9e Iustin Pop

2876 acd9ff9e Iustin Pop
  """
2877 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2878 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
2879 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2880 acd9ff9e Iustin Pop
2881 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
2882 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
2883 acd9ff9e Iustin Pop
2884 acd9ff9e Iustin Pop
  if not status:
2885 acd9ff9e Iustin Pop
    if required:
2886 acd9ff9e Iustin Pop
      _Fail(tbv)
2887 acd9ff9e Iustin Pop
    else:
2888 acd9ff9e Iustin Pop
      return False
2889 acd9ff9e Iustin Pop
2890 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
2891 72db3fd7 Iustin Pop
    return True
2892 72db3fd7 Iustin Pop
2893 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
2894 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
2895 acd9ff9e Iustin Pop
2896 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
2897 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2898 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
2899 acd9ff9e Iustin Pop
  if result.failed:
2900 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
2901 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
2902 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
2903 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
2904 acd9ff9e Iustin Pop
2905 acd9ff9e Iustin Pop
  return True
2906 acd9ff9e Iustin Pop
2907 acd9ff9e Iustin Pop
2908 56aa9fd5 Iustin Pop
def DemoteFromMC():
2909 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2910 56aa9fd5 Iustin Pop

2911 56aa9fd5 Iustin Pop
  """
2912 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2913 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2914 56aa9fd5 Iustin Pop
  if master == myself:
2915 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2916 f154a7a3 Michael Hanselmann
2917 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2918 f154a7a3 Michael Hanselmann
  if not result.failed:
2919 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2920 f154a7a3 Michael Hanselmann
2921 56aa9fd5 Iustin Pop
  try:
2922 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2923 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2924 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2925 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2926 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2927 f154a7a3 Michael Hanselmann
2928 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2929 56aa9fd5 Iustin Pop
2930 56aa9fd5 Iustin Pop
2931 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
2932 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
2933 f942a838 Michael Hanselmann

2934 f942a838 Michael Hanselmann
  """
2935 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
2936 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2937 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2938 f942a838 Michael Hanselmann
2939 f942a838 Michael Hanselmann
2940 f942a838 Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2941 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
2942 f942a838 Michael Hanselmann

2943 f942a838 Michael Hanselmann
  @type validity: int
2944 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
2945 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
2946 f942a838 Michael Hanselmann
  @return: Certificate name and public part
2947 f942a838 Michael Hanselmann

2948 f942a838 Michael Hanselmann
  """
2949 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
2950 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2951 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2952 f942a838 Michael Hanselmann
2953 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2954 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
2955 f942a838 Michael Hanselmann
  try:
2956 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
2957 f942a838 Michael Hanselmann
    assert len(name) > 5
2958 f942a838 Michael Hanselmann
2959 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2960 f942a838 Michael Hanselmann
2961 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2962 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2963 f942a838 Michael Hanselmann
2964 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
2965 f942a838 Michael Hanselmann
    return (name, cert_pem)
2966 f942a838 Michael Hanselmann
  except Exception:
2967 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
2968 f942a838 Michael Hanselmann
    raise
2969 f942a838 Michael Hanselmann
2970 f942a838 Michael Hanselmann
2971 f942a838 Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2972 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
2973 f942a838 Michael Hanselmann

2974 f942a838 Michael Hanselmann
  @type name: string
2975 f942a838 Michael Hanselmann
  @param name: Certificate name
2976 f942a838 Michael Hanselmann

2977 f942a838 Michael Hanselmann
  """
2978 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2979 f942a838 Michael Hanselmann
2980 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
2981 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
2982 f942a838 Michael Hanselmann
2983 f942a838 Michael Hanselmann
  try:
2984 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
2985 f942a838 Michael Hanselmann
  except EnvironmentError, err:
2986 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
2987 f942a838 Michael Hanselmann
          cert_dir, err)
2988 f942a838 Michael Hanselmann
2989 f942a838 Michael Hanselmann
2990 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2991 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
2992 1651d116 Michael Hanselmann

2993 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
2994 1651d116 Michael Hanselmann
  @param instance: The instance object
2995 1651d116 Michael Hanselmann
  @param mode: Import/export mode
2996 1651d116 Michael Hanselmann
  @param ieio: Input/output type
2997 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
2998 1651d116 Michael Hanselmann

2999 1651d116 Michael Hanselmann
  """
3000 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3001 1651d116 Michael Hanselmann
3002 1651d116 Michael Hanselmann
  env = None
3003 1651d116 Michael Hanselmann
  prefix = None
3004 1651d116 Michael Hanselmann
  suffix = None
3005 2ad5550d Michael Hanselmann
  exp_size = None
3006 1651d116 Michael Hanselmann
3007 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
3008 1651d116 Michael Hanselmann
    (filename, ) = ieargs
3009 1651d116 Michael Hanselmann
3010 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
3011 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
3012 1651d116 Michael Hanselmann
3013 748c9884 René Nussbaumer
    real_filename = os.path.realpath(filename)
3014 748c9884 René Nussbaumer
    directory = os.path.dirname(real_filename)
3015 1651d116 Michael Hanselmann
3016 945859e0 René Nussbaumer
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
3017 748c9884 René Nussbaumer
      _Fail("File '%s' is not under exports directory '%s': %s",
3018 748c9884 René Nussbaumer
            filename, constants.EXPORT_DIR, real_filename)
3019 1651d116 Michael Hanselmann
3020 1651d116 Michael Hanselmann
    # Create directory
3021 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
3022 1651d116 Michael Hanselmann
3023 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
3024 1651d116 Michael Hanselmann
3025 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3026 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
3027 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3028 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
3029 1651d116 Michael Hanselmann
3030 2ad5550d Michael Hanselmann
      # Retrieve file size
3031 2ad5550d Michael Hanselmann
      try:
3032 2ad5550d Michael Hanselmann
        st = os.stat(filename)
3033 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
3034 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
3035 2ad5550d Michael Hanselmann
      else:
3036 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
3037 2ad5550d Michael Hanselmann
3038 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
3039 1651d116 Michael Hanselmann
    (disk, ) = ieargs
3040 1651d116 Michael Hanselmann
3041 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3042 1651d116 Michael Hanselmann
3043 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3044 1651d116 Michael Hanselmann
      # we set here a smaller block size as, due to transport buffering, more
3045 1651d116 Michael Hanselmann
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3046 1651d116 Michael Hanselmann
      # is not already there or we pass a wrong path; we use notrunc to no
3047 1651d116 Michael Hanselmann
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3048 1651d116 Michael Hanselmann
      # much memory; this means that at best, we flush every 64k, which will
3049 1651d116 Michael Hanselmann
      # not be very fast
3050 1651d116 Michael Hanselmann
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3051 1651d116 Michael Hanselmann
                                    " bs=%s oflag=dsync"),
3052 1651d116 Michael Hanselmann
                                    real_disk.dev_path,
3053 1651d116 Michael Hanselmann
                                    str(64 * 1024))
3054 1651d116 Michael Hanselmann
3055 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3056 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
3057 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3058 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
3059 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
3060 1651d116 Michael Hanselmann
                                   str(disk.size))
3061 2ad5550d Michael Hanselmann
      exp_size = disk.size
3062 1651d116 Michael Hanselmann
3063 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
3064 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
3065 1651d116 Michael Hanselmann
3066 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
3067 1651d116 Michael Hanselmann
3068 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3069 1651d116 Michael Hanselmann
3070 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
3071 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
3072 1651d116 Michael Hanselmann
3073 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3074 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3075 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
3076 1651d116 Michael Hanselmann
      script = inst_os.import_script
3077 1651d116 Michael Hanselmann
3078 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3079 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
3080 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
3081 1651d116 Michael Hanselmann
      script = inst_os.export_script
3082 1651d116 Michael Hanselmann
3083 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
3084 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3085 1651d116 Michael Hanselmann
3086 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3087 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
3088 1651d116 Michael Hanselmann
3089 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3090 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
3091 1651d116 Michael Hanselmann
3092 2ad5550d Michael Hanselmann
    # Let script predict size
3093 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
3094 2ad5550d Michael Hanselmann
3095 1651d116 Michael Hanselmann
  else:
3096 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3097 1651d116 Michael Hanselmann
3098 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
3099 1651d116 Michael Hanselmann
3100 1651d116 Michael Hanselmann
3101 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
3102 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
3103 1651d116 Michael Hanselmann

3104 1651d116 Michael Hanselmann
  """
3105 1651d116 Michael Hanselmann
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3106 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3107 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3108 1651d116 Michael Hanselmann
3109 1651d116 Michael Hanselmann
3110 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3111 6613661a Iustin Pop
                            ieio, ieioargs):
3112 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3113 1651d116 Michael Hanselmann

3114 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3115 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3116 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3117 1651d116 Michael Hanselmann
  @type host: string
3118 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3119 1651d116 Michael Hanselmann
  @type port: int
3120 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3121 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3122 1651d116 Michael Hanselmann
  @param instance: Instance object
3123 6613661a Iustin Pop
  @type component: string
3124 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3125 6613661a Iustin Pop
      e.g. 'disk/0'
3126 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3127 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3128 1651d116 Michael Hanselmann

3129 1651d116 Michael Hanselmann
  """
3130 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
3131 1651d116 Michael Hanselmann
    prefix = "import"
3132 1651d116 Michael Hanselmann
3133 1651d116 Michael Hanselmann
    if not (host is None and port is None):
3134 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
3135 1651d116 Michael Hanselmann
3136 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
3137 1651d116 Michael Hanselmann
    prefix = "export"
3138 1651d116 Michael Hanselmann
3139 1651d116 Michael Hanselmann
    if host is None or port is None:
3140 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
3141 1651d116 Michael Hanselmann
3142 1651d116 Michael Hanselmann
  else:
3143 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
3144 1651d116 Michael Hanselmann
3145 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
3146 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
3147 1651d116 Michael Hanselmann
3148 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3149 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3150 1651d116 Michael Hanselmann
3151 eb630f50 Michael Hanselmann
  if opts.key_name is None:
3152 1651d116 Michael Hanselmann
    # Use server.pem
3153 1651d116 Michael Hanselmann
    key_path = constants.NODED_CERT_FILE
3154 1651d116 Michael Hanselmann
    cert_path = constants.NODED_CERT_FILE
3155 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
3156 1651d116 Michael Hanselmann
  else:
3157 1651d116 Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3158 eb630f50 Michael Hanselmann
                                                 opts.key_name)
3159 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
3160 1651d116 Michael Hanselmann
3161 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
3162 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
3163 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
3164 63bcea2a Michael Hanselmann
3165 6613661a Iustin Pop
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3166 1651d116 Michael Hanselmann
  try:
3167 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3168 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3169 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3170 1651d116 Michael Hanselmann
3171 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
3172 1651d116 Michael Hanselmann
      # Use server.pem
3173 63bcea2a Michael Hanselmann
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3174 eb630f50 Michael Hanselmann
    else:
3175 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
3176 63bcea2a Michael Hanselmann
3177 eb630f50 Michael Hanselmann
    # Write CA file
3178 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
3179 1651d116 Michael Hanselmann
3180 1651d116 Michael Hanselmann
    cmd = [
3181 1651d116 Michael Hanselmann
      constants.IMPORT_EXPORT_DAEMON,
3182 1651d116 Michael Hanselmann
      status_file, mode,
3183 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
3184 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
3185 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
3186 1651d116 Michael Hanselmann
      ]
3187 1651d116 Michael Hanselmann
3188 1651d116 Michael Hanselmann
    if host:
3189 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
3190 1651d116 Michael Hanselmann
3191 1651d116 Michael Hanselmann
    if port:
3192 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
3193 1651d116 Michael Hanselmann
3194 855d2fc7 Michael Hanselmann
    if opts.ipv6:
3195 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
3196 855d2fc7 Michael Hanselmann
    else:
3197 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
3198 855d2fc7 Michael Hanselmann
3199 a5310c2a Michael Hanselmann
    if opts.compress:
3200 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
3201 a5310c2a Michael Hanselmann
3202 af1d39b1 Michael Hanselmann
    if opts.magic:
3203 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
3204 af1d39b1 Michael Hanselmann
3205 2ad5550d Michael Hanselmann
    if exp_size is not None:
3206 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
3207 2ad5550d Michael Hanselmann
3208 1651d116 Michael Hanselmann
    if cmd_prefix:
3209 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3210 1651d116 Michael Hanselmann
3211 1651d116 Michael Hanselmann
    if cmd_suffix:
3212 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3213 1651d116 Michael Hanselmann
3214 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
3215 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
3216 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3217 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3218 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
3219 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
3220 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
3221 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3222 4478301b Michael Hanselmann
3223 6aa7a354 Iustin Pop
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3224 1651d116 Michael Hanselmann
3225 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3226 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
3227 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3228 1651d116 Michael Hanselmann
                      output=logfile)
3229 1651d116 Michael Hanselmann
3230 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
3231 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
3232 1651d116 Michael Hanselmann
3233 1651d116 Michael Hanselmann
  except Exception:
3234 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
3235 1651d116 Michael Hanselmann
    raise
3236 1651d116 Michael Hanselmann
3237 1651d116 Michael Hanselmann
3238 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
3239 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
3240 1651d116 Michael Hanselmann

3241 1651d116 Michael Hanselmann
  @type names: sequence
3242 1651d116 Michael Hanselmann
  @param names: List of names
3243 1651d116 Michael Hanselmann
  @rtype: List of dicts
3244 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3245 1651d116 Michael Hanselmann
           status couldn't be read
3246 1651d116 Michael Hanselmann

3247 1651d116 Michael Hanselmann
  """
3248 1651d116 Michael Hanselmann
  result = []
3249 1651d116 Michael Hanselmann
3250 1651d116 Michael Hanselmann
  for name in names:
3251 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3252 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3253 1651d116 Michael Hanselmann
3254 1651d116 Michael Hanselmann
    try:
3255 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3256 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3257 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3258 1651d116 Michael Hanselmann
        raise
3259 1651d116 Michael Hanselmann
      data = None
3260 1651d116 Michael Hanselmann
3261 1651d116 Michael Hanselmann
    if not data:
3262 1651d116 Michael Hanselmann
      result.append(None)
3263 1651d116 Michael Hanselmann
      continue
3264 1651d116 Michael Hanselmann
3265 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3266 1651d116 Michael Hanselmann
3267 1651d116 Michael Hanselmann
  return result
3268 1651d116 Michael Hanselmann
3269 1651d116 Michael Hanselmann
3270 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3271 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3272 f81c4737 Michael Hanselmann

3273 f81c4737 Michael Hanselmann
  """
3274 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3275 f81c4737 Michael Hanselmann
3276 f81c4737 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3277 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3278 f81c4737 Michael Hanselmann
3279 f81c4737 Michael Hanselmann
  if pid:
3280 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3281 f81c4737 Michael Hanselmann
                 name, pid)
3282 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3283 f81c4737 Michael Hanselmann
3284 f81c4737 Michael Hanselmann
3285 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3286 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3287 1651d116 Michael Hanselmann

3288 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3289 1651d116 Michael Hanselmann
  whole status directory is removed.
3290 1651d116 Michael Hanselmann

3291 1651d116 Michael Hanselmann
  """
3292 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3293 1651d116 Michael Hanselmann
3294 1651d116 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3295 1651d116 Michael Hanselmann
3296 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3297 1651d116 Michael Hanselmann
3298 1651d116 Michael Hanselmann
  if pid:
3299 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3300 1651d116 Michael Hanselmann
                 name, pid)
3301 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3302 1651d116 Michael Hanselmann
3303 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3304 1651d116 Michael Hanselmann
3305 1651d116 Michael Hanselmann
3306 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3307 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3308 6b93ec9d Iustin Pop

3309 6b93ec9d Iustin Pop
  """
3310 6b93ec9d Iustin Pop
  # set the correct physical ID
3311 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3312 6b93ec9d Iustin Pop
  for cf in disks:
3313 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3314 6b93ec9d Iustin Pop
3315 6b93ec9d Iustin Pop
  bdevs = []
3316 6b93ec9d Iustin Pop
3317 6b93ec9d Iustin Pop
  for cf in disks:
3318 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3319 6b93ec9d Iustin Pop
    if rd is None:
3320 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3321 6b93ec9d Iustin Pop
    bdevs.append(rd)
3322 5a533f8a Iustin Pop
  return bdevs
3323 6b93ec9d Iustin Pop
3324 6b93ec9d Iustin Pop
3325 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3326 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3327 6b93ec9d Iustin Pop

3328 6b93ec9d Iustin Pop
  """
3329 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3330 6b93ec9d Iustin Pop
3331 6b93ec9d Iustin Pop
  # disconnect disks
3332 6b93ec9d Iustin Pop
  for rd in bdevs:
3333 6b93ec9d Iustin Pop
    try:
3334 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3335 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3336 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3337 2cc6781a Iustin Pop
            err, exc=True)
3338 6b93ec9d Iustin Pop
3339 6b93ec9d Iustin Pop
3340 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3341 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3342 6b93ec9d Iustin Pop

3343 6b93ec9d Iustin Pop
  """
3344 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3345 6b93ec9d Iustin Pop
3346 6b93ec9d Iustin Pop
  if multimaster:
3347 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3348 6b93ec9d Iustin Pop
      try:
3349 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3350 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3351 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3352 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3353 6b93ec9d Iustin Pop
  # needed primary mode
3354 6b93ec9d Iustin Pop
  for rd in bdevs:
3355 6b93ec9d Iustin Pop
    try:
3356 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3357 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3358 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3359 3c0cdc83 Michael Hanselmann
3360 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3361 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3362 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3363 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3364 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3365 3c0cdc83 Michael Hanselmann
3366 3c0cdc83 Michael Hanselmann
  def _Attach():
3367 6b93ec9d Iustin Pop
    all_connected = True
3368 3c0cdc83 Michael Hanselmann
3369 6b93ec9d Iustin Pop
    for rd in bdevs:
3370 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3371 3c0cdc83 Michael Hanselmann
3372 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3373 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3374 3c0cdc83 Michael Hanselmann
3375 6b93ec9d Iustin Pop
      if stats.is_standalone:
3376 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3377 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3378 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3379 6b93ec9d Iustin Pop
        try:
3380 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3381 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3382 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3383 3c0cdc83 Michael Hanselmann
3384 3c0cdc83 Michael Hanselmann
    if not all_connected:
3385 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3386 3c0cdc83 Michael Hanselmann
3387 3c0cdc83 Michael Hanselmann
  try:
3388 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3389 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3390 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3391 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3392 3c0cdc83 Michael Hanselmann
3393 6b93ec9d Iustin Pop
  if multimaster:
3394 6b93ec9d Iustin Pop
    # change to primary mode
3395 6b93ec9d Iustin Pop
    for rd in bdevs:
3396 d3da87b8 Iustin Pop
      try:
3397 d3da87b8 Iustin Pop
        rd.Open()
3398 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3399 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3400 6b93ec9d Iustin Pop
3401 6b93ec9d Iustin Pop
3402 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3403 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3404 6b93ec9d Iustin Pop

3405 6b93ec9d Iustin Pop
  """
3406 db8667b7 Iustin Pop
  def _helper(rd):
3407 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3408 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3409 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3410 db8667b7 Iustin Pop
    return stats
3411 db8667b7 Iustin Pop
3412 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3413 6b93ec9d Iustin Pop
3414 6b93ec9d Iustin Pop
  min_resync = 100
3415 6b93ec9d Iustin Pop
  alldone = True
3416 6b93ec9d Iustin Pop
  for rd in bdevs:
3417 db8667b7 Iustin Pop
    try:
3418 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3419 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3420 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3421 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3422 db8667b7 Iustin Pop
      # last check
3423 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3424 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3425 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3426 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3427 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3428 afdc3985 Iustin Pop
3429 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3430 6b93ec9d Iustin Pop
3431 6b93ec9d Iustin Pop
3432 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3433 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3434 c46b9782 Luca Bigliardi

3435 c46b9782 Luca Bigliardi
  """
3436 c46b9782 Luca Bigliardi
  try:
3437 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3438 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3439 c46b9782 Luca Bigliardi
    _Fail(str(err))
3440 c46b9782 Luca Bigliardi
3441 c46b9782 Luca Bigliardi
3442 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3443 f5118ade Iustin Pop
  """Hard-powercycle the node.
3444 f5118ade Iustin Pop

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

3448 f5118ade Iustin Pop
  """
3449 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3450 f5118ade Iustin Pop
  try:
3451 f5118ade Iustin Pop
    pid = os.fork()
3452 29921401 Iustin Pop
  except OSError:
3453 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3454 f5118ade Iustin Pop
    pid = 0
3455 f5118ade Iustin Pop
  if pid > 0:
3456 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3457 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3458 1af6ac0f Luca Bigliardi
  try:
3459 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3460 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3461 1af6ac0f Luca Bigliardi
    pass
3462 f5118ade Iustin Pop
  time.sleep(5)
3463 f5118ade Iustin Pop
  hyper.PowercycleNode()
3464 f5118ade Iustin Pop
3465 f5118ade Iustin Pop
3466 a8083063 Iustin Pop
class HooksRunner(object):
3467 a8083063 Iustin Pop
  """Hook runner.
3468 a8083063 Iustin Pop

3469 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3470 10c2650b Iustin Pop
  on the master side.
3471 a8083063 Iustin Pop

3472 a8083063 Iustin Pop
  """
3473 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3474 a8083063 Iustin Pop
    """Constructor for hooks runner.
3475 a8083063 Iustin Pop

3476 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
3477 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
3478 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3479 a8083063 Iustin Pop

3480 a8083063 Iustin Pop
    """
3481 a8083063 Iustin Pop
    if hooks_base_dir is None:
3482 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
3483 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3484 fe267188 Iustin Pop
    # constant
3485 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3486 a8083063 Iustin Pop
3487 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3488 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3489 0fa481f5 Andrea Spadaccini

3490 0fa481f5 Andrea Spadaccini
    """
3491 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3492 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3493 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3494 0fa481f5 Andrea Spadaccini
    assert node == myself
3495 0fa481f5 Andrea Spadaccini
3496 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3497 0fa481f5 Andrea Spadaccini
3498 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3499 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3500 0fa481f5 Andrea Spadaccini
3501 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3502 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3503 a8083063 Iustin Pop

3504 10c2650b Iustin Pop
    @type hpath: str
3505 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3506 10c2650b Iustin Pop
        holds the scripts
3507 10c2650b Iustin Pop
    @type phase: str
3508 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3509 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3510 10c2650b Iustin Pop
    @type env: dict
3511 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3512 10c2650b Iustin Pop
    @rtype: list
3513 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3514 10c2650b Iustin Pop
      - script path
3515 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3516 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3517 10c2650b Iustin Pop
      - output of the script
3518 10c2650b Iustin Pop

3519 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3520 10c2650b Iustin Pop
        parameters
3521 a8083063 Iustin Pop

3522 a8083063 Iustin Pop
    """
3523 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3524 a8083063 Iustin Pop
      suffix = "pre"
3525 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3526 a8083063 Iustin Pop
      suffix = "post"
3527 a8083063 Iustin Pop
    else:
3528 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3529 3fb4f740 Iustin Pop
3530 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3531 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3532 6bb65e3a Guido Trotter
3533 6bb65e3a Guido Trotter
    results = []
3534 a9b7e346 Iustin Pop
3535 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3536 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3537 a9b7e346 Iustin Pop
      # warning at every operation
3538 a9b7e346 Iustin Pop
      return results
3539 a9b7e346 Iustin Pop
3540 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3541 a9b7e346 Iustin Pop
3542 6bb65e3a Guido Trotter
    for (relname, relstatus, runresult)  in runparts_results:
3543 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3544 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3545 a8083063 Iustin Pop
        output = ""
3546 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3547 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3548 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3549 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3550 6bb65e3a Guido Trotter
        if runresult.failed:
3551 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3552 a8083063 Iustin Pop
        else:
3553 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3554 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3555 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3556 6bb65e3a Guido Trotter
3557 6bb65e3a Guido Trotter
    return results
3558 3f78eef2 Iustin Pop
3559 3f78eef2 Iustin Pop
3560 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3561 8d528b7c Iustin Pop
  """IAllocator runner.
3562 8d528b7c Iustin Pop

3563 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3564 8d528b7c Iustin Pop
  the master side.
3565 8d528b7c Iustin Pop

3566 8d528b7c Iustin Pop
  """
3567 7e950d31 Iustin Pop
  @staticmethod
3568 7e950d31 Iustin Pop
  def Run(name, idata):
3569 8d528b7c Iustin Pop
    """Run an iallocator script.
3570 8d528b7c Iustin Pop

3571 10c2650b Iustin Pop
    @type name: str
3572 10c2650b Iustin Pop
    @param name: the iallocator script name
3573 10c2650b Iustin Pop
    @type idata: str
3574 10c2650b Iustin Pop
    @param idata: the allocator input data
3575 10c2650b Iustin Pop

3576 10c2650b Iustin Pop
    @rtype: tuple
3577 87f5c298 Iustin Pop
    @return: two element tuple of:
3578 87f5c298 Iustin Pop
       - status
3579 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3580 8d528b7c Iustin Pop

3581 8d528b7c Iustin Pop
    """
3582 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3583 8d528b7c Iustin Pop
                                  os.path.isfile)
3584 8d528b7c Iustin Pop
    if alloc_script is None:
3585 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3586 8d528b7c Iustin Pop
3587 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3588 8d528b7c Iustin Pop
    try:
3589 8d528b7c Iustin Pop
      os.write(fd, idata)
3590 8d528b7c Iustin Pop
      os.close(fd)
3591 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3592 8d528b7c Iustin Pop
      if result.failed:
3593 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3594 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3595 8d528b7c Iustin Pop
    finally:
3596 8d528b7c Iustin Pop
      os.unlink(fin_name)
3597 8d528b7c Iustin Pop
3598 c26a6bd2 Iustin Pop
    return result.stdout
3599 8d528b7c Iustin Pop
3600 8d528b7c Iustin Pop
3601 3f78eef2 Iustin Pop
class DevCacheManager(object):
3602 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3603 3f78eef2 Iustin Pop

3604 3f78eef2 Iustin Pop
  """
3605 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3606 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3607 3f78eef2 Iustin Pop
3608 3f78eef2 Iustin Pop
  @classmethod
3609 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3610 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3611 3f78eef2 Iustin Pop

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

3615 10c2650b Iustin Pop
    @type dev_path: str
3616 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3617 10c2650b Iustin Pop
    @rtype: str
3618 10c2650b Iustin Pop
    @return: the converted path name
3619 3f78eef2 Iustin Pop

3620 3f78eef2 Iustin Pop
    """
3621 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3622 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3623 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3624 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3625 3f78eef2 Iustin Pop
    return fpath
3626 3f78eef2 Iustin Pop
3627 3f78eef2 Iustin Pop
  @classmethod
3628 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3629 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3630 3f78eef2 Iustin Pop

3631 10c2650b Iustin Pop
    @type dev_path: str
3632 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3633 10c2650b Iustin Pop
    @type owner: str
3634 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3635 10c2650b Iustin Pop
    @type on_primary: bool
3636 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3637 10c2650b Iustin Pop
        node nor not
3638 10c2650b Iustin Pop
    @type iv_name: str
3639 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3640 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3641 10c2650b Iustin Pop

3642 10c2650b Iustin Pop
    @rtype: None
3643 10c2650b Iustin Pop

3644 3f78eef2 Iustin Pop
    """
3645 cf5a8306 Iustin Pop
    if dev_path is None:
3646 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3647 cf5a8306 Iustin Pop
      return
3648 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3649 3f78eef2 Iustin Pop
    if on_primary:
3650 3f78eef2 Iustin Pop
      state = "primary"
3651 3f78eef2 Iustin Pop
    else:
3652 3f78eef2 Iustin Pop
      state = "secondary"
3653 3f78eef2 Iustin Pop
    if iv_name is None:
3654 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3655 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3656 3f78eef2 Iustin Pop
    try:
3657 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3658 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3659 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3660 3f78eef2 Iustin Pop
3661 3f78eef2 Iustin Pop
  @classmethod
3662 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3663 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3664 3f78eef2 Iustin Pop

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

3668 10c2650b Iustin Pop
    @type dev_path: str
3669 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3670 10c2650b Iustin Pop

3671 10c2650b Iustin Pop
    @rtype: None
3672 10c2650b Iustin Pop

3673 3f78eef2 Iustin Pop
    """
3674 cf5a8306 Iustin Pop
    if dev_path is None:
3675 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3676 cf5a8306 Iustin Pop
      return
3677 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3678 3f78eef2 Iustin Pop
    try:
3679 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3680 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3681 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)