Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 61e062dd

History | View | Annotate | Download (120.4 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a1f38213 Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 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 3ccd3243 Andrea Spadaccini
from ganeti import compat
65 710f30ec Michael Hanselmann
from ganeti import pathutils
66 cffbbae7 Michael Hanselmann
from ganeti import vcluster
67 a8083063 Iustin Pop
68 a8083063 Iustin Pop
69 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
70 714ea7ca Iustin Pop
_ALLOWED_CLEAN_DIRS = frozenset([
71 710f30ec Michael Hanselmann
  pathutils.DATA_DIR,
72 710f30ec Michael Hanselmann
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
73 710f30ec Michael Hanselmann
  pathutils.QUEUE_DIR,
74 710f30ec Michael Hanselmann
  pathutils.CRYPTO_KEYS_DIR,
75 714ea7ca Iustin Pop
  ])
76 f942a838 Michael Hanselmann
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
77 f942a838 Michael Hanselmann
_X509_KEY_FILE = "key"
78 f942a838 Michael Hanselmann
_X509_CERT_FILE = "cert"
79 1651d116 Michael Hanselmann
_IES_STATUS_FILE = "status"
80 1651d116 Michael Hanselmann
_IES_PID_FILE = "pid"
81 1651d116 Michael Hanselmann
_IES_CA_FILE = "ca"
82 13998ef2 Michael Hanselmann
83 0b5303da Iustin Pop
#: Valid LVS output line regex
84 a1f38213 Iustin Pop
_LVSLINE_REGEX = re.compile("^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
85 0b5303da Iustin Pop
86 702eff21 Andrea Spadaccini
# Actions for the master setup script
87 702eff21 Andrea Spadaccini
_MASTER_START = "start"
88 702eff21 Andrea Spadaccini
_MASTER_STOP = "stop"
89 702eff21 Andrea Spadaccini
90 1a2eb2dc Michael Hanselmann
#: Maximum file permissions for remote command directory and executables
91 1a2eb2dc Michael Hanselmann
_RCMD_MAX_MODE = (stat.S_IRWXU |
92 1a2eb2dc Michael Hanselmann
                  stat.S_IRGRP | stat.S_IXGRP |
93 1a2eb2dc Michael Hanselmann
                  stat.S_IROTH | stat.S_IXOTH)
94 1a2eb2dc Michael Hanselmann
95 1a2eb2dc Michael Hanselmann
#: Delay before returning an error for remote commands
96 1a2eb2dc Michael Hanselmann
_RCMD_INVALID_DELAY = 10
97 1a2eb2dc Michael Hanselmann
98 1a2eb2dc Michael Hanselmann
#: How long to wait to acquire lock for remote commands (shorter than
99 1a2eb2dc Michael Hanselmann
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
100 1a2eb2dc Michael Hanselmann
#: command requests arrive
101 1a2eb2dc Michael Hanselmann
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
102 1a2eb2dc Michael Hanselmann
103 13998ef2 Michael Hanselmann
104 2cc6781a Iustin Pop
class RPCFail(Exception):
105 2cc6781a Iustin Pop
  """Class denoting RPC failure.
106 2cc6781a Iustin Pop

107 2cc6781a Iustin Pop
  Its argument is the error message.
108 2cc6781a Iustin Pop

109 2cc6781a Iustin Pop
  """
110 2cc6781a Iustin Pop
111 13998ef2 Michael Hanselmann
112 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
113 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
114 2cc6781a Iustin Pop

115 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
116 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
117 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
118 2cc6781a Iustin Pop
  daemon.
119 2cc6781a Iustin Pop

120 2cc6781a Iustin Pop
  @type msg: string
121 2cc6781a Iustin Pop
  @param msg: the text of the exception
122 2cc6781a Iustin Pop
  @raise RPCFail
123 2cc6781a Iustin Pop

124 2cc6781a Iustin Pop
  """
125 2cc6781a Iustin Pop
  if args:
126 2cc6781a Iustin Pop
    msg = msg % args
127 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
128 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
129 afdc3985 Iustin Pop
      logging.exception(msg)
130 afdc3985 Iustin Pop
    else:
131 afdc3985 Iustin Pop
      logging.error(msg)
132 2cc6781a Iustin Pop
  raise RPCFail(msg)
133 2cc6781a Iustin Pop
134 2cc6781a Iustin Pop
135 c657dcc9 Michael Hanselmann
def _GetConfig():
136 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
137 10c2650b Iustin Pop

138 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
139 93384844 Iustin Pop
  @return: a SimpleStore instance
140 10c2650b Iustin Pop

141 10c2650b Iustin Pop
  """
142 93384844 Iustin Pop
  return ssconf.SimpleStore()
143 c657dcc9 Michael Hanselmann
144 c657dcc9 Michael Hanselmann
145 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
146 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
147 10c2650b Iustin Pop

148 10c2650b Iustin Pop
  @type cluster_name: str
149 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
150 10c2650b Iustin Pop
      by the SshRunner constructor
151 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
152 10c2650b Iustin Pop
  @return: an SshRunner instance
153 10c2650b Iustin Pop

154 10c2650b Iustin Pop
  """
155 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
156 c92b310a Michael Hanselmann
157 c92b310a Michael Hanselmann
158 12bce260 Michael Hanselmann
def _Decompress(data):
159 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
160 12bce260 Michael Hanselmann

161 12bce260 Michael Hanselmann
  @type data: list or tuple
162 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
163 12bce260 Michael Hanselmann
  @rtype: str
164 12bce260 Michael Hanselmann
  @return: Decompressed data
165 12bce260 Michael Hanselmann

166 12bce260 Michael Hanselmann
  """
167 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
168 12bce260 Michael Hanselmann
  assert len(data) == 2
169 12bce260 Michael Hanselmann
  (encoding, content) = data
170 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
171 12bce260 Michael Hanselmann
    return content
172 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
173 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
174 12bce260 Michael Hanselmann
  else:
175 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
176 12bce260 Michael Hanselmann
177 12bce260 Michael Hanselmann
178 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
179 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
180 76ab5558 Michael Hanselmann

181 10c2650b Iustin Pop
  @type path: str
182 10c2650b Iustin Pop
  @param path: the directory to clean
183 76ab5558 Michael Hanselmann
  @type exclude: list
184 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
185 10c2650b Iustin Pop
      to the empty list
186 76ab5558 Michael Hanselmann

187 76ab5558 Michael Hanselmann
  """
188 714ea7ca Iustin Pop
  if path not in _ALLOWED_CLEAN_DIRS:
189 714ea7ca Iustin Pop
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
190 714ea7ca Iustin Pop
          path)
191 714ea7ca Iustin Pop
192 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
193 3956cee1 Michael Hanselmann
    return
194 3bc6be5c Iustin Pop
  if exclude is None:
195 3bc6be5c Iustin Pop
    exclude = []
196 3bc6be5c Iustin Pop
  else:
197 3bc6be5c Iustin Pop
    # Normalize excluded paths
198 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
199 76ab5558 Michael Hanselmann
200 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
201 c4feafe8 Iustin Pop
    full_name = utils.PathJoin(path, rel_name)
202 76ab5558 Michael Hanselmann
    if full_name in exclude:
203 76ab5558 Michael Hanselmann
      continue
204 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
205 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
206 3956cee1 Michael Hanselmann
207 3956cee1 Michael Hanselmann
208 360b0dc2 Iustin Pop
def _BuildUploadFileList():
209 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
210 360b0dc2 Iustin Pop

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

213 360b0dc2 Iustin Pop
  """
214 b397a7d2 Iustin Pop
  allowed_files = set([
215 710f30ec Michael Hanselmann
    pathutils.CLUSTER_CONF_FILE,
216 ee045466 Michael Hanselmann
    pathutils.ETC_HOSTS,
217 710f30ec Michael Hanselmann
    pathutils.SSH_KNOWN_HOSTS_FILE,
218 710f30ec Michael Hanselmann
    pathutils.VNC_PASSWORD_FILE,
219 710f30ec Michael Hanselmann
    pathutils.RAPI_CERT_FILE,
220 710f30ec Michael Hanselmann
    pathutils.SPICE_CERT_FILE,
221 710f30ec Michael Hanselmann
    pathutils.SPICE_CACERT_FILE,
222 710f30ec Michael Hanselmann
    pathutils.RAPI_USERS_FILE,
223 710f30ec Michael Hanselmann
    pathutils.CONFD_HMAC_KEY,
224 710f30ec Michael Hanselmann
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
225 b397a7d2 Iustin Pop
    ])
226 b397a7d2 Iustin Pop
227 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
228 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
229 69ab2e12 Guido Trotter
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
230 b397a7d2 Iustin Pop
231 3439fd6b Michael Hanselmann
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
232 3439fd6b Michael Hanselmann
    "Allowed file storage paths should never be uploaded via RPC"
233 3439fd6b Michael Hanselmann
234 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
235 360b0dc2 Iustin Pop
236 360b0dc2 Iustin Pop
237 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
238 360b0dc2 Iustin Pop
239 360b0dc2 Iustin Pop
240 1bc59f76 Michael Hanselmann
def JobQueuePurge():
241 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
242 10c2650b Iustin Pop

243 c8457ce7 Iustin Pop
  @rtype: tuple
244 c8457ce7 Iustin Pop
  @return: True, None
245 24fc781f Michael Hanselmann

246 24fc781f Michael Hanselmann
  """
247 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
248 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
249 24fc781f Michael Hanselmann
250 24fc781f Michael Hanselmann
251 bd1e4562 Iustin Pop
def GetMasterInfo():
252 bd1e4562 Iustin Pop
  """Returns master information.
253 bd1e4562 Iustin Pop

254 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
255 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
256 bd1e4562 Iustin Pop

257 bd1e4562 Iustin Pop
  @rtype: tuple
258 909b3a0e Andrea Spadaccini
  @return: master_netdev, master_ip, master_name, primary_ip_family,
259 909b3a0e Andrea Spadaccini
    master_netmask
260 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
261 b1b6ea87 Iustin Pop

262 b1b6ea87 Iustin Pop
  """
263 b1b6ea87 Iustin Pop
  try:
264 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
265 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
266 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
267 5a8648eb Andrea Spadaccini
    master_netmask = cfg.GetMasterNetmask()
268 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
269 d8e0caa6 Manuel Franceschini
    primary_ip_family = cfg.GetPrimaryIPFamily()
270 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
271 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
272 909b3a0e Andrea Spadaccini
  return (master_netdev, master_ip, master_node, primary_ip_family,
273 5ae4945a Iustin Pop
          master_netmask)
274 b1b6ea87 Iustin Pop
275 b1b6ea87 Iustin Pop
276 0fa481f5 Andrea Spadaccini
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
277 0fa481f5 Andrea Spadaccini
  """Decorator that runs hooks before and after the decorated function.
278 0fa481f5 Andrea Spadaccini

279 0fa481f5 Andrea Spadaccini
  @type hook_opcode: string
280 0fa481f5 Andrea Spadaccini
  @param hook_opcode: opcode of the hook
281 0fa481f5 Andrea Spadaccini
  @type hooks_path: string
282 0fa481f5 Andrea Spadaccini
  @param hooks_path: path of the hooks
283 0fa481f5 Andrea Spadaccini
  @type env_builder_fn: function
284 0fa481f5 Andrea Spadaccini
  @param env_builder_fn: function that returns a dictionary containing the
285 3ccd3243 Andrea Spadaccini
    environment variables for the hooks. Will get all the parameters of the
286 3ccd3243 Andrea Spadaccini
    decorated function.
287 0fa481f5 Andrea Spadaccini
  @raise RPCFail: in case of pre-hook failure
288 0fa481f5 Andrea Spadaccini

289 0fa481f5 Andrea Spadaccini
  """
290 0fa481f5 Andrea Spadaccini
  def decorator(fn):
291 0fa481f5 Andrea Spadaccini
    def wrapper(*args, **kwargs):
292 0fa481f5 Andrea Spadaccini
      _, myself = ssconf.GetMasterAndMyself()
293 0fa481f5 Andrea Spadaccini
      nodes = ([myself], [myself])  # these hooks run locally
294 0fa481f5 Andrea Spadaccini
295 3ccd3243 Andrea Spadaccini
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
296 3ccd3243 Andrea Spadaccini
297 0fa481f5 Andrea Spadaccini
      cfg = _GetConfig()
298 0fa481f5 Andrea Spadaccini
      hr = HooksRunner()
299 0fa481f5 Andrea Spadaccini
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
300 3ccd3243 Andrea Spadaccini
                            None, env_fn, logging.warning, cfg.GetClusterName(),
301 3ccd3243 Andrea Spadaccini
                            cfg.GetMasterNode())
302 0fa481f5 Andrea Spadaccini
303 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
304 0fa481f5 Andrea Spadaccini
      result = fn(*args, **kwargs)
305 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_POST)
306 0fa481f5 Andrea Spadaccini
307 0fa481f5 Andrea Spadaccini
      return result
308 0fa481f5 Andrea Spadaccini
    return wrapper
309 0fa481f5 Andrea Spadaccini
  return decorator
310 0fa481f5 Andrea Spadaccini
311 0fa481f5 Andrea Spadaccini
312 57c7bc57 Andrea Spadaccini
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
313 2d88fdd3 Andrea Spadaccini
  """Builds environment variables for master IP hooks.
314 2d88fdd3 Andrea Spadaccini

315 3ccd3243 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
316 3ccd3243 Andrea Spadaccini
  @param master_params: network parameters of the master
317 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
318 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
319 57c7bc57 Andrea Spadaccini
    address setup script (unused, but necessary per the implementation of the
320 57c7bc57 Andrea Spadaccini
    _RunLocalHooks decorator)
321 3ccd3243 Andrea Spadaccini

322 2d88fdd3 Andrea Spadaccini
  """
323 57c7bc57 Andrea Spadaccini
  # pylint: disable=W0613
324 3ccd3243 Andrea Spadaccini
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
325 2d88fdd3 Andrea Spadaccini
  env = {
326 3ccd3243 Andrea Spadaccini
    "MASTER_NETDEV": master_params.netdev,
327 3ccd3243 Andrea Spadaccini
    "MASTER_IP": master_params.ip,
328 702eff21 Andrea Spadaccini
    "MASTER_NETMASK": str(master_params.netmask),
329 3ccd3243 Andrea Spadaccini
    "CLUSTER_IP_VERSION": str(ver),
330 2d88fdd3 Andrea Spadaccini
  }
331 2d88fdd3 Andrea Spadaccini
332 2d88fdd3 Andrea Spadaccini
  return env
333 2d88fdd3 Andrea Spadaccini
334 2d88fdd3 Andrea Spadaccini
335 702eff21 Andrea Spadaccini
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
336 702eff21 Andrea Spadaccini
  """Execute the master IP address setup script.
337 702eff21 Andrea Spadaccini

338 702eff21 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
339 702eff21 Andrea Spadaccini
  @param master_params: network parameters of the master
340 702eff21 Andrea Spadaccini
  @type action: string
341 702eff21 Andrea Spadaccini
  @param action: action to pass to the script. Must be one of
342 702eff21 Andrea Spadaccini
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
343 702eff21 Andrea Spadaccini
  @type use_external_mip_script: boolean
344 702eff21 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
345 702eff21 Andrea Spadaccini
    address setup script
346 702eff21 Andrea Spadaccini
  @raise backend.RPCFail: if there are errors during the execution of the
347 702eff21 Andrea Spadaccini
    script
348 702eff21 Andrea Spadaccini

349 702eff21 Andrea Spadaccini
  """
350 702eff21 Andrea Spadaccini
  env = _BuildMasterIpEnv(master_params)
351 702eff21 Andrea Spadaccini
352 702eff21 Andrea Spadaccini
  if use_external_mip_script:
353 710f30ec Michael Hanselmann
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
354 702eff21 Andrea Spadaccini
  else:
355 710f30ec Michael Hanselmann
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
356 702eff21 Andrea Spadaccini
357 702eff21 Andrea Spadaccini
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
358 702eff21 Andrea Spadaccini
359 702eff21 Andrea Spadaccini
  if result.failed:
360 702eff21 Andrea Spadaccini
    _Fail("Failed to %s the master IP. Script return value: %s" %
361 702eff21 Andrea Spadaccini
          (action, result.exit_code), log=True)
362 702eff21 Andrea Spadaccini
363 702eff21 Andrea Spadaccini
364 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
365 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
366 57c7bc57 Andrea Spadaccini
def ActivateMasterIp(master_params, use_external_mip_script):
367 fb460cf7 Andrea Spadaccini
  """Activate the IP address of the master daemon.
368 fb460cf7 Andrea Spadaccini

369 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
370 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
371 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
372 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
373 57c7bc57 Andrea Spadaccini
    address setup script
374 702eff21 Andrea Spadaccini
  @raise RPCFail: in case of errors during the IP startup
375 8da2bd43 Andrea Spadaccini

376 fb460cf7 Andrea Spadaccini
  """
377 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_START,
378 702eff21 Andrea Spadaccini
                        use_external_mip_script)
379 fb460cf7 Andrea Spadaccini
380 fb460cf7 Andrea Spadaccini
381 fb460cf7 Andrea Spadaccini
def StartMasterDaemons(no_voting):
382 a8083063 Iustin Pop
  """Activate local node as master node.
383 a8083063 Iustin Pop

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

386 3583908a Guido Trotter
  @type no_voting: boolean
387 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
388 fb460cf7 Andrea Spadaccini
      but still non-interactively
389 10c2650b Iustin Pop
  @rtype: None
390 a8083063 Iustin Pop

391 a8083063 Iustin Pop
  """
392 a8083063 Iustin Pop
393 fb460cf7 Andrea Spadaccini
  if no_voting:
394 fb460cf7 Andrea Spadaccini
    masterd_args = "--no-voting --yes-do-it"
395 fb460cf7 Andrea Spadaccini
  else:
396 fb460cf7 Andrea Spadaccini
    masterd_args = ""
397 f154a7a3 Michael Hanselmann
398 fb460cf7 Andrea Spadaccini
  env = {
399 fb460cf7 Andrea Spadaccini
    "EXTRA_MASTERD_ARGS": masterd_args,
400 fb460cf7 Andrea Spadaccini
    }
401 fb460cf7 Andrea Spadaccini
402 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
403 fb460cf7 Andrea Spadaccini
  if result.failed:
404 fb460cf7 Andrea Spadaccini
    msg = "Can't start Ganeti master: %s" % result.output
405 fb460cf7 Andrea Spadaccini
    logging.error(msg)
406 fb460cf7 Andrea Spadaccini
    _Fail(msg)
407 f154a7a3 Michael Hanselmann
408 fb460cf7 Andrea Spadaccini
409 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
410 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
411 57c7bc57 Andrea Spadaccini
def DeactivateMasterIp(master_params, use_external_mip_script):
412 fb460cf7 Andrea Spadaccini
  """Deactivate the master IP on this node.
413 a8083063 Iustin Pop

414 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
415 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
416 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
417 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
418 57c7bc57 Andrea Spadaccini
    address setup script
419 702eff21 Andrea Spadaccini
  @raise RPCFail: in case of errors during the IP turndown
420 96e0d5cc Andrea Spadaccini

421 a8083063 Iustin Pop
  """
422 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_STOP,
423 702eff21 Andrea Spadaccini
                        use_external_mip_script)
424 b1b6ea87 Iustin Pop
425 fb460cf7 Andrea Spadaccini
426 fb460cf7 Andrea Spadaccini
def StopMasterDaemons():
427 fb460cf7 Andrea Spadaccini
  """Stop the master daemons on this node.
428 fb460cf7 Andrea Spadaccini

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

431 fb460cf7 Andrea Spadaccini
  @rtype: None
432 fb460cf7 Andrea Spadaccini

433 fb460cf7 Andrea Spadaccini
  """
434 fb460cf7 Andrea Spadaccini
  # TODO: log and report back to the caller the error failures; we
435 fb460cf7 Andrea Spadaccini
  # need to decide in which case we fail the RPC for this
436 fb460cf7 Andrea Spadaccini
437 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
438 fb460cf7 Andrea Spadaccini
  if result.failed:
439 fb460cf7 Andrea Spadaccini
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
440 fb460cf7 Andrea Spadaccini
                  " and error %s",
441 fb460cf7 Andrea Spadaccini
                  result.cmd, result.exit_code, result.output)
442 a8083063 Iustin Pop
443 a8083063 Iustin Pop
444 41e079ce Andrea Spadaccini
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
445 5a8648eb Andrea Spadaccini
  """Change the netmask of the master IP.
446 5a8648eb Andrea Spadaccini

447 41e079ce Andrea Spadaccini
  @param old_netmask: the old value of the netmask
448 41e079ce Andrea Spadaccini
  @param netmask: the new value of the netmask
449 41e079ce Andrea Spadaccini
  @param master_ip: the master IP
450 41e079ce Andrea Spadaccini
  @param master_netdev: the master network device
451 41e079ce Andrea Spadaccini

452 5a8648eb Andrea Spadaccini
  """
453 5a8648eb Andrea Spadaccini
  if old_netmask == netmask:
454 5a8648eb Andrea Spadaccini
    return
455 5a8648eb Andrea Spadaccini
456 9e6014b9 Andrea Spadaccini
  if not netutils.IPAddress.Own(master_ip):
457 9e6014b9 Andrea Spadaccini
    _Fail("The master IP address is not up, not attempting to change its"
458 9e6014b9 Andrea Spadaccini
          " netmask")
459 9e6014b9 Andrea Spadaccini
460 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
461 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, netmask),
462 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
463 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
464 5a8648eb Andrea Spadaccini
  if result.failed:
465 9e6014b9 Andrea Spadaccini
    _Fail("Could not set the new netmask on the master IP address")
466 5a8648eb Andrea Spadaccini
467 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
468 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, old_netmask),
469 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
470 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
471 5a8648eb Andrea Spadaccini
  if result.failed:
472 9e6014b9 Andrea Spadaccini
    _Fail("Could not bring down the master IP address with the old netmask")
473 5a8648eb Andrea Spadaccini
474 5a8648eb Andrea Spadaccini
475 19ddc57a René Nussbaumer
def EtcHostsModify(mode, host, ip):
476 19ddc57a René Nussbaumer
  """Modify a host entry in /etc/hosts.
477 19ddc57a René Nussbaumer

478 19ddc57a René Nussbaumer
  @param mode: The mode to operate. Either add or remove entry
479 19ddc57a René Nussbaumer
  @param host: The host to operate on
480 19ddc57a René Nussbaumer
  @param ip: The ip associated with the entry
481 19ddc57a René Nussbaumer

482 19ddc57a René Nussbaumer
  """
483 19ddc57a René Nussbaumer
  if mode == constants.ETC_HOSTS_ADD:
484 19ddc57a René Nussbaumer
    if not ip:
485 19ddc57a René Nussbaumer
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
486 19ddc57a René Nussbaumer
              " present")
487 19ddc57a René Nussbaumer
    utils.AddHostToEtcHosts(host, ip)
488 19ddc57a René Nussbaumer
  elif mode == constants.ETC_HOSTS_REMOVE:
489 19ddc57a René Nussbaumer
    if ip:
490 19ddc57a René Nussbaumer
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
491 19ddc57a René Nussbaumer
              " parameter is present")
492 19ddc57a René Nussbaumer
    utils.RemoveHostFromEtcHosts(host)
493 19ddc57a René Nussbaumer
  else:
494 19ddc57a René Nussbaumer
    RPCFail("Mode not supported")
495 19ddc57a René Nussbaumer
496 19ddc57a René Nussbaumer
497 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
498 10c2650b Iustin Pop
  """Cleans up and remove the current node.
499 10c2650b Iustin Pop

500 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
501 10c2650b Iustin Pop
  from the cluster.
502 10c2650b Iustin Pop

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

507 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
508 b989b9d9 Ken Wehr

509 a8083063 Iustin Pop
  """
510 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.DATA_DIR)
511 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
512 1bc59f76 Michael Hanselmann
  JobQueuePurge()
513 f78346f5 Michael Hanselmann
514 b989b9d9 Ken Wehr
  if modify_ssh_setup:
515 b989b9d9 Ken Wehr
    try:
516 052783ff Michael Hanselmann
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
517 7900ed01 Iustin Pop
518 b989b9d9 Ken Wehr
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
519 a8083063 Iustin Pop
520 b989b9d9 Ken Wehr
      utils.RemoveFile(priv_key)
521 b989b9d9 Ken Wehr
      utils.RemoveFile(pub_key)
522 b989b9d9 Ken Wehr
    except errors.OpExecError:
523 b989b9d9 Ken Wehr
      logging.exception("Error while processing ssh files")
524 a8083063 Iustin Pop
525 ed008420 Guido Trotter
  try:
526 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
527 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
528 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
529 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
530 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
531 b459a848 Andrea Spadaccini
  except: # pylint: disable=W0702
532 ed008420 Guido Trotter
    logging.exception("Error while removing cluster secrets")
533 ed008420 Guido Trotter
534 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
535 f154a7a3 Michael Hanselmann
  if result.failed:
536 f154a7a3 Michael Hanselmann
    logging.error("Command %s failed with exitcode %s and error %s",
537 f154a7a3 Michael Hanselmann
                  result.cmd, result.exit_code, result.output)
538 ed008420 Guido Trotter
539 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
540 d0c8c01d Iustin Pop
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
541 6d8b6238 Guido Trotter
542 a8083063 Iustin Pop
543 78519c10 Michael Hanselmann
def _GetVgInfo(name):
544 78519c10 Michael Hanselmann
  """Retrieves information about a LVM volume group.
545 78519c10 Michael Hanselmann

546 78519c10 Michael Hanselmann
  """
547 78519c10 Michael Hanselmann
  # TODO: GetVGInfo supports returning information for multiple VGs at once
548 78519c10 Michael Hanselmann
  vginfo = bdev.LogicalVolume.GetVGInfo([name])
549 78519c10 Michael Hanselmann
  if vginfo:
550 78519c10 Michael Hanselmann
    vg_free = int(round(vginfo[0][0], 0))
551 78519c10 Michael Hanselmann
    vg_size = int(round(vginfo[0][1], 0))
552 78519c10 Michael Hanselmann
  else:
553 78519c10 Michael Hanselmann
    vg_free = None
554 78519c10 Michael Hanselmann
    vg_size = None
555 78519c10 Michael Hanselmann
556 78519c10 Michael Hanselmann
  return {
557 78519c10 Michael Hanselmann
    "name": name,
558 1e89a135 Michael Hanselmann
    "vg_free": vg_free,
559 1e89a135 Michael Hanselmann
    "vg_size": vg_size,
560 78519c10 Michael Hanselmann
    }
561 78519c10 Michael Hanselmann
562 78519c10 Michael Hanselmann
563 78519c10 Michael Hanselmann
def _GetHvInfo(name):
564 78519c10 Michael Hanselmann
  """Retrieves node information from a hypervisor.
565 78519c10 Michael Hanselmann

566 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
567 78519c10 Michael Hanselmann

568 78519c10 Michael Hanselmann
    - vg_size is the size of the configured volume group in MiB
569 78519c10 Michael Hanselmann
    - vg_free is the free size of the volume group in MiB
570 78519c10 Michael Hanselmann
    - memory_dom0 is the memory allocated for domain0 in MiB
571 78519c10 Michael Hanselmann
    - memory_free is the currently available (free) ram in MiB
572 78519c10 Michael Hanselmann
    - memory_total is the total number of ram in MiB
573 78519c10 Michael Hanselmann
    - hv_version: the hypervisor version, if available
574 78519c10 Michael Hanselmann

575 78519c10 Michael Hanselmann
  """
576 78519c10 Michael Hanselmann
  return hypervisor.GetHypervisor(name).GetNodeInfo()
577 78519c10 Michael Hanselmann
578 78519c10 Michael Hanselmann
579 78519c10 Michael Hanselmann
def _GetNamedNodeInfo(names, fn):
580 78519c10 Michael Hanselmann
  """Calls C{fn} for all names in C{names} and returns a dictionary.
581 78519c10 Michael Hanselmann

582 78519c10 Michael Hanselmann
  @rtype: None or dict
583 78519c10 Michael Hanselmann

584 78519c10 Michael Hanselmann
  """
585 78519c10 Michael Hanselmann
  if names is None:
586 78519c10 Michael Hanselmann
    return None
587 78519c10 Michael Hanselmann
  else:
588 ff3be305 Michael Hanselmann
    return map(fn, names)
589 78519c10 Michael Hanselmann
590 78519c10 Michael Hanselmann
591 78519c10 Michael Hanselmann
def GetNodeInfo(vg_names, hv_names):
592 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
593 a8083063 Iustin Pop

594 78519c10 Michael Hanselmann
  @type vg_names: list of string
595 78519c10 Michael Hanselmann
  @param vg_names: Names of the volume groups to ask for disk space information
596 78519c10 Michael Hanselmann
  @type hv_names: list of string
597 78519c10 Michael Hanselmann
  @param hv_names: Names of the hypervisors to ask for node information
598 78519c10 Michael Hanselmann
  @rtype: tuple; (string, None/dict, None/dict)
599 78519c10 Michael Hanselmann
  @return: Tuple containing boot ID, volume group information and hypervisor
600 78519c10 Michael Hanselmann
    information
601 a8083063 Iustin Pop

602 098c0958 Michael Hanselmann
  """
603 78519c10 Michael Hanselmann
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
604 78519c10 Michael Hanselmann
  vg_info = _GetNamedNodeInfo(vg_names, _GetVgInfo)
605 78519c10 Michael Hanselmann
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
606 78519c10 Michael Hanselmann
607 78519c10 Michael Hanselmann
  return (bootid, vg_info, hv_info)
608 a8083063 Iustin Pop
609 a8083063 Iustin Pop
610 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
611 a8083063 Iustin Pop
  """Verify the status of the local node.
612 a8083063 Iustin Pop

613 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
614 e69d05fd Iustin Pop
  local node.
615 e69d05fd Iustin Pop

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

619 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
620 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
621 e69d05fd Iustin Pop
  report).
622 a8083063 Iustin Pop

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

627 e69d05fd Iustin Pop
  @type what: C{dict}
628 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
629 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
630 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
631 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
632 e69d05fd Iustin Pop
        connectivity with
633 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
634 10c2650b Iustin Pop
  @rtype: dict
635 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
636 10c2650b Iustin Pop
      values representing the result of the checks
637 a8083063 Iustin Pop

638 a8083063 Iustin Pop
  """
639 a8083063 Iustin Pop
  result = {}
640 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
641 a744b676 Manuel Franceschini
  port = netutils.GetDaemonPort(constants.NODED)
642 8964ee14 Iustin Pop
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
643 a8083063 Iustin Pop
644 8964ee14 Iustin Pop
  if constants.NV_HYPERVISOR in what and vm_capable:
645 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
646 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
647 0cf5e7f5 Iustin Pop
      try:
648 0cf5e7f5 Iustin Pop
        val = hypervisor.GetHypervisor(hv_name).Verify()
649 0cf5e7f5 Iustin Pop
      except errors.HypervisorError, err:
650 0cf5e7f5 Iustin Pop
        val = "Error while checking hypervisor: %s" % str(err)
651 0cf5e7f5 Iustin Pop
      tmp[hv_name] = val
652 25361b9a Iustin Pop
653 58a59652 Iustin Pop
  if constants.NV_HVPARAMS in what and vm_capable:
654 58a59652 Iustin Pop
    result[constants.NV_HVPARAMS] = tmp = []
655 58a59652 Iustin Pop
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
656 58a59652 Iustin Pop
      try:
657 58a59652 Iustin Pop
        logging.info("Validating hv %s, %s", hv_name, hvparms)
658 58a59652 Iustin Pop
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
659 58a59652 Iustin Pop
      except errors.HypervisorError, err:
660 58a59652 Iustin Pop
        tmp.append((source, hv_name, str(err)))
661 58a59652 Iustin Pop
662 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
663 47130d50 Michael Hanselmann
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
664 47130d50 Michael Hanselmann
                                              what[constants.NV_FILELIST]))
665 47130d50 Michael Hanselmann
    result[constants.NV_FILELIST] = \
666 47130d50 Michael Hanselmann
      dict((vcluster.MakeVirtualPath(key), value)
667 47130d50 Michael Hanselmann
           for (key, value) in fingerprints.items())
668 25361b9a Iustin Pop
669 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
670 64c7b383 Michael Hanselmann
    (nodes, bynode) = what[constants.NV_NODELIST]
671 64c7b383 Michael Hanselmann
672 64c7b383 Michael Hanselmann
    # Add nodes from other groups (different for each node)
673 64c7b383 Michael Hanselmann
    try:
674 64c7b383 Michael Hanselmann
      nodes.extend(bynode[my_name])
675 64c7b383 Michael Hanselmann
    except KeyError:
676 64c7b383 Michael Hanselmann
      pass
677 64c7b383 Michael Hanselmann
678 64c7b383 Michael Hanselmann
    # Use a random order
679 64c7b383 Michael Hanselmann
    random.shuffle(nodes)
680 64c7b383 Michael Hanselmann
681 64c7b383 Michael Hanselmann
    # Try to contact all nodes
682 64c7b383 Michael Hanselmann
    val = {}
683 64c7b383 Michael Hanselmann
    for node in nodes:
684 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
685 a8083063 Iustin Pop
      if not success:
686 64c7b383 Michael Hanselmann
        val[node] = message
687 64c7b383 Michael Hanselmann
688 64c7b383 Michael Hanselmann
    result[constants.NV_NODELIST] = val
689 25361b9a Iustin Pop
690 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
691 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
692 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
693 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
694 9d4bfc96 Iustin Pop
      if name == my_name:
695 9d4bfc96 Iustin Pop
        my_pip = pip
696 9d4bfc96 Iustin Pop
        my_sip = sip
697 9d4bfc96 Iustin Pop
        break
698 9d4bfc96 Iustin Pop
    if not my_pip:
699 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
700 25361b9a Iustin Pop
                      " in the node list")
701 9d4bfc96 Iustin Pop
    else:
702 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
703 9d4bfc96 Iustin Pop
        fail = []
704 a744b676 Manuel Franceschini
        if not netutils.TcpPing(pip, port, source=my_pip):
705 9d4bfc96 Iustin Pop
          fail.append("primary")
706 9d4bfc96 Iustin Pop
        if sip != pip:
707 a744b676 Manuel Franceschini
          if not netutils.TcpPing(sip, port, source=my_sip):
708 9d4bfc96 Iustin Pop
            fail.append("secondary")
709 9d4bfc96 Iustin Pop
        if fail:
710 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
711 25361b9a Iustin Pop
                       " and ".join(fail))
712 25361b9a Iustin Pop
713 a3a5f850 Iustin Pop
  if constants.NV_MASTERIP in what:
714 a3a5f850 Iustin Pop
    # FIXME: add checks on incoming data structures (here and in the
715 a3a5f850 Iustin Pop
    # rest of the function)
716 a3a5f850 Iustin Pop
    master_name, master_ip = what[constants.NV_MASTERIP]
717 a3a5f850 Iustin Pop
    if master_name == my_name:
718 9769bb78 Manuel Franceschini
      source = constants.IP4_ADDRESS_LOCALHOST
719 a3a5f850 Iustin Pop
    else:
720 a3a5f850 Iustin Pop
      source = None
721 a744b676 Manuel Franceschini
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
722 5ae4945a Iustin Pop
                                                     source=source)
723 a3a5f850 Iustin Pop
724 17b0b812 Andrea Spadaccini
  if constants.NV_USERSCRIPTS in what:
725 17b0b812 Andrea Spadaccini
    result[constants.NV_USERSCRIPTS] = \
726 17b0b812 Andrea Spadaccini
      [script for script in what[constants.NV_USERSCRIPTS]
727 10b86782 Michael Hanselmann
       if not utils.IsExecutable(script)]
728 17b0b812 Andrea Spadaccini
729 16f41f24 René Nussbaumer
  if constants.NV_OOB_PATHS in what:
730 16f41f24 René Nussbaumer
    result[constants.NV_OOB_PATHS] = tmp = []
731 16f41f24 René Nussbaumer
    for path in what[constants.NV_OOB_PATHS]:
732 16f41f24 René Nussbaumer
      try:
733 16f41f24 René Nussbaumer
        st = os.stat(path)
734 16f41f24 René Nussbaumer
      except OSError, err:
735 16f41f24 René Nussbaumer
        tmp.append("error stating out of band helper: %s" % err)
736 16f41f24 René Nussbaumer
      else:
737 16f41f24 René Nussbaumer
        if stat.S_ISREG(st.st_mode):
738 16f41f24 René Nussbaumer
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
739 16f41f24 René Nussbaumer
            tmp.append(None)
740 16f41f24 René Nussbaumer
          else:
741 16f41f24 René Nussbaumer
            tmp.append("out of band helper %s is not executable" % path)
742 16f41f24 René Nussbaumer
        else:
743 16f41f24 René Nussbaumer
          tmp.append("out of band helper %s is not a file" % path)
744 16f41f24 René Nussbaumer
745 8964ee14 Iustin Pop
  if constants.NV_LVLIST in what and vm_capable:
746 ed904904 Iustin Pop
    try:
747 84d7e26b Dmitry Chernyak
      val = GetVolumeList(utils.ListVolumeGroups().keys())
748 ed904904 Iustin Pop
    except RPCFail, err:
749 ed904904 Iustin Pop
      val = str(err)
750 ed904904 Iustin Pop
    result[constants.NV_LVLIST] = val
751 25361b9a Iustin Pop
752 8964ee14 Iustin Pop
  if constants.NV_INSTANCELIST in what and vm_capable:
753 0cf5e7f5 Iustin Pop
    # GetInstanceList can fail
754 0cf5e7f5 Iustin Pop
    try:
755 0cf5e7f5 Iustin Pop
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
756 0cf5e7f5 Iustin Pop
    except RPCFail, err:
757 0cf5e7f5 Iustin Pop
      val = str(err)
758 0cf5e7f5 Iustin Pop
    result[constants.NV_INSTANCELIST] = val
759 25361b9a Iustin Pop
760 8964ee14 Iustin Pop
  if constants.NV_VGLIST in what and vm_capable:
761 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
762 25361b9a Iustin Pop
763 8964ee14 Iustin Pop
  if constants.NV_PVLIST in what and vm_capable:
764 d091393e Iustin Pop
    result[constants.NV_PVLIST] = \
765 d091393e Iustin Pop
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
766 d091393e Iustin Pop
                                   filter_allocatable=False)
767 d091393e Iustin Pop
768 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
769 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
770 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
771 25361b9a Iustin Pop
772 8964ee14 Iustin Pop
  if constants.NV_HVINFO in what and vm_capable:
773 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
774 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
775 9d4bfc96 Iustin Pop
776 8964ee14 Iustin Pop
  if constants.NV_DRBDLIST in what and vm_capable:
777 6d2e83d5 Iustin Pop
    try:
778 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
779 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
780 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
781 f6eaed12 Iustin Pop
      used_minors = str(err)
782 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
783 6d2e83d5 Iustin Pop
784 8964ee14 Iustin Pop
  if constants.NV_DRBDHELPER in what and vm_capable:
785 7ef40fbe Luca Bigliardi
    status = True
786 7ef40fbe Luca Bigliardi
    try:
787 7ef40fbe Luca Bigliardi
      payload = bdev.BaseDRBD.GetUsermodeHelper()
788 7ef40fbe Luca Bigliardi
    except errors.BlockDeviceError, err:
789 7ef40fbe Luca Bigliardi
      logging.error("Can't get DRBD usermode helper: %s", str(err))
790 7ef40fbe Luca Bigliardi
      status = False
791 7ef40fbe Luca Bigliardi
      payload = str(err)
792 7ef40fbe Luca Bigliardi
    result[constants.NV_DRBDHELPER] = (status, payload)
793 7ef40fbe Luca Bigliardi
794 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
795 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
796 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
797 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
798 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
799 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
800 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
801 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
802 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
803 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
804 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
805 313b2dd4 Michael Hanselmann
806 313b2dd4 Michael Hanselmann
  if constants.NV_TIME in what:
807 313b2dd4 Michael Hanselmann
    result[constants.NV_TIME] = utils.SplitTime(time.time())
808 313b2dd4 Michael Hanselmann
809 8964ee14 Iustin Pop
  if constants.NV_OSLIST in what and vm_capable:
810 b0d85178 Iustin Pop
    result[constants.NV_OSLIST] = DiagnoseOS()
811 b0d85178 Iustin Pop
812 20d317d4 Iustin Pop
  if constants.NV_BRIDGES in what and vm_capable:
813 20d317d4 Iustin Pop
    result[constants.NV_BRIDGES] = [bridge
814 20d317d4 Iustin Pop
                                    for bridge in what[constants.NV_BRIDGES]
815 20d317d4 Iustin Pop
                                    if not utils.BridgeExists(bridge)]
816 23e3c9b7 Michael Hanselmann
817 72b35807 Michael Hanselmann
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
818 72b35807 Michael Hanselmann
    result[constants.NV_FILE_STORAGE_PATHS] = \
819 72b35807 Michael Hanselmann
      bdev.ComputeWrongFileStoragePaths()
820 72b35807 Michael Hanselmann
821 c26a6bd2 Iustin Pop
  return result
822 a8083063 Iustin Pop
823 a8083063 Iustin Pop
824 2be7273c Apollon Oikonomopoulos
def GetBlockDevSizes(devices):
825 2be7273c Apollon Oikonomopoulos
  """Return the size of the given block devices
826 2be7273c Apollon Oikonomopoulos

827 2be7273c Apollon Oikonomopoulos
  @type devices: list
828 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
829 2be7273c Apollon Oikonomopoulos
  @rtype: dict
830 2be7273c Apollon Oikonomopoulos
  @return:
831 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
832 2be7273c Apollon Oikonomopoulos
    size in MiB.
833 2be7273c Apollon Oikonomopoulos

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

836 2be7273c Apollon Oikonomopoulos
  """
837 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
838 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
839 2be7273c Apollon Oikonomopoulos
840 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
841 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
842 2be7273c Apollon Oikonomopoulos
      continue
843 2be7273c Apollon Oikonomopoulos
844 2be7273c Apollon Oikonomopoulos
    try:
845 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
846 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
847 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
848 2be7273c Apollon Oikonomopoulos
      continue
849 2be7273c Apollon Oikonomopoulos
850 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
851 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
852 2be7273c Apollon Oikonomopoulos
      if result.failed:
853 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
854 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
855 2be7273c Apollon Oikonomopoulos
        continue
856 2be7273c Apollon Oikonomopoulos
857 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
858 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
859 2be7273c Apollon Oikonomopoulos
  return blockdevs
860 2be7273c Apollon Oikonomopoulos
861 2be7273c Apollon Oikonomopoulos
862 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
863 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
864 a8083063 Iustin Pop

865 84d7e26b Dmitry Chernyak
  @type vg_names: list
866 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
867 397693d3 Iustin Pop
      empty for all volume groups
868 10c2650b Iustin Pop
  @rtype: dict
869 10c2650b Iustin Pop
  @return:
870 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
871 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
872 10c2650b Iustin Pop

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

875 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
876 10c2650b Iustin Pop
      details.
877 a8083063 Iustin Pop

878 a8083063 Iustin Pop
  """
879 cb2037a2 Iustin Pop
  lvs = {}
880 d0c8c01d Iustin Pop
  sep = "|"
881 397693d3 Iustin Pop
  if not vg_names:
882 397693d3 Iustin Pop
    vg_names = []
883 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
884 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
885 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
886 a8083063 Iustin Pop
  if result.failed:
887 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
888 cb2037a2 Iustin Pop
889 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
890 df4c2628 Iustin Pop
    line = line.strip()
891 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
892 df4c2628 Iustin Pop
    if not match:
893 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
894 df4c2628 Iustin Pop
      continue
895 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
896 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
897 d0c8c01d Iustin Pop
    online = attr[5] == "o"
898 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
899 33f2a81a Iustin Pop
    if virtual:
900 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
901 33f2a81a Iustin Pop
      # don't really hold data
902 33f2a81a Iustin Pop
      continue
903 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
904 cb2037a2 Iustin Pop
905 cb2037a2 Iustin Pop
  return lvs
906 a8083063 Iustin Pop
907 a8083063 Iustin Pop
908 a8083063 Iustin Pop
def ListVolumeGroups():
909 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
910 a8083063 Iustin Pop

911 10c2650b Iustin Pop
  @rtype: dict
912 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
913 10c2650b Iustin Pop
      size of the volume
914 a8083063 Iustin Pop

915 a8083063 Iustin Pop
  """
916 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
917 a8083063 Iustin Pop
918 a8083063 Iustin Pop
919 dcb93971 Michael Hanselmann
def NodeVolumes():
920 dcb93971 Michael Hanselmann
  """List all volumes on this node.
921 dcb93971 Michael Hanselmann

922 10c2650b Iustin Pop
  @rtype: list
923 10c2650b Iustin Pop
  @return:
924 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
925 10c2650b Iustin Pop
      - name: the logical volume name,
926 10c2650b Iustin Pop
      - size: the size of the logical volume
927 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
928 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
929 10c2650b Iustin Pop

930 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
931 10c2650b Iustin Pop
    error.
932 10c2650b Iustin Pop

933 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
934 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
935 10c2650b Iustin Pop
    multiple times.
936 10c2650b Iustin Pop

937 dcb93971 Michael Hanselmann
  """
938 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
939 dcb93971 Michael Hanselmann
                         "--separator=|",
940 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
941 dcb93971 Michael Hanselmann
  if result.failed:
942 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
943 10bfe6cb Iustin Pop
          result.output)
944 dcb93971 Michael Hanselmann
945 dcb93971 Michael Hanselmann
  def parse_dev(dev):
946 d0c8c01d Iustin Pop
    return dev.split("(")[0]
947 89e5ab02 Iustin Pop
948 89e5ab02 Iustin Pop
  def handle_dev(dev):
949 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
950 dcb93971 Michael Hanselmann
951 dcb93971 Michael Hanselmann
  def map_line(line):
952 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
953 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
954 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
955 89e5ab02 Iustin Pop
956 89e5ab02 Iustin Pop
  all_devs = []
957 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
958 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
959 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
960 89e5ab02 Iustin Pop
    else:
961 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
962 89e5ab02 Iustin Pop
  return all_devs
963 dcb93971 Michael Hanselmann
964 dcb93971 Michael Hanselmann
965 a8083063 Iustin Pop
def BridgesExist(bridges_list):
966 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
967 a8083063 Iustin Pop

968 b1206984 Iustin Pop
  @rtype: boolean
969 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
970 a8083063 Iustin Pop

971 a8083063 Iustin Pop
  """
972 35c0c8da Iustin Pop
  missing = []
973 a8083063 Iustin Pop
  for bridge in bridges_list:
974 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
975 35c0c8da Iustin Pop
      missing.append(bridge)
976 a8083063 Iustin Pop
977 35c0c8da Iustin Pop
  if missing:
978 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
979 35c0c8da Iustin Pop
980 a8083063 Iustin Pop
981 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
982 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
983 a8083063 Iustin Pop

984 e69d05fd Iustin Pop
  @type hypervisor_list: list
985 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
986 e69d05fd Iustin Pop

987 e69d05fd Iustin Pop
  @rtype: list
988 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
989 10c2650b Iustin Pop
    - instance1.example.com
990 10c2650b Iustin Pop
    - instance2.example.com
991 a8083063 Iustin Pop

992 098c0958 Michael Hanselmann
  """
993 e69d05fd Iustin Pop
  results = []
994 e69d05fd Iustin Pop
  for hname in hypervisor_list:
995 e69d05fd Iustin Pop
    try:
996 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
997 e69d05fd Iustin Pop
      results.extend(names)
998 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
999 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
1000 aca13712 Iustin Pop
            hname, err, exc=True)
1001 a8083063 Iustin Pop
1002 e69d05fd Iustin Pop
  return results
1003 a8083063 Iustin Pop
1004 a8083063 Iustin Pop
1005 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
1006 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
1007 a8083063 Iustin Pop

1008 e69d05fd Iustin Pop
  @type instance: string
1009 e69d05fd Iustin Pop
  @param instance: the instance name
1010 e69d05fd Iustin Pop
  @type hname: string
1011 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1012 a8083063 Iustin Pop

1013 e69d05fd Iustin Pop
  @rtype: dict
1014 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1015 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1016 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1017 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1018 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1019 a8083063 Iustin Pop

1020 098c0958 Michael Hanselmann
  """
1021 a8083063 Iustin Pop
  output = {}
1022 a8083063 Iustin Pop
1023 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1024 a8083063 Iustin Pop
  if iinfo is not None:
1025 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1026 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1027 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1028 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1029 a8083063 Iustin Pop
1030 c26a6bd2 Iustin Pop
  return output
1031 a8083063 Iustin Pop
1032 a8083063 Iustin Pop
1033 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1034 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
1035 56e7640c Iustin Pop

1036 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1037 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1038 56e7640c Iustin Pop

1039 56e7640c Iustin Pop
  @rtype: tuple
1040 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1041 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1042 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1043 56e7640c Iustin Pop

1044 56e7640c Iustin Pop
  """
1045 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1046 afdc3985 Iustin Pop
  iname = instance.name
1047 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
1048 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1049 56e7640c Iustin Pop
1050 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1051 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1052 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1053 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1054 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1055 56e7640c Iustin Pop
1056 56e7640c Iustin Pop
1057 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
1058 a8083063 Iustin Pop
  """Gather data about all instances.
1059 a8083063 Iustin Pop

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

1064 e69d05fd Iustin Pop
  @type hypervisor_list: list
1065 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1066 e69d05fd Iustin Pop

1067 955db481 Guido Trotter
  @rtype: dict
1068 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1069 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1070 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1071 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1072 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1073 a8083063 Iustin Pop

1074 098c0958 Michael Hanselmann
  """
1075 a8083063 Iustin Pop
  output = {}
1076 a8083063 Iustin Pop
1077 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1078 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1079 e69d05fd Iustin Pop
    if iinfo:
1080 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1081 f23b5ae8 Iustin Pop
        value = {
1082 d0c8c01d Iustin Pop
          "memory": memory,
1083 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1084 d0c8c01d Iustin Pop
          "state": state,
1085 d0c8c01d Iustin Pop
          "time": times,
1086 e69d05fd Iustin Pop
          }
1087 b33b6f55 Iustin Pop
        if name in output:
1088 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1089 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1090 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1091 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1092 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1093 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1094 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1095 f23b5ae8 Iustin Pop
        output[name] = value
1096 a8083063 Iustin Pop
1097 c26a6bd2 Iustin Pop
  return output
1098 a8083063 Iustin Pop
1099 a8083063 Iustin Pop
1100 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1101 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1102 81a3406c Iustin Pop

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

1106 81a3406c Iustin Pop
  @type kind: string
1107 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1108 81a3406c Iustin Pop
  @type os_name: string
1109 81a3406c Iustin Pop
  @param os_name: the os name
1110 81a3406c Iustin Pop
  @type instance: string
1111 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1112 6aa7a354 Iustin Pop
  @type component: string or None
1113 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1114 6aa7a354 Iustin Pop
      transferred
1115 81a3406c Iustin Pop

1116 81a3406c Iustin Pop
  """
1117 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1118 6aa7a354 Iustin Pop
  if component:
1119 6aa7a354 Iustin Pop
    assert "/" not in component
1120 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1121 6aa7a354 Iustin Pop
  else:
1122 6aa7a354 Iustin Pop
    c_msg = ""
1123 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1124 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1125 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1126 81a3406c Iustin Pop
1127 81a3406c Iustin Pop
1128 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1129 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1130 a8083063 Iustin Pop

1131 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1132 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1133 e557bae9 Guido Trotter
  @type reinstall: boolean
1134 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1135 4a0e011f Iustin Pop
  @type debug: integer
1136 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1137 c26a6bd2 Iustin Pop
  @rtype: None
1138 a8083063 Iustin Pop

1139 a8083063 Iustin Pop
  """
1140 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1141 255dcebd Iustin Pop
1142 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1143 e557bae9 Guido Trotter
  if reinstall:
1144 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1145 a8083063 Iustin Pop
1146 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1147 decd5f45 Iustin Pop
1148 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1149 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1150 decd5f45 Iustin Pop
  if result.failed:
1151 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1152 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1153 18682bca Iustin Pop
                  result.output)
1154 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1155 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1156 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1157 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1158 decd5f45 Iustin Pop
1159 decd5f45 Iustin Pop
1160 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1161 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1162 decd5f45 Iustin Pop

1163 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1164 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1165 d15a9ad3 Guido Trotter
  @type old_name: string
1166 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1167 4a0e011f Iustin Pop
  @type debug: integer
1168 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1169 10c2650b Iustin Pop
  @rtype: boolean
1170 10c2650b Iustin Pop
  @return: the success of the operation
1171 decd5f45 Iustin Pop

1172 decd5f45 Iustin Pop
  """
1173 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1174 decd5f45 Iustin Pop
1175 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1176 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1177 decd5f45 Iustin Pop
1178 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1179 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1180 a8083063 Iustin Pop
1181 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1182 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1183 a8083063 Iustin Pop
1184 a8083063 Iustin Pop
  if result.failed:
1185 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1186 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1187 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1188 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1189 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1190 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1191 a8083063 Iustin Pop
1192 a8083063 Iustin Pop
1193 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
1194 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.DISK_LINKS_DIR, "%s%s%d" %
1195 3536c792 Iustin Pop
                        (instance_name, constants.DISK_SEPARATOR, idx))
1196 5282084b Iustin Pop
1197 5282084b Iustin Pop
1198 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1199 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1200 9332fd8a Iustin Pop

1201 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1202 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1203 9332fd8a Iustin Pop

1204 9332fd8a Iustin Pop

1205 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1206 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1207 5282084b Iustin Pop
  @param idx: the disk index
1208 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1209 9332fd8a Iustin Pop

1210 9332fd8a Iustin Pop
  """
1211 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1212 9332fd8a Iustin Pop
  try:
1213 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1214 5282084b Iustin Pop
  except OSError, err:
1215 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1216 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1217 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1218 9332fd8a Iustin Pop
        os.remove(link_name)
1219 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1220 9332fd8a Iustin Pop
    else:
1221 9332fd8a Iustin Pop
      raise
1222 9332fd8a Iustin Pop
1223 9332fd8a Iustin Pop
  return link_name
1224 9332fd8a Iustin Pop
1225 9332fd8a Iustin Pop
1226 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1227 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1228 3c9c571d Iustin Pop

1229 3c9c571d Iustin Pop
  """
1230 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1231 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1232 5282084b Iustin Pop
    if os.path.islink(link_name):
1233 3c9c571d Iustin Pop
      try:
1234 03dfa658 Iustin Pop
        os.remove(link_name)
1235 03dfa658 Iustin Pop
      except OSError:
1236 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1237 3c9c571d Iustin Pop
1238 3c9c571d Iustin Pop
1239 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1240 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1241 a8083063 Iustin Pop

1242 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1243 a8083063 Iustin Pop
  devices must be already assembled.
1244 a8083063 Iustin Pop

1245 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1246 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1247 069cfbf1 Iustin Pop
  @rtype: list
1248 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1249 10c2650b Iustin Pop

1250 a8083063 Iustin Pop
  """
1251 a8083063 Iustin Pop
  block_devices = []
1252 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1253 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1254 a8083063 Iustin Pop
    if device is None:
1255 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1256 a8083063 Iustin Pop
                                    str(disk))
1257 a8083063 Iustin Pop
    device.Open()
1258 9332fd8a Iustin Pop
    try:
1259 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1260 9332fd8a Iustin Pop
    except OSError, e:
1261 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1262 9332fd8a Iustin Pop
                                    e.strerror)
1263 9332fd8a Iustin Pop
1264 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1265 9332fd8a Iustin Pop
1266 a8083063 Iustin Pop
  return block_devices
1267 a8083063 Iustin Pop
1268 a8083063 Iustin Pop
1269 323f9095 Stephen Shirley
def StartInstance(instance, startup_paused):
1270 a8083063 Iustin Pop
  """Start an instance.
1271 a8083063 Iustin Pop

1272 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1273 e69d05fd Iustin Pop
  @param instance: the instance object
1274 323f9095 Stephen Shirley
  @type startup_paused: bool
1275 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1276 c26a6bd2 Iustin Pop
  @rtype: None
1277 a8083063 Iustin Pop

1278 098c0958 Michael Hanselmann
  """
1279 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1280 a8083063 Iustin Pop
1281 a8083063 Iustin Pop
  if instance.name in running_instances:
1282 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1283 c26a6bd2 Iustin Pop
    return
1284 a8083063 Iustin Pop
1285 a8083063 Iustin Pop
  try:
1286 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1287 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1288 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1289 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1290 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1291 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1292 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1293 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1294 a8083063 Iustin Pop
1295 a8083063 Iustin Pop
1296 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1297 a8083063 Iustin Pop
  """Shut an instance down.
1298 a8083063 Iustin Pop

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

1301 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1302 e69d05fd Iustin Pop
  @param instance: the instance object
1303 6263189c Guido Trotter
  @type timeout: integer
1304 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1305 c26a6bd2 Iustin Pop
  @rtype: None
1306 a8083063 Iustin Pop

1307 098c0958 Michael Hanselmann
  """
1308 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1309 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1310 c26a6bd2 Iustin Pop
  iname = instance.name
1311 a8083063 Iustin Pop
1312 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1313 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1314 c26a6bd2 Iustin Pop
    return
1315 a8083063 Iustin Pop
1316 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1317 3c0cdc83 Michael Hanselmann
    def __init__(self):
1318 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1319 a8083063 Iustin Pop
1320 3c0cdc83 Michael Hanselmann
    def __call__(self):
1321 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1322 3c0cdc83 Michael Hanselmann
        return
1323 3c0cdc83 Michael Hanselmann
1324 3c0cdc83 Michael Hanselmann
      try:
1325 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1326 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1327 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1328 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1329 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1330 3c0cdc83 Michael Hanselmann
          return
1331 3c0cdc83 Michael Hanselmann
1332 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1333 3c0cdc83 Michael Hanselmann
1334 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1335 3c0cdc83 Michael Hanselmann
1336 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1337 3c0cdc83 Michael Hanselmann
1338 3c0cdc83 Michael Hanselmann
  try:
1339 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1340 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1341 a8083063 Iustin Pop
    # the shutdown did not succeed
1342 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1343 a8083063 Iustin Pop
1344 a8083063 Iustin Pop
    try:
1345 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1346 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1347 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1348 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1349 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1350 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1351 a8083063 Iustin Pop
1352 a8083063 Iustin Pop
    time.sleep(1)
1353 3c0cdc83 Michael Hanselmann
1354 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1355 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1356 3c9c571d Iustin Pop
1357 f28ec899 Guido Trotter
  try:
1358 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1359 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1360 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1361 f28ec899 Guido Trotter
1362 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1363 a8083063 Iustin Pop
1364 a8083063 Iustin Pop
1365 17c3f802 Guido Trotter
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1366 007a2f3e Alexander Schreiber
  """Reboot an instance.
1367 007a2f3e Alexander Schreiber

1368 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1369 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1370 10c2650b Iustin Pop
  @type reboot_type: str
1371 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1372 10c2650b Iustin Pop
    constants:
1373 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1374 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1375 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1376 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1377 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1378 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1379 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1380 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1381 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1382 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1383 c26a6bd2 Iustin Pop
  @rtype: None
1384 007a2f3e Alexander Schreiber

1385 007a2f3e Alexander Schreiber
  """
1386 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1387 007a2f3e Alexander Schreiber
1388 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1389 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1390 007a2f3e Alexander Schreiber
1391 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1392 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1393 007a2f3e Alexander Schreiber
    try:
1394 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1395 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1396 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1397 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1398 007a2f3e Alexander Schreiber
    try:
1399 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1400 82bc21e2 Stephen Shirley
      return StartInstance(instance, False)
1401 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1402 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1403 007a2f3e Alexander Schreiber
  else:
1404 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1405 007a2f3e Alexander Schreiber
1406 007a2f3e Alexander Schreiber
1407 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1408 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1409 ebe466d8 Guido Trotter

1410 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1411 ebe466d8 Guido Trotter
  @param instance: the instance object
1412 ebe466d8 Guido Trotter
  @type memory: int
1413 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1414 ebe466d8 Guido Trotter
  @rtype: None
1415 ebe466d8 Guido Trotter

1416 ebe466d8 Guido Trotter
  """
1417 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1418 ebe466d8 Guido Trotter
  running = hyper.ListInstances()
1419 ebe466d8 Guido Trotter
  if instance.name not in running:
1420 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1421 ebe466d8 Guido Trotter
    return
1422 ebe466d8 Guido Trotter
  try:
1423 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1424 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1425 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1426 ebe466d8 Guido Trotter
1427 ebe466d8 Guido Trotter
1428 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1429 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1430 6906a9d8 Guido Trotter

1431 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1432 6906a9d8 Guido Trotter
  @param instance: the instance definition
1433 6906a9d8 Guido Trotter

1434 6906a9d8 Guido Trotter
  """
1435 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1436 cd42d0ad Guido Trotter
  try:
1437 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1438 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1439 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1440 c26a6bd2 Iustin Pop
  return info
1441 6906a9d8 Guido Trotter
1442 6906a9d8 Guido Trotter
1443 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1444 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1445 6906a9d8 Guido Trotter

1446 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1447 6906a9d8 Guido Trotter
  @param instance: the instance definition
1448 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1449 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1450 6906a9d8 Guido Trotter
  @type target: string
1451 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1452 6906a9d8 Guido Trotter

1453 6906a9d8 Guido Trotter
  """
1454 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1455 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1456 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1457 77fcff4a Apollon Oikonomopoulos
    # in any way
1458 77fcff4a Apollon Oikonomopoulos
    try:
1459 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1460 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1461 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1462 77fcff4a Apollon Oikonomopoulos
1463 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1464 cd42d0ad Guido Trotter
  try:
1465 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1466 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1467 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1468 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1469 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1470 6906a9d8 Guido Trotter
1471 6906a9d8 Guido Trotter
1472 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1473 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1474 6906a9d8 Guido Trotter

1475 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1476 6906a9d8 Guido Trotter
  @param instance: the instance definition
1477 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1478 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1479 6906a9d8 Guido Trotter
  @type success: boolean
1480 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1481 6906a9d8 Guido Trotter

1482 6906a9d8 Guido Trotter
  """
1483 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1484 cd42d0ad Guido Trotter
  try:
1485 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1486 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1487 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1488 6906a9d8 Guido Trotter
1489 6906a9d8 Guido Trotter
1490 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1491 2a10865c Iustin Pop
  """Migrates an instance to another node.
1492 2a10865c Iustin Pop

1493 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1494 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1495 9f0e6b37 Iustin Pop
  @type target: string
1496 9f0e6b37 Iustin Pop
  @param target: the target node name
1497 9f0e6b37 Iustin Pop
  @type live: boolean
1498 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1499 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1500 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1501 9f0e6b37 Iustin Pop

1502 2a10865c Iustin Pop
  """
1503 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1504 2a10865c Iustin Pop
1505 2a10865c Iustin Pop
  try:
1506 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1507 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1508 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1509 2a10865c Iustin Pop
1510 2a10865c Iustin Pop
1511 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1512 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1513 6a1434d7 Andrea Spadaccini

1514 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1515 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1516 6a1434d7 Andrea Spadaccini
  @type success: bool
1517 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1518 6a1434d7 Andrea Spadaccini
  @type live: bool
1519 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1520 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1521 6a1434d7 Andrea Spadaccini

1522 6a1434d7 Andrea Spadaccini
  """
1523 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1524 6a1434d7 Andrea Spadaccini
1525 6a1434d7 Andrea Spadaccini
  try:
1526 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1527 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1528 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1529 6a1434d7 Andrea Spadaccini
          exc=True)
1530 6a1434d7 Andrea Spadaccini
1531 6a1434d7 Andrea Spadaccini
1532 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1533 6a1434d7 Andrea Spadaccini
  """Get the migration status
1534 6a1434d7 Andrea Spadaccini

1535 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1536 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1537 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1538 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1539 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1540 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1541 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1542 6a1434d7 Andrea Spadaccini

1543 6a1434d7 Andrea Spadaccini
  """
1544 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1545 6a1434d7 Andrea Spadaccini
  try:
1546 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1547 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1548 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1549 6a1434d7 Andrea Spadaccini
1550 6a1434d7 Andrea Spadaccini
1551 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1552 a8083063 Iustin Pop
  """Creates a block device for an instance.
1553 a8083063 Iustin Pop

1554 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1555 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1556 b1206984 Iustin Pop
  @type size: int
1557 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1558 b1206984 Iustin Pop
  @type owner: str
1559 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1560 b1206984 Iustin Pop
      used for device cache data
1561 b1206984 Iustin Pop
  @type on_primary: boolean
1562 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1563 b1206984 Iustin Pop
  @type info: string
1564 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1565 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1566 b1206984 Iustin Pop

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

1571 a8083063 Iustin Pop
  """
1572 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
1573 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
1574 a8083063 Iustin Pop
  clist = []
1575 a8083063 Iustin Pop
  if disk.children:
1576 a8083063 Iustin Pop
    for child in disk.children:
1577 1063abd1 Iustin Pop
      try:
1578 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1579 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1580 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1581 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1582 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1583 a8083063 Iustin Pop
        # be assembled
1584 1063abd1 Iustin Pop
        try:
1585 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
1586 1063abd1 Iustin Pop
          crdev.Open()
1587 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1588 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1589 a8083063 Iustin Pop
      clist.append(crdev)
1590 a8083063 Iustin Pop
1591 dab69e97 Iustin Pop
  try:
1592 94dcbdb0 Andrea Spadaccini
    device = bdev.Create(disk, clist)
1593 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1594 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1595 6c626518 Iustin Pop
1596 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1597 1063abd1 Iustin Pop
    try:
1598 1063abd1 Iustin Pop
      device.Assemble()
1599 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1600 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1601 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1602 1063abd1 Iustin Pop
      try:
1603 1063abd1 Iustin Pop
        device.Open(force=True)
1604 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1605 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1606 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1607 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1608 a0c3fea1 Michael Hanselmann
1609 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1610 a0c3fea1 Michael Hanselmann
1611 c26a6bd2 Iustin Pop
  return device.unique_id
1612 a8083063 Iustin Pop
1613 a8083063 Iustin Pop
1614 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1615 69dd363f René Nussbaumer
  """This function actually wipes the device.
1616 69dd363f René Nussbaumer

1617 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1618 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1619 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1620 69dd363f René Nussbaumer

1621 69dd363f René Nussbaumer
  """
1622 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
1623 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
1624 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
1625 0188611b Michael Hanselmann
  block_size = 1024 * 1024
1626 0188611b Michael Hanselmann
1627 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1628 0188611b Michael Hanselmann
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1629 da63bb4e René Nussbaumer
         "count=%d" % size]
1630 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1631 69dd363f René Nussbaumer
1632 69dd363f René Nussbaumer
  if result.failed:
1633 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1634 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1635 69dd363f René Nussbaumer
1636 69dd363f René Nussbaumer
1637 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1638 69dd363f René Nussbaumer
  """Wipes a block device.
1639 69dd363f René Nussbaumer

1640 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1641 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1642 da63bb4e René Nussbaumer
  @type offset: int
1643 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1644 da63bb4e René Nussbaumer
  @type size: int
1645 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1646 69dd363f René Nussbaumer

1647 69dd363f René Nussbaumer
  """
1648 69dd363f René Nussbaumer
  try:
1649 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1650 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1651 da63bb4e René Nussbaumer
    rdev = None
1652 da63bb4e René Nussbaumer
1653 da63bb4e René Nussbaumer
  if not rdev:
1654 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1655 da63bb4e René Nussbaumer
1656 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1657 0188611b Michael Hanselmann
  if offset < 0:
1658 0188611b Michael Hanselmann
    _Fail("Negative offset")
1659 0188611b Michael Hanselmann
  if size < 0:
1660 0188611b Michael Hanselmann
    _Fail("Negative size")
1661 da63bb4e René Nussbaumer
  if offset > rdev.size:
1662 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1663 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1664 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1665 69dd363f René Nussbaumer
1666 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1667 69dd363f René Nussbaumer
1668 69dd363f René Nussbaumer
1669 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1670 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1671 5119c79e René Nussbaumer

1672 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1673 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1674 5119c79e René Nussbaumer
  @type pause: bool
1675 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1676 5119c79e René Nussbaumer

1677 5119c79e René Nussbaumer
  """
1678 5119c79e René Nussbaumer
  success = []
1679 5119c79e René Nussbaumer
  for disk in disks:
1680 5119c79e René Nussbaumer
    try:
1681 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1682 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1683 5119c79e René Nussbaumer
      rdev = None
1684 5119c79e René Nussbaumer
1685 5119c79e René Nussbaumer
    if not rdev:
1686 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1687 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1688 5119c79e René Nussbaumer
      continue
1689 5119c79e René Nussbaumer
1690 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1691 5119c79e René Nussbaumer
1692 5119c79e René Nussbaumer
    if result:
1693 5119c79e René Nussbaumer
      success.append((result, None))
1694 5119c79e René Nussbaumer
    else:
1695 5119c79e René Nussbaumer
      if pause:
1696 5119c79e René Nussbaumer
        msg = "Pause"
1697 5119c79e René Nussbaumer
      else:
1698 5119c79e René Nussbaumer
        msg = "Resume"
1699 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1700 5119c79e René Nussbaumer
1701 5119c79e René Nussbaumer
  return success
1702 5119c79e René Nussbaumer
1703 5119c79e René Nussbaumer
1704 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1705 a8083063 Iustin Pop
  """Remove a block device.
1706 a8083063 Iustin Pop

1707 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1708 10c2650b Iustin Pop

1709 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1710 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1711 10c2650b Iustin Pop
  @rtype: boolean
1712 10c2650b Iustin Pop
  @return: the success of the operation
1713 a8083063 Iustin Pop

1714 a8083063 Iustin Pop
  """
1715 e1bc0878 Iustin Pop
  msgs = []
1716 a8083063 Iustin Pop
  try:
1717 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1718 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1719 a8083063 Iustin Pop
    # probably can't attach
1720 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1721 a8083063 Iustin Pop
    rdev = None
1722 a8083063 Iustin Pop
  if rdev is not None:
1723 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1724 e1bc0878 Iustin Pop
    try:
1725 0c6c04ec Iustin Pop
      rdev.Remove()
1726 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1727 e1bc0878 Iustin Pop
      msgs.append(str(err))
1728 c26a6bd2 Iustin Pop
    if not msgs:
1729 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1730 e1bc0878 Iustin Pop
1731 a8083063 Iustin Pop
  if disk.children:
1732 a8083063 Iustin Pop
    for child in disk.children:
1733 c26a6bd2 Iustin Pop
      try:
1734 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1735 c26a6bd2 Iustin Pop
      except RPCFail, err:
1736 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1737 e1bc0878 Iustin Pop
1738 c26a6bd2 Iustin Pop
  if msgs:
1739 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1740 afdc3985 Iustin Pop
1741 a8083063 Iustin Pop
1742 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1743 a8083063 Iustin Pop
  """Activate a block device for an instance.
1744 a8083063 Iustin Pop

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

1747 10c2650b Iustin Pop
  @note: this function is called recursively.
1748 a8083063 Iustin Pop

1749 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1750 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1751 10c2650b Iustin Pop
  @type owner: str
1752 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1753 10c2650b Iustin Pop
  @type as_primary: boolean
1754 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1755 10c2650b Iustin Pop
      read/write
1756 a8083063 Iustin Pop

1757 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1758 10c2650b Iustin Pop
      was assembled)
1759 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1760 10c2650b Iustin Pop
      during the activation of the children or the device
1761 10c2650b Iustin Pop
      itself
1762 a8083063 Iustin Pop

1763 a8083063 Iustin Pop
  """
1764 a8083063 Iustin Pop
  children = []
1765 a8083063 Iustin Pop
  if disk.children:
1766 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1767 fc1dc9d7 Iustin Pop
    if mcn == -1:
1768 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1769 fc1dc9d7 Iustin Pop
    else:
1770 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1771 a8083063 Iustin Pop
    for chld_disk in disk.children:
1772 fc1dc9d7 Iustin Pop
      try:
1773 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1774 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1775 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1776 fc1dc9d7 Iustin Pop
          raise
1777 fc1dc9d7 Iustin Pop
        cdev = None
1778 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1779 1063abd1 Iustin Pop
                      str(err))
1780 fc1dc9d7 Iustin Pop
      children.append(cdev)
1781 a8083063 Iustin Pop
1782 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1783 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
1784 a8083063 Iustin Pop
    result = r_dev
1785 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1786 a8083063 Iustin Pop
      r_dev.Open()
1787 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1788 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1789 3f78eef2 Iustin Pop
1790 a8083063 Iustin Pop
  else:
1791 a8083063 Iustin Pop
    result = True
1792 a8083063 Iustin Pop
  return result
1793 a8083063 Iustin Pop
1794 a8083063 Iustin Pop
1795 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
1796 a8083063 Iustin Pop
  """Activate a block device for an instance.
1797 a8083063 Iustin Pop

1798 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1799 a8083063 Iustin Pop

1800 b1206984 Iustin Pop
  @rtype: str or boolean
1801 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1802 b1206984 Iustin Pop
      C{True} for secondary nodes
1803 a8083063 Iustin Pop

1804 a8083063 Iustin Pop
  """
1805 53c14ef1 Iustin Pop
  try:
1806 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1807 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1808 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
1809 53c14ef1 Iustin Pop
      result = result.dev_path
1810 c417e115 Iustin Pop
      if as_primary:
1811 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
1812 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1813 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1814 c417e115 Iustin Pop
  except OSError, err:
1815 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
1816 afdc3985 Iustin Pop
1817 c26a6bd2 Iustin Pop
  return result
1818 a8083063 Iustin Pop
1819 a8083063 Iustin Pop
1820 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1821 a8083063 Iustin Pop
  """Shut down a block device.
1822 a8083063 Iustin Pop

1823 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1824 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1825 c41eea6e Iustin Pop
  shutdown.
1826 a8083063 Iustin Pop

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

1831 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1832 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1833 10c2650b Iustin Pop
      shutdown
1834 c26a6bd2 Iustin Pop
  @rtype: None
1835 10c2650b Iustin Pop

1836 a8083063 Iustin Pop
  """
1837 cacfd1fd Iustin Pop
  msgs = []
1838 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1839 a8083063 Iustin Pop
  if r_dev is not None:
1840 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1841 cacfd1fd Iustin Pop
    try:
1842 746f7476 Iustin Pop
      r_dev.Shutdown()
1843 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1844 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1845 cacfd1fd Iustin Pop
      msgs.append(str(err))
1846 746f7476 Iustin Pop
1847 a8083063 Iustin Pop
  if disk.children:
1848 a8083063 Iustin Pop
    for child in disk.children:
1849 c26a6bd2 Iustin Pop
      try:
1850 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1851 c26a6bd2 Iustin Pop
      except RPCFail, err:
1852 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1853 746f7476 Iustin Pop
1854 c26a6bd2 Iustin Pop
  if msgs:
1855 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1856 a8083063 Iustin Pop
1857 a8083063 Iustin Pop
1858 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1859 153d9724 Iustin Pop
  """Extend a mirrored block device.
1860 a8083063 Iustin Pop

1861 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1862 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1863 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1864 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1865 c26a6bd2 Iustin Pop
  @rtype: None
1866 10c2650b Iustin Pop

1867 a8083063 Iustin Pop
  """
1868 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1869 153d9724 Iustin Pop
  if parent_bdev is None:
1870 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1871 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1872 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1873 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1874 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1875 a8083063 Iustin Pop
1876 a8083063 Iustin Pop
1877 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1878 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1879 a8083063 Iustin Pop

1880 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1881 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1882 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1883 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1884 c26a6bd2 Iustin Pop
  @rtype: None
1885 10c2650b Iustin Pop

1886 a8083063 Iustin Pop
  """
1887 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1888 153d9724 Iustin Pop
  if parent_bdev is None:
1889 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1890 e739bd57 Iustin Pop
  devs = []
1891 e739bd57 Iustin Pop
  for disk in new_cdevs:
1892 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1893 e739bd57 Iustin Pop
    if rpath is None:
1894 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1895 e739bd57 Iustin Pop
      if bd is None:
1896 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1897 e739bd57 Iustin Pop
      else:
1898 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1899 e739bd57 Iustin Pop
    else:
1900 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1901 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1902 e739bd57 Iustin Pop
      devs.append(rpath)
1903 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1904 a8083063 Iustin Pop
1905 a8083063 Iustin Pop
1906 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1907 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1908 a8083063 Iustin Pop

1909 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1910 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1911 10c2650b Iustin Pop
  @rtype: disk
1912 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1913 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1914 10c2650b Iustin Pop
      found
1915 a8083063 Iustin Pop

1916 a8083063 Iustin Pop
  """
1917 a8083063 Iustin Pop
  stats = []
1918 a8083063 Iustin Pop
  for dsk in disks:
1919 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1920 a8083063 Iustin Pop
    if rbd is None:
1921 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1922 96acbc09 Michael Hanselmann
1923 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1924 96acbc09 Michael Hanselmann
1925 c26a6bd2 Iustin Pop
  return stats
1926 a8083063 Iustin Pop
1927 a8083063 Iustin Pop
1928 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1929 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1930 c6a9dffa Michael Hanselmann

1931 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1932 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1933 c6a9dffa Michael Hanselmann
  @rtype: disk
1934 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1935 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
1936 c6a9dffa Michael Hanselmann
    otherwise
1937 c6a9dffa Michael Hanselmann

1938 c6a9dffa Michael Hanselmann
  """
1939 c6a9dffa Michael Hanselmann
  result = []
1940 c6a9dffa Michael Hanselmann
  for disk in disks:
1941 c6a9dffa Michael Hanselmann
    try:
1942 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
1943 c6a9dffa Michael Hanselmann
      if rbd is None:
1944 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
1945 c6a9dffa Michael Hanselmann
        continue
1946 c6a9dffa Michael Hanselmann
1947 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
1948 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
1949 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
1950 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
1951 c6a9dffa Michael Hanselmann
    else:
1952 c6a9dffa Michael Hanselmann
      result.append((True, status))
1953 c6a9dffa Michael Hanselmann
1954 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
1955 c6a9dffa Michael Hanselmann
1956 c6a9dffa Michael Hanselmann
  return result
1957 c6a9dffa Michael Hanselmann
1958 c6a9dffa Michael Hanselmann
1959 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1960 a8083063 Iustin Pop
  """Check if a device is activated.
1961 a8083063 Iustin Pop

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

1964 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1965 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1966 a8083063 Iustin Pop

1967 10c2650b Iustin Pop
  @return: None if the device can't be found,
1968 10c2650b Iustin Pop
      otherwise the device instance
1969 a8083063 Iustin Pop

1970 a8083063 Iustin Pop
  """
1971 a8083063 Iustin Pop
  children = []
1972 a8083063 Iustin Pop
  if disk.children:
1973 a8083063 Iustin Pop
    for chdisk in disk.children:
1974 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1975 a8083063 Iustin Pop
1976 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
1977 a8083063 Iustin Pop
1978 a8083063 Iustin Pop
1979 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1980 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1981 f2e07bb4 Michael Hanselmann

1982 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1983 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1984 f2e07bb4 Michael Hanselmann

1985 f2e07bb4 Michael Hanselmann
  """
1986 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1987 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1988 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1989 f2e07bb4 Michael Hanselmann
1990 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1991 f2e07bb4 Michael Hanselmann
1992 f2e07bb4 Michael Hanselmann
  return real_disk
1993 f2e07bb4 Michael Hanselmann
1994 f2e07bb4 Michael Hanselmann
1995 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1996 a8083063 Iustin Pop
  """Check if a device is activated.
1997 a8083063 Iustin Pop

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

2000 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2001 10c2650b Iustin Pop
  @param disk: the disk to find
2002 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2003 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2004 96acbc09 Michael Hanselmann
           information
2005 a8083063 Iustin Pop

2006 a8083063 Iustin Pop
  """
2007 23829f6f Iustin Pop
  try:
2008 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
2009 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
2010 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
2011 96acbc09 Michael Hanselmann
2012 a8083063 Iustin Pop
  if rbd is None:
2013 c26a6bd2 Iustin Pop
    return None
2014 96acbc09 Michael Hanselmann
2015 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2016 a8083063 Iustin Pop
2017 a8083063 Iustin Pop
2018 968a7623 Iustin Pop
def BlockdevGetsize(disks):
2019 968a7623 Iustin Pop
  """Computes the size of the given disks.
2020 968a7623 Iustin Pop

2021 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2022 968a7623 Iustin Pop

2023 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2024 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2025 968a7623 Iustin Pop
  @rtype: list
2026 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2027 968a7623 Iustin Pop
      otherwise the size
2028 968a7623 Iustin Pop

2029 968a7623 Iustin Pop
  """
2030 968a7623 Iustin Pop
  result = []
2031 968a7623 Iustin Pop
  for cf in disks:
2032 968a7623 Iustin Pop
    try:
2033 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2034 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2035 968a7623 Iustin Pop
      result.append(None)
2036 968a7623 Iustin Pop
      continue
2037 968a7623 Iustin Pop
    if rbd is None:
2038 968a7623 Iustin Pop
      result.append(None)
2039 968a7623 Iustin Pop
    else:
2040 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
2041 968a7623 Iustin Pop
  return result
2042 968a7623 Iustin Pop
2043 968a7623 Iustin Pop
2044 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2045 858f3d18 Iustin Pop
  """Export a block device to a remote node.
2046 858f3d18 Iustin Pop

2047 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
2048 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
2049 858f3d18 Iustin Pop
  @type dest_node: str
2050 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
2051 858f3d18 Iustin Pop
  @type dest_path: str
2052 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
2053 858f3d18 Iustin Pop
  @type cluster_name: str
2054 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2055 858f3d18 Iustin Pop
  @rtype: None
2056 858f3d18 Iustin Pop

2057 858f3d18 Iustin Pop
  """
2058 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
2059 858f3d18 Iustin Pop
2060 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
2061 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2062 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
2063 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
2064 858f3d18 Iustin Pop
2065 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
2066 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
2067 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
2068 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2069 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
2070 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
2071 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2072 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
2073 858f3d18 Iustin Pop
2074 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2075 052783ff Michael Hanselmann
                                                   constants.SSH_LOGIN_USER,
2076 858f3d18 Iustin Pop
                                                   destcmd)
2077 858f3d18 Iustin Pop
2078 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
2079 d0c8c01d Iustin Pop
  command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2080 858f3d18 Iustin Pop
2081 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
2082 858f3d18 Iustin Pop
2083 858f3d18 Iustin Pop
  if result.failed:
2084 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
2085 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
2086 858f3d18 Iustin Pop
2087 858f3d18 Iustin Pop
2088 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2089 a8083063 Iustin Pop
  """Write a file to the filesystem.
2090 a8083063 Iustin Pop

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

2094 10c2650b Iustin Pop
  @type file_name: str
2095 10c2650b Iustin Pop
  @param file_name: the target file name
2096 10c2650b Iustin Pop
  @type data: str
2097 10c2650b Iustin Pop
  @param data: the new contents of the file
2098 10c2650b Iustin Pop
  @type mode: int
2099 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2100 9a914f7a René Nussbaumer
  @type uid: string
2101 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2102 9a914f7a René Nussbaumer
  @type gid: string
2103 9a914f7a René Nussbaumer
  @param gid: the group of the file
2104 10c2650b Iustin Pop
  @type atime: float
2105 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2106 10c2650b Iustin Pop
  @type mtime: float
2107 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2108 c26a6bd2 Iustin Pop
  @rtype: None
2109 10c2650b Iustin Pop

2110 a8083063 Iustin Pop
  """
2111 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2112 cffbbae7 Michael Hanselmann
2113 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2114 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2115 a8083063 Iustin Pop
2116 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2117 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2118 2cc6781a Iustin Pop
          file_name)
2119 a8083063 Iustin Pop
2120 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2121 12bce260 Michael Hanselmann
2122 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2123 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2124 9a914f7a René Nussbaumer
2125 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2126 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2127 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2128 9a914f7a René Nussbaumer
2129 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2130 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2131 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2132 a8083063 Iustin Pop
2133 386b57af Iustin Pop
2134 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2135 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2136 b2f29800 René Nussbaumer

2137 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2138 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2139 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2140 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2141 b2f29800 René Nussbaumer

2142 b2f29800 René Nussbaumer
  @return: stdout
2143 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2144 b2f29800 René Nussbaumer

2145 b2f29800 René Nussbaumer
  """
2146 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2147 b2f29800 René Nussbaumer
2148 b2f29800 René Nussbaumer
  if result.failed:
2149 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2150 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2151 b2f29800 René Nussbaumer
2152 b2f29800 René Nussbaumer
  return result.stdout
2153 b2f29800 René Nussbaumer
2154 b2f29800 René Nussbaumer
2155 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2156 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2157 a8083063 Iustin Pop

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

2161 10c2650b Iustin Pop
  @type os_dir: str
2162 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2163 8e70b181 Iustin Pop
  @rtype: tuple
2164 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2165 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2166 a8083063 Iustin Pop

2167 a8083063 Iustin Pop
  """
2168 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2169 a8083063 Iustin Pop
2170 a8083063 Iustin Pop
  try:
2171 a8083063 Iustin Pop
    st = os.stat(api_file)
2172 a8083063 Iustin Pop
  except EnvironmentError, err:
2173 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2174 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2175 a8083063 Iustin Pop
2176 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2177 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2178 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2179 a8083063 Iustin Pop
2180 a8083063 Iustin Pop
  try:
2181 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2182 a8083063 Iustin Pop
  except EnvironmentError, err:
2183 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2184 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2185 a8083063 Iustin Pop
2186 a8083063 Iustin Pop
  try:
2187 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2188 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2189 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2190 255dcebd Iustin Pop
                   str(err))
2191 a8083063 Iustin Pop
2192 255dcebd Iustin Pop
  return True, api_versions
2193 a8083063 Iustin Pop
2194 386b57af Iustin Pop
2195 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2196 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2197 a8083063 Iustin Pop

2198 10c2650b Iustin Pop
  @type top_dirs: list
2199 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2200 10c2650b Iustin Pop
      search (if not given defaults to
2201 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2202 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2203 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2204 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2205 bad78e66 Iustin Pop
      search paths, where:
2206 255dcebd Iustin Pop
          - name is the (potential) OS name
2207 255dcebd Iustin Pop
          - path is the full path to the OS
2208 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2209 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2210 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2211 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2212 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2213 a8083063 Iustin Pop

2214 a8083063 Iustin Pop
  """
2215 7c3d51d4 Guido Trotter
  if top_dirs is None:
2216 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2217 a8083063 Iustin Pop
2218 a8083063 Iustin Pop
  result = []
2219 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2220 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2221 7c3d51d4 Guido Trotter
      try:
2222 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2223 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2224 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2225 7c3d51d4 Guido Trotter
        break
2226 7c3d51d4 Guido Trotter
      for name in f_names:
2227 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2228 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2229 255dcebd Iustin Pop
        if status:
2230 255dcebd Iustin Pop
          diagnose = ""
2231 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2232 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2233 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2234 255dcebd Iustin Pop
        else:
2235 255dcebd Iustin Pop
          diagnose = os_inst
2236 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2237 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2238 bad78e66 Iustin Pop
                       parameters, api_versions))
2239 a8083063 Iustin Pop
2240 c26a6bd2 Iustin Pop
  return result
2241 a8083063 Iustin Pop
2242 a8083063 Iustin Pop
2243 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2244 a8083063 Iustin Pop
  """Create an OS instance from disk.
2245 a8083063 Iustin Pop

2246 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2247 8e70b181 Iustin Pop
  valid OS name.
2248 a8083063 Iustin Pop

2249 8ee4dc80 Guido Trotter
  @type base_dir: string
2250 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2251 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2252 255dcebd Iustin Pop
  @rtype: tuple
2253 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2254 255dcebd Iustin Pop
      or error message
2255 7c3d51d4 Guido Trotter

2256 a8083063 Iustin Pop
  """
2257 56bcd3f4 Guido Trotter
  if base_dir is None:
2258 710f30ec Michael Hanselmann
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2259 c34c0cfd Iustin Pop
  else:
2260 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2261 f95c81bf Iustin Pop
2262 f95c81bf Iustin Pop
  if os_dir is None:
2263 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
2264 a8083063 Iustin Pop
2265 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2266 255dcebd Iustin Pop
  if not status:
2267 255dcebd Iustin Pop
    # push the error up
2268 255dcebd Iustin Pop
    return status, api_versions
2269 a8083063 Iustin Pop
2270 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2271 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2272 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2273 a8083063 Iustin Pop
2274 35007011 Iustin Pop
  # OS Files dictionary, we will populate it with the absolute path
2275 35007011 Iustin Pop
  # names; if the value is True, then it is a required file, otherwise
2276 35007011 Iustin Pop
  # an optional one
2277 35007011 Iustin Pop
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2278 a8083063 Iustin Pop
2279 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
2280 35007011 Iustin Pop
    os_files[constants.OS_VARIANTS_FILE] = False
2281 95075fba Guido Trotter
2282 c7d04a6b Iustin Pop
  if max(api_versions) >= constants.OS_API_V20:
2283 35007011 Iustin Pop
    os_files[constants.OS_PARAMETERS_FILE] = True
2284 c7d04a6b Iustin Pop
  else:
2285 c7d04a6b Iustin Pop
    del os_files[constants.OS_SCRIPT_VERIFY]
2286 c7d04a6b Iustin Pop
2287 35007011 Iustin Pop
  for (filename, required) in os_files.items():
2288 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
2289 a8083063 Iustin Pop
2290 a8083063 Iustin Pop
    try:
2291 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
2292 a8083063 Iustin Pop
    except EnvironmentError, err:
2293 35007011 Iustin Pop
      if err.errno == errno.ENOENT and not required:
2294 35007011 Iustin Pop
        del os_files[filename]
2295 35007011 Iustin Pop
        continue
2296 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
2297 eb93b673 Guido Trotter
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2298 a8083063 Iustin Pop
2299 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2300 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
2301 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
2302 255dcebd Iustin Pop
2303 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
2304 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2305 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
2306 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
2307 0757c107 Guido Trotter
2308 845da3e8 Iustin Pop
  variants = []
2309 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
2310 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2311 95075fba Guido Trotter
    try:
2312 5a7cb9d3 Iustin Pop
      variants = \
2313 5a7cb9d3 Iustin Pop
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2314 95075fba Guido Trotter
    except EnvironmentError, err:
2315 35007011 Iustin Pop
      # we accept missing files, but not other errors
2316 35007011 Iustin Pop
      if err.errno != errno.ENOENT:
2317 35007011 Iustin Pop
        return False, ("Error while reading the OS variants file at %s: %s" %
2318 eb93b673 Guido Trotter
                       (variants_file, utils.ErrnoOrStr(err)))
2319 0757c107 Guido Trotter
2320 c7d04a6b Iustin Pop
  parameters = []
2321 c7d04a6b Iustin Pop
  if constants.OS_PARAMETERS_FILE in os_files:
2322 c7d04a6b Iustin Pop
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2323 c7d04a6b Iustin Pop
    try:
2324 c7d04a6b Iustin Pop
      parameters = utils.ReadFile(parameters_file).splitlines()
2325 c7d04a6b Iustin Pop
    except EnvironmentError, err:
2326 c7d04a6b Iustin Pop
      return False, ("Error while reading the OS parameters file at %s: %s" %
2327 eb93b673 Guido Trotter
                     (parameters_file, utils.ErrnoOrStr(err)))
2328 c7d04a6b Iustin Pop
    parameters = [v.split(None, 1) for v in parameters]
2329 c7d04a6b Iustin Pop
2330 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
2331 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2332 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2333 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2334 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2335 40684c3a Iustin Pop
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2336 40684c3a Iustin Pop
                                                 None),
2337 95075fba Guido Trotter
                      supported_variants=variants,
2338 c7d04a6b Iustin Pop
                      supported_parameters=parameters,
2339 255dcebd Iustin Pop
                      api_versions=api_versions)
2340 255dcebd Iustin Pop
  return True, os_obj
2341 255dcebd Iustin Pop
2342 255dcebd Iustin Pop
2343 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
2344 255dcebd Iustin Pop
  """Create an OS instance from disk.
2345 255dcebd Iustin Pop

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

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

2353 255dcebd Iustin Pop
  @type base_dir: string
2354 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2355 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2356 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2357 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2358 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2359 255dcebd Iustin Pop

2360 255dcebd Iustin Pop
  """
2361 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2362 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2363 255dcebd Iustin Pop
2364 255dcebd Iustin Pop
  if not status:
2365 255dcebd Iustin Pop
    _Fail(payload)
2366 a8083063 Iustin Pop
2367 255dcebd Iustin Pop
  return payload
2368 a8083063 Iustin Pop
2369 a8083063 Iustin Pop
2370 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2371 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2372 2266edb2 Guido Trotter

2373 a025e535 Vitaly Kuznetsov
  @type os_name: str
2374 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2375 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2376 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2377 1bdcbbab Iustin Pop
  @type os_params: dict
2378 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2379 2266edb2 Guido Trotter
  @type debug: integer
2380 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2381 2266edb2 Guido Trotter
  @rtype: dict
2382 2266edb2 Guido Trotter
  @return: dict of environment variables
2383 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2384 10c2650b Iustin Pop
      cannot be found
2385 2266edb2 Guido Trotter

2386 2266edb2 Guido Trotter
  """
2387 2266edb2 Guido Trotter
  result = {}
2388 099c52ad Iustin Pop
  api_version = \
2389 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2390 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2391 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2392 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2393 efaa9b06 Iustin Pop
2394 efaa9b06 Iustin Pop
  # OS variants
2395 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2396 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2397 870dc44c Iustin Pop
    if not variant:
2398 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2399 35007011 Iustin Pop
  else:
2400 35007011 Iustin Pop
    variant = ""
2401 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2402 efaa9b06 Iustin Pop
2403 1bdcbbab Iustin Pop
  # OS params
2404 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2405 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2406 1bdcbbab Iustin Pop
2407 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
2408 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
2409 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
2410 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
2411 9a6ade06 Iustin Pop
2412 efaa9b06 Iustin Pop
  return result
2413 efaa9b06 Iustin Pop
2414 efaa9b06 Iustin Pop
2415 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2416 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2417 efaa9b06 Iustin Pop

2418 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2419 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2420 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2421 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2422 efaa9b06 Iustin Pop
  @type debug: integer
2423 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2424 efaa9b06 Iustin Pop
  @rtype: dict
2425 efaa9b06 Iustin Pop
  @return: dict of environment variables
2426 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2427 efaa9b06 Iustin Pop
      cannot be found
2428 efaa9b06 Iustin Pop

2429 efaa9b06 Iustin Pop
  """
2430 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2431 efaa9b06 Iustin Pop
2432 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2433 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2434 f2165b8a Iustin Pop
2435 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2436 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2437 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2438 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2439 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2440 efaa9b06 Iustin Pop
2441 efaa9b06 Iustin Pop
  # Disks
2442 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2443 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2444 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2445 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2446 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2447 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2448 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2449 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2450 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2451 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2452 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2453 d0c8c01d Iustin Pop
        "file:%s" % disk.physical_id[0]
2454 efaa9b06 Iustin Pop
2455 efaa9b06 Iustin Pop
  # NICs
2456 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2457 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2458 2266edb2 Guido Trotter
    if nic.ip:
2459 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2460 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2461 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2462 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2463 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2464 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2465 a5ad5e58 Apollon Oikonomopoulos
    if nic.network:
2466 a5ad5e58 Apollon Oikonomopoulos
      result["NIC_%d_NETWORK" % idx] = nic.network
2467 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2468 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2469 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2470 2266edb2 Guido Trotter
2471 efaa9b06 Iustin Pop
  # HV/BE params
2472 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2473 67fc3042 Iustin Pop
    for key, value in source.items():
2474 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2475 67fc3042 Iustin Pop
2476 2266edb2 Guido Trotter
  return result
2477 a8083063 Iustin Pop
2478 f2e07bb4 Michael Hanselmann
2479 cad0723b Iustin Pop
def BlockdevGrow(disk, amount, dryrun, backingstore):
2480 594609c0 Iustin Pop
  """Grow a stack of block devices.
2481 594609c0 Iustin Pop

2482 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2483 10c2650b Iustin Pop
  first ones to resize.
2484 594609c0 Iustin Pop

2485 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2486 10c2650b Iustin Pop
  @param disk: the disk to be grown
2487 a59faf4b Iustin Pop
  @type amount: integer
2488 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2489 a59faf4b Iustin Pop
  @type dryrun: boolean
2490 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2491 a59faf4b Iustin Pop
      only, without actually increasing the size
2492 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
2493 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2494 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
2495 10c2650b Iustin Pop
  @rtype: (status, result)
2496 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2497 a59faf4b Iustin Pop
      the errors message if status is False
2498 594609c0 Iustin Pop

2499 594609c0 Iustin Pop
  """
2500 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2501 594609c0 Iustin Pop
  if r_dev is None:
2502 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2503 594609c0 Iustin Pop
2504 594609c0 Iustin Pop
  try:
2505 cad0723b Iustin Pop
    r_dev.Grow(amount, dryrun, backingstore)
2506 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2507 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2508 594609c0 Iustin Pop
2509 594609c0 Iustin Pop
2510 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2511 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2512 a8083063 Iustin Pop

2513 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2514 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2515 a8083063 Iustin Pop

2516 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2517 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2518 e9e9263d Guido Trotter
  @rtype: string
2519 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2520 a8083063 Iustin Pop

2521 098c0958 Michael Hanselmann
  """
2522 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2523 433c63aa Iustin Pop
    if not disk.children:
2524 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2525 433c63aa Iustin Pop
            disk.unique_id)
2526 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2527 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2528 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2529 a8083063 Iustin Pop
    if r_dev is not None:
2530 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2531 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2532 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2533 a8083063 Iustin Pop
    else:
2534 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2535 a8083063 Iustin Pop
  else:
2536 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2537 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2538 a8083063 Iustin Pop
2539 a8083063 Iustin Pop
2540 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
2541 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
2542 48e175a2 Iustin Pop

2543 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
2544 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
2545 48e175a2 Iustin Pop
  for example after renames.
2546 48e175a2 Iustin Pop

2547 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
2548 48e175a2 Iustin Pop
  @param disk: the disk to be grown
2549 48e175a2 Iustin Pop
  @type info: string
2550 48e175a2 Iustin Pop
  @param info: new 'info' metadata
2551 48e175a2 Iustin Pop
  @rtype: (status, result)
2552 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2553 48e175a2 Iustin Pop
      the errors message if status is False
2554 48e175a2 Iustin Pop

2555 48e175a2 Iustin Pop
  """
2556 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2557 48e175a2 Iustin Pop
  if r_dev is None:
2558 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2559 48e175a2 Iustin Pop
2560 48e175a2 Iustin Pop
  try:
2561 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
2562 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
2563 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
2564 48e175a2 Iustin Pop
2565 48e175a2 Iustin Pop
2566 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2567 a8083063 Iustin Pop
  """Write out the export configuration information.
2568 a8083063 Iustin Pop

2569 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2570 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2571 10c2650b Iustin Pop
      saving configuration
2572 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2573 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2574 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2575 a8083063 Iustin Pop

2576 c26a6bd2 Iustin Pop
  @rtype: None
2577 a8083063 Iustin Pop

2578 098c0958 Michael Hanselmann
  """
2579 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2580 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2581 a8083063 Iustin Pop
2582 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2583 a8083063 Iustin Pop
2584 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2585 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
2586 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2587 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2588 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
2589 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2590 a8083063 Iustin Pop
2591 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2592 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
2593 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2594 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2595 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
2596 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
2597 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2598 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
2599 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2600 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2601 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2602 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2603 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2604 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2605 66f93869 Manuel Franceschini
2606 95268cc3 Iustin Pop
  nic_total = 0
2607 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2608 95268cc3 Iustin Pop
    nic_total += 1
2609 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
2610 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
2611 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2612 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2613 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
2614 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2615 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2616 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
2617 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2618 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2619 a8083063 Iustin Pop
2620 726d7d68 Iustin Pop
  disk_total = 0
2621 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2622 19d7f90a Guido Trotter
    if disk:
2623 726d7d68 Iustin Pop
      disk_total += 1
2624 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2625 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
2626 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2627 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
2628 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2629 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
2630 d0c8c01d Iustin Pop
2631 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2632 a8083063 Iustin Pop
2633 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2634 3c8954ad Iustin Pop
2635 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2636 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2637 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2638 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2639 3c8954ad Iustin Pop
2640 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2641 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2642 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2643 3c8954ad Iustin Pop
2644 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2645 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2646 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2647 535b49cb Iustin Pop
2648 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2649 726d7d68 Iustin Pop
                  data=config.Dumps())
2650 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2651 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2652 a8083063 Iustin Pop
2653 a8083063 Iustin Pop
2654 a8083063 Iustin Pop
def ExportInfo(dest):
2655 a8083063 Iustin Pop
  """Get export configuration information.
2656 a8083063 Iustin Pop

2657 10c2650b Iustin Pop
  @type dest: str
2658 10c2650b Iustin Pop
  @param dest: directory containing the export
2659 a8083063 Iustin Pop

2660 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2661 10c2650b Iustin Pop
  @return: a serializable config file containing the
2662 10c2650b Iustin Pop
      export info
2663 a8083063 Iustin Pop

2664 a8083063 Iustin Pop
  """
2665 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2666 a8083063 Iustin Pop
2667 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2668 a8083063 Iustin Pop
  config.read(cff)
2669 a8083063 Iustin Pop
2670 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2671 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2672 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2673 a8083063 Iustin Pop
2674 c26a6bd2 Iustin Pop
  return config.Dumps()
2675 a8083063 Iustin Pop
2676 a8083063 Iustin Pop
2677 a8083063 Iustin Pop
def ListExports():
2678 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2679 098c0958 Michael Hanselmann

2680 10c2650b Iustin Pop
  @rtype: list
2681 10c2650b Iustin Pop
  @return: list of the exports
2682 10c2650b Iustin Pop

2683 a8083063 Iustin Pop
  """
2684 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
2685 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2686 a8083063 Iustin Pop
  else:
2687 afdc3985 Iustin Pop
    _Fail("No exports directory")
2688 a8083063 Iustin Pop
2689 a8083063 Iustin Pop
2690 a8083063 Iustin Pop
def RemoveExport(export):
2691 a8083063 Iustin Pop
  """Remove an existing export from the node.
2692 a8083063 Iustin Pop

2693 10c2650b Iustin Pop
  @type export: str
2694 10c2650b Iustin Pop
  @param export: the name of the export to remove
2695 c26a6bd2 Iustin Pop
  @rtype: None
2696 a8083063 Iustin Pop

2697 098c0958 Michael Hanselmann
  """
2698 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2699 a8083063 Iustin Pop
2700 35fbcd11 Iustin Pop
  try:
2701 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2702 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2703 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2704 a8083063 Iustin Pop
2705 a8083063 Iustin Pop
2706 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2707 f3e513ad Iustin Pop
  """Rename a list of block devices.
2708 f3e513ad Iustin Pop

2709 10c2650b Iustin Pop
  @type devlist: list of tuples
2710 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2711 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2712 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2713 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2714 10c2650b Iustin Pop
      rename it to
2715 10c2650b Iustin Pop
  @rtype: boolean
2716 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2717 f3e513ad Iustin Pop

2718 f3e513ad Iustin Pop
  """
2719 6b5e3f70 Iustin Pop
  msgs = []
2720 f3e513ad Iustin Pop
  result = True
2721 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2722 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2723 f3e513ad Iustin Pop
    if dev is None:
2724 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2725 f3e513ad Iustin Pop
      result = False
2726 f3e513ad Iustin Pop
      continue
2727 f3e513ad Iustin Pop
    try:
2728 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2729 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2730 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2731 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2732 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2733 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2734 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2735 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2736 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2737 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2738 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2739 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2740 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2741 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2742 f3e513ad Iustin Pop
      result = False
2743 afdc3985 Iustin Pop
  if not result:
2744 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2745 f3e513ad Iustin Pop
2746 f3e513ad Iustin Pop
2747 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2748 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2749 778b75bb Manuel Franceschini

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

2754 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2755 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2756 d61cbe76 Iustin Pop

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

2759 778b75bb Manuel Franceschini
  """
2760 63a3d8f7 Michael Hanselmann
  if not (constants.ENABLE_FILE_STORAGE or
2761 63a3d8f7 Michael Hanselmann
          constants.ENABLE_SHARED_FILE_STORAGE):
2762 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2763 5e09a309 Michael Hanselmann
2764 5e09a309 Michael Hanselmann
  bdev.CheckFileStoragePath(fs_dir)
2765 5e09a309 Michael Hanselmann
2766 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
2767 778b75bb Manuel Franceschini
2768 778b75bb Manuel Franceschini
2769 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2770 778b75bb Manuel Franceschini
  """Create file storage directory.
2771 778b75bb Manuel Franceschini

2772 b1206984 Iustin Pop
  @type file_storage_dir: str
2773 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2774 778b75bb Manuel Franceschini

2775 b1206984 Iustin Pop
  @rtype: tuple
2776 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2777 b1206984 Iustin Pop
      creation was successful or not
2778 778b75bb Manuel Franceschini

2779 778b75bb Manuel Franceschini
  """
2780 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2781 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2782 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2783 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2784 b2b8bcce Iustin Pop
            file_storage_dir)
2785 778b75bb Manuel Franceschini
  else:
2786 b2b8bcce Iustin Pop
    try:
2787 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2788 b2b8bcce Iustin Pop
    except OSError, err:
2789 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2790 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2791 778b75bb Manuel Franceschini
2792 778b75bb Manuel Franceschini
2793 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2794 778b75bb Manuel Franceschini
  """Remove file storage directory.
2795 778b75bb Manuel Franceschini

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

2798 10c2650b Iustin Pop
  @type file_storage_dir: str
2799 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2800 10c2650b Iustin Pop
  @rtype: tuple (success,)
2801 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2802 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2803 778b75bb Manuel Franceschini

2804 778b75bb Manuel Franceschini
  """
2805 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2806 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2807 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2808 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2809 b2b8bcce Iustin Pop
            file_storage_dir)
2810 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2811 b2b8bcce Iustin Pop
    try:
2812 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2813 b2b8bcce Iustin Pop
    except OSError, err:
2814 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2815 b2b8bcce Iustin Pop
            file_storage_dir, err)
2816 b2b8bcce Iustin Pop
2817 778b75bb Manuel Franceschini
2818 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2819 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2820 778b75bb Manuel Franceschini

2821 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2822 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2823 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2824 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2825 10c2650b Iustin Pop
  @rtype: tuple (success,)
2826 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2827 10c2650b Iustin Pop
      whether the operation was successful
2828 778b75bb Manuel Franceschini

2829 778b75bb Manuel Franceschini
  """
2830 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2831 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2832 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2833 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2834 b2b8bcce Iustin Pop
      try:
2835 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2836 b2b8bcce Iustin Pop
      except OSError, err:
2837 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2838 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2839 778b75bb Manuel Franceschini
    else:
2840 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2841 b2b8bcce Iustin Pop
            old_file_storage_dir)
2842 b2b8bcce Iustin Pop
  else:
2843 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2844 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2845 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2846 778b75bb Manuel Franceschini
2847 778b75bb Manuel Franceschini
2848 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2849 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2850 ca52cdeb Michael Hanselmann

2851 10c2650b Iustin Pop
  @type file_name: str
2852 10c2650b Iustin Pop
  @param file_name: the file name we should check
2853 c8457ce7 Iustin Pop
  @rtype: None
2854 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2855 10c2650b Iustin Pop

2856 ca52cdeb Michael Hanselmann
  """
2857 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2858 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2859 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2860 dc31eae3 Michael Hanselmann
2861 dc31eae3 Michael Hanselmann
2862 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2863 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2864 dc31eae3 Michael Hanselmann

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

2868 10c2650b Iustin Pop
  @type file_name: str
2869 10c2650b Iustin Pop
  @param file_name: the job file name
2870 10c2650b Iustin Pop
  @type content: str
2871 10c2650b Iustin Pop
  @param content: the new job contents
2872 10c2650b Iustin Pop
  @rtype: boolean
2873 10c2650b Iustin Pop
  @return: the success of the operation
2874 10c2650b Iustin Pop

2875 dc31eae3 Michael Hanselmann
  """
2876 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2877 cffbbae7 Michael Hanselmann
2878 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2879 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2880 ca52cdeb Michael Hanselmann
2881 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2882 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2883 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2884 ca52cdeb Michael Hanselmann
2885 ca52cdeb Michael Hanselmann
2886 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2887 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2888 af5ebcb1 Michael Hanselmann

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

2891 10c2650b Iustin Pop
  @type old: str
2892 10c2650b Iustin Pop
  @param old: the old (actual) file name
2893 10c2650b Iustin Pop
  @type new: str
2894 10c2650b Iustin Pop
  @param new: the desired file name
2895 c8457ce7 Iustin Pop
  @rtype: tuple
2896 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2897 10c2650b Iustin Pop

2898 af5ebcb1 Michael Hanselmann
  """
2899 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
2900 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
2901 cffbbae7 Michael Hanselmann
2902 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2903 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2904 af5ebcb1 Michael Hanselmann
2905 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
2906 8e5a705d René Nussbaumer
2907 8e5a705d René Nussbaumer
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2908 8e5a705d René Nussbaumer
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2909 af5ebcb1 Michael Hanselmann
2910 af5ebcb1 Michael Hanselmann
2911 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2912 d61cbe76 Iustin Pop
  """Closes the given block devices.
2913 d61cbe76 Iustin Pop

2914 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2915 10c2650b Iustin Pop
  DRBD).
2916 10c2650b Iustin Pop

2917 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2918 b2e7666a Iustin Pop
      of this instance will be removed
2919 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2920 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2921 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2922 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2923 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2924 10c2650b Iustin Pop
      which will contain the error details in case we
2925 10c2650b Iustin Pop
      failed
2926 d61cbe76 Iustin Pop

2927 d61cbe76 Iustin Pop
  """
2928 d61cbe76 Iustin Pop
  bdevs = []
2929 d61cbe76 Iustin Pop
  for cf in disks:
2930 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2931 d61cbe76 Iustin Pop
    if rd is None:
2932 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2933 d61cbe76 Iustin Pop
    bdevs.append(rd)
2934 d61cbe76 Iustin Pop
2935 d61cbe76 Iustin Pop
  msg = []
2936 d61cbe76 Iustin Pop
  for rd in bdevs:
2937 d61cbe76 Iustin Pop
    try:
2938 d61cbe76 Iustin Pop
      rd.Close()
2939 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2940 d61cbe76 Iustin Pop
      msg.append(str(err))
2941 d61cbe76 Iustin Pop
  if msg:
2942 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2943 d61cbe76 Iustin Pop
  else:
2944 b2e7666a Iustin Pop
    if instance_name:
2945 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2946 d61cbe76 Iustin Pop
2947 d61cbe76 Iustin Pop
2948 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2949 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2950 6217e295 Iustin Pop

2951 6217e295 Iustin Pop
  @type hvname: string
2952 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2953 6217e295 Iustin Pop
  @type hvparams: dict
2954 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2955 c26a6bd2 Iustin Pop
  @rtype: None
2956 6217e295 Iustin Pop

2957 6217e295 Iustin Pop
  """
2958 6217e295 Iustin Pop
  try:
2959 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2960 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2961 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2962 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2963 6217e295 Iustin Pop
2964 6217e295 Iustin Pop
2965 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
2966 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
2967 acd9ff9e Iustin Pop

2968 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
2969 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
2970 acd9ff9e Iustin Pop
  @type parameters: list
2971 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
2972 acd9ff9e Iustin Pop

2973 acd9ff9e Iustin Pop
  """
2974 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
2975 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
2976 acd9ff9e Iustin Pop
  if delta:
2977 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
2978 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2979 acd9ff9e Iustin Pop
2980 acd9ff9e Iustin Pop
2981 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
2982 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
2983 acd9ff9e Iustin Pop

2984 acd9ff9e Iustin Pop
  @type required: boolean
2985 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
2986 acd9ff9e Iustin Pop
      failure or not
2987 acd9ff9e Iustin Pop
  @type osname: string
2988 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
2989 acd9ff9e Iustin Pop
  @type checks: list
2990 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
2991 acd9ff9e Iustin Pop
  @type osparams: dict
2992 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
2993 acd9ff9e Iustin Pop
  @rtype: boolean
2994 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
2995 acd9ff9e Iustin Pop
      found and L{required} was false
2996 acd9ff9e Iustin Pop

2997 acd9ff9e Iustin Pop
  """
2998 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2999 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3000 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3001 acd9ff9e Iustin Pop
3002 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3003 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3004 acd9ff9e Iustin Pop
3005 acd9ff9e Iustin Pop
  if not status:
3006 acd9ff9e Iustin Pop
    if required:
3007 acd9ff9e Iustin Pop
      _Fail(tbv)
3008 acd9ff9e Iustin Pop
    else:
3009 acd9ff9e Iustin Pop
      return False
3010 acd9ff9e Iustin Pop
3011 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3012 72db3fd7 Iustin Pop
    return True
3013 72db3fd7 Iustin Pop
3014 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3015 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3016 acd9ff9e Iustin Pop
3017 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3018 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3019 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3020 acd9ff9e Iustin Pop
  if result.failed:
3021 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3022 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3023 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3024 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3025 acd9ff9e Iustin Pop
3026 acd9ff9e Iustin Pop
  return True
3027 acd9ff9e Iustin Pop
3028 acd9ff9e Iustin Pop
3029 56aa9fd5 Iustin Pop
def DemoteFromMC():
3030 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3031 56aa9fd5 Iustin Pop

3032 56aa9fd5 Iustin Pop
  """
3033 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3034 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3035 56aa9fd5 Iustin Pop
  if master == myself:
3036 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3037 f154a7a3 Michael Hanselmann
3038 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3039 f154a7a3 Michael Hanselmann
  if not result.failed:
3040 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3041 f154a7a3 Michael Hanselmann
3042 56aa9fd5 Iustin Pop
  try:
3043 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3044 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3045 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3046 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3047 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3048 f154a7a3 Michael Hanselmann
3049 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3050 56aa9fd5 Iustin Pop
3051 56aa9fd5 Iustin Pop
3052 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3053 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3054 f942a838 Michael Hanselmann

3055 f942a838 Michael Hanselmann
  """
3056 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3057 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3058 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3059 f942a838 Michael Hanselmann
3060 f942a838 Michael Hanselmann
3061 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3062 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3063 f942a838 Michael Hanselmann

3064 f942a838 Michael Hanselmann
  @type validity: int
3065 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3066 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3067 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3068 f942a838 Michael Hanselmann

3069 f942a838 Michael Hanselmann
  """
3070 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3071 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3072 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3073 f942a838 Michael Hanselmann
3074 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3075 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3076 f942a838 Michael Hanselmann
  try:
3077 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3078 f942a838 Michael Hanselmann
    assert len(name) > 5
3079 f942a838 Michael Hanselmann
3080 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3081 f942a838 Michael Hanselmann
3082 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3083 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3084 f942a838 Michael Hanselmann
3085 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3086 f942a838 Michael Hanselmann
    return (name, cert_pem)
3087 f942a838 Michael Hanselmann
  except Exception:
3088 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3089 f942a838 Michael Hanselmann
    raise
3090 f942a838 Michael Hanselmann
3091 f942a838 Michael Hanselmann
3092 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3093 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3094 f942a838 Michael Hanselmann

3095 f942a838 Michael Hanselmann
  @type name: string
3096 f942a838 Michael Hanselmann
  @param name: Certificate name
3097 f942a838 Michael Hanselmann

3098 f942a838 Michael Hanselmann
  """
3099 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3100 f942a838 Michael Hanselmann
3101 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3102 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3103 f942a838 Michael Hanselmann
3104 f942a838 Michael Hanselmann
  try:
3105 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3106 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3107 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3108 f942a838 Michael Hanselmann
          cert_dir, err)
3109 f942a838 Michael Hanselmann
3110 f942a838 Michael Hanselmann
3111 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3112 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3113 1651d116 Michael Hanselmann

3114 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3115 1651d116 Michael Hanselmann
  @param instance: The instance object
3116 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3117 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3118 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3119 1651d116 Michael Hanselmann

3120 1651d116 Michael Hanselmann
  """
3121 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3122 1651d116 Michael Hanselmann
3123 1651d116 Michael Hanselmann
  env = None
3124 1651d116 Michael Hanselmann
  prefix = None
3125 1651d116 Michael Hanselmann
  suffix = None
3126 2ad5550d Michael Hanselmann
  exp_size = None
3127 1651d116 Michael Hanselmann
3128 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
3129 1651d116 Michael Hanselmann
    (filename, ) = ieargs
3130 1651d116 Michael Hanselmann
3131 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
3132 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
3133 1651d116 Michael Hanselmann
3134 748c9884 René Nussbaumer
    real_filename = os.path.realpath(filename)
3135 748c9884 René Nussbaumer
    directory = os.path.dirname(real_filename)
3136 1651d116 Michael Hanselmann
3137 710f30ec Michael Hanselmann
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3138 748c9884 René Nussbaumer
      _Fail("File '%s' is not under exports directory '%s': %s",
3139 710f30ec Michael Hanselmann
            filename, pathutils.EXPORT_DIR, real_filename)
3140 1651d116 Michael Hanselmann
3141 1651d116 Michael Hanselmann
    # Create directory
3142 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
3143 1651d116 Michael Hanselmann
3144 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
3145 1651d116 Michael Hanselmann
3146 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3147 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
3148 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3149 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
3150 1651d116 Michael Hanselmann
3151 2ad5550d Michael Hanselmann
      # Retrieve file size
3152 2ad5550d Michael Hanselmann
      try:
3153 2ad5550d Michael Hanselmann
        st = os.stat(filename)
3154 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
3155 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
3156 2ad5550d Michael Hanselmann
      else:
3157 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
3158 2ad5550d Michael Hanselmann
3159 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
3160 1651d116 Michael Hanselmann
    (disk, ) = ieargs
3161 1651d116 Michael Hanselmann
3162 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3163 1651d116 Michael Hanselmann
3164 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3165 1651d116 Michael Hanselmann
      # we set here a smaller block size as, due to transport buffering, more
3166 1651d116 Michael Hanselmann
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3167 1651d116 Michael Hanselmann
      # is not already there or we pass a wrong path; we use notrunc to no
3168 1651d116 Michael Hanselmann
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3169 1651d116 Michael Hanselmann
      # much memory; this means that at best, we flush every 64k, which will
3170 1651d116 Michael Hanselmann
      # not be very fast
3171 1651d116 Michael Hanselmann
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3172 1651d116 Michael Hanselmann
                                    " bs=%s oflag=dsync"),
3173 1651d116 Michael Hanselmann
                                    real_disk.dev_path,
3174 1651d116 Michael Hanselmann
                                    str(64 * 1024))
3175 1651d116 Michael Hanselmann
3176 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3177 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
3178 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3179 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
3180 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
3181 1651d116 Michael Hanselmann
                                   str(disk.size))
3182 2ad5550d Michael Hanselmann
      exp_size = disk.size
3183 1651d116 Michael Hanselmann
3184 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
3185 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
3186 1651d116 Michael Hanselmann
3187 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
3188 1651d116 Michael Hanselmann
3189 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3190 1651d116 Michael Hanselmann
3191 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
3192 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
3193 1651d116 Michael Hanselmann
3194 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3195 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3196 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
3197 1651d116 Michael Hanselmann
      script = inst_os.import_script
3198 1651d116 Michael Hanselmann
3199 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3200 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
3201 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
3202 1651d116 Michael Hanselmann
      script = inst_os.export_script
3203 1651d116 Michael Hanselmann
3204 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
3205 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3206 1651d116 Michael Hanselmann
3207 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3208 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
3209 1651d116 Michael Hanselmann
3210 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3211 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
3212 1651d116 Michael Hanselmann
3213 2ad5550d Michael Hanselmann
    # Let script predict size
3214 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
3215 2ad5550d Michael Hanselmann
3216 1651d116 Michael Hanselmann
  else:
3217 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3218 1651d116 Michael Hanselmann
3219 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
3220 1651d116 Michael Hanselmann
3221 1651d116 Michael Hanselmann
3222 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
3223 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
3224 1651d116 Michael Hanselmann

3225 1651d116 Michael Hanselmann
  """
3226 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3227 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3228 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3229 1651d116 Michael Hanselmann
3230 1651d116 Michael Hanselmann
3231 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3232 6613661a Iustin Pop
                            ieio, ieioargs):
3233 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3234 1651d116 Michael Hanselmann

3235 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3236 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3237 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3238 1651d116 Michael Hanselmann
  @type host: string
3239 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3240 1651d116 Michael Hanselmann
  @type port: int
3241 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3242 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3243 1651d116 Michael Hanselmann
  @param instance: Instance object
3244 6613661a Iustin Pop
  @type component: string
3245 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3246 6613661a Iustin Pop
      e.g. 'disk/0'
3247 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3248 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3249 1651d116 Michael Hanselmann

3250 1651d116 Michael Hanselmann
  """
3251 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
3252 1651d116 Michael Hanselmann
    prefix = "import"
3253 1651d116 Michael Hanselmann
3254 1651d116 Michael Hanselmann
    if not (host is None and port is None):
3255 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
3256 1651d116 Michael Hanselmann
3257 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
3258 1651d116 Michael Hanselmann
    prefix = "export"
3259 1651d116 Michael Hanselmann
3260 1651d116 Michael Hanselmann
    if host is None or port is None:
3261 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
3262 1651d116 Michael Hanselmann
3263 1651d116 Michael Hanselmann
  else:
3264 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
3265 1651d116 Michael Hanselmann
3266 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
3267 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
3268 1651d116 Michael Hanselmann
3269 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3270 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3271 1651d116 Michael Hanselmann
3272 eb630f50 Michael Hanselmann
  if opts.key_name is None:
3273 1651d116 Michael Hanselmann
    # Use server.pem
3274 710f30ec Michael Hanselmann
    key_path = pathutils.NODED_CERT_FILE
3275 710f30ec Michael Hanselmann
    cert_path = pathutils.NODED_CERT_FILE
3276 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
3277 1651d116 Michael Hanselmann
  else:
3278 710f30ec Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3279 eb630f50 Michael Hanselmann
                                                 opts.key_name)
3280 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
3281 1651d116 Michael Hanselmann
3282 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
3283 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
3284 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
3285 63bcea2a Michael Hanselmann
3286 6613661a Iustin Pop
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3287 1651d116 Michael Hanselmann
  try:
3288 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3289 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3290 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3291 1651d116 Michael Hanselmann
3292 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
3293 1651d116 Michael Hanselmann
      # Use server.pem
3294 710f30ec Michael Hanselmann
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3295 eb630f50 Michael Hanselmann
    else:
3296 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
3297 63bcea2a Michael Hanselmann
3298 eb630f50 Michael Hanselmann
    # Write CA file
3299 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
3300 1651d116 Michael Hanselmann
3301 1651d116 Michael Hanselmann
    cmd = [
3302 710f30ec Michael Hanselmann
      pathutils.IMPORT_EXPORT_DAEMON,
3303 1651d116 Michael Hanselmann
      status_file, mode,
3304 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
3305 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
3306 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
3307 1651d116 Michael Hanselmann
      ]
3308 1651d116 Michael Hanselmann
3309 1651d116 Michael Hanselmann
    if host:
3310 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
3311 1651d116 Michael Hanselmann
3312 1651d116 Michael Hanselmann
    if port:
3313 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
3314 1651d116 Michael Hanselmann
3315 855d2fc7 Michael Hanselmann
    if opts.ipv6:
3316 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
3317 855d2fc7 Michael Hanselmann
    else:
3318 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
3319 855d2fc7 Michael Hanselmann
3320 a5310c2a Michael Hanselmann
    if opts.compress:
3321 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
3322 a5310c2a Michael Hanselmann
3323 af1d39b1 Michael Hanselmann
    if opts.magic:
3324 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
3325 af1d39b1 Michael Hanselmann
3326 2ad5550d Michael Hanselmann
    if exp_size is not None:
3327 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
3328 2ad5550d Michael Hanselmann
3329 1651d116 Michael Hanselmann
    if cmd_prefix:
3330 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3331 1651d116 Michael Hanselmann
3332 1651d116 Michael Hanselmann
    if cmd_suffix:
3333 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3334 1651d116 Michael Hanselmann
3335 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
3336 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
3337 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3338 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3339 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
3340 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
3341 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
3342 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3343 4478301b Michael Hanselmann
3344 6aa7a354 Iustin Pop
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3345 1651d116 Michael Hanselmann
3346 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3347 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
3348 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3349 1651d116 Michael Hanselmann
                      output=logfile)
3350 1651d116 Michael Hanselmann
3351 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
3352 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
3353 1651d116 Michael Hanselmann
3354 1651d116 Michael Hanselmann
  except Exception:
3355 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
3356 1651d116 Michael Hanselmann
    raise
3357 1651d116 Michael Hanselmann
3358 1651d116 Michael Hanselmann
3359 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
3360 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
3361 1651d116 Michael Hanselmann

3362 1651d116 Michael Hanselmann
  @type names: sequence
3363 1651d116 Michael Hanselmann
  @param names: List of names
3364 1651d116 Michael Hanselmann
  @rtype: List of dicts
3365 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3366 1651d116 Michael Hanselmann
           status couldn't be read
3367 1651d116 Michael Hanselmann

3368 1651d116 Michael Hanselmann
  """
3369 1651d116 Michael Hanselmann
  result = []
3370 1651d116 Michael Hanselmann
3371 1651d116 Michael Hanselmann
  for name in names:
3372 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3373 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3374 1651d116 Michael Hanselmann
3375 1651d116 Michael Hanselmann
    try:
3376 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3377 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3378 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3379 1651d116 Michael Hanselmann
        raise
3380 1651d116 Michael Hanselmann
      data = None
3381 1651d116 Michael Hanselmann
3382 1651d116 Michael Hanselmann
    if not data:
3383 1651d116 Michael Hanselmann
      result.append(None)
3384 1651d116 Michael Hanselmann
      continue
3385 1651d116 Michael Hanselmann
3386 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3387 1651d116 Michael Hanselmann
3388 1651d116 Michael Hanselmann
  return result
3389 1651d116 Michael Hanselmann
3390 1651d116 Michael Hanselmann
3391 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3392 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3393 f81c4737 Michael Hanselmann

3394 f81c4737 Michael Hanselmann
  """
3395 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3396 f81c4737 Michael Hanselmann
3397 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3398 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3399 f81c4737 Michael Hanselmann
3400 f81c4737 Michael Hanselmann
  if pid:
3401 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3402 f81c4737 Michael Hanselmann
                 name, pid)
3403 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3404 f81c4737 Michael Hanselmann
3405 f81c4737 Michael Hanselmann
3406 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3407 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3408 1651d116 Michael Hanselmann

3409 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3410 1651d116 Michael Hanselmann
  whole status directory is removed.
3411 1651d116 Michael Hanselmann

3412 1651d116 Michael Hanselmann
  """
3413 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3414 1651d116 Michael Hanselmann
3415 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3416 1651d116 Michael Hanselmann
3417 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3418 1651d116 Michael Hanselmann
3419 1651d116 Michael Hanselmann
  if pid:
3420 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3421 1651d116 Michael Hanselmann
                 name, pid)
3422 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3423 1651d116 Michael Hanselmann
3424 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3425 1651d116 Michael Hanselmann
3426 1651d116 Michael Hanselmann
3427 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3428 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3429 6b93ec9d Iustin Pop

3430 6b93ec9d Iustin Pop
  """
3431 6b93ec9d Iustin Pop
  # set the correct physical ID
3432 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3433 6b93ec9d Iustin Pop
  for cf in disks:
3434 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3435 6b93ec9d Iustin Pop
3436 6b93ec9d Iustin Pop
  bdevs = []
3437 6b93ec9d Iustin Pop
3438 6b93ec9d Iustin Pop
  for cf in disks:
3439 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3440 6b93ec9d Iustin Pop
    if rd is None:
3441 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3442 6b93ec9d Iustin Pop
    bdevs.append(rd)
3443 5a533f8a Iustin Pop
  return bdevs
3444 6b93ec9d Iustin Pop
3445 6b93ec9d Iustin Pop
3446 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3447 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3448 6b93ec9d Iustin Pop

3449 6b93ec9d Iustin Pop
  """
3450 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3451 6b93ec9d Iustin Pop
3452 6b93ec9d Iustin Pop
  # disconnect disks
3453 6b93ec9d Iustin Pop
  for rd in bdevs:
3454 6b93ec9d Iustin Pop
    try:
3455 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3456 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3457 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3458 2cc6781a Iustin Pop
            err, exc=True)
3459 6b93ec9d Iustin Pop
3460 6b93ec9d Iustin Pop
3461 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3462 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3463 6b93ec9d Iustin Pop

3464 6b93ec9d Iustin Pop
  """
3465 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3466 6b93ec9d Iustin Pop
3467 6b93ec9d Iustin Pop
  if multimaster:
3468 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3469 6b93ec9d Iustin Pop
      try:
3470 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3471 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3472 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3473 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3474 6b93ec9d Iustin Pop
  # needed primary mode
3475 6b93ec9d Iustin Pop
  for rd in bdevs:
3476 6b93ec9d Iustin Pop
    try:
3477 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3478 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3479 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3480 3c0cdc83 Michael Hanselmann
3481 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3482 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3483 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3484 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3485 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3486 3c0cdc83 Michael Hanselmann
3487 3c0cdc83 Michael Hanselmann
  def _Attach():
3488 6b93ec9d Iustin Pop
    all_connected = True
3489 3c0cdc83 Michael Hanselmann
3490 6b93ec9d Iustin Pop
    for rd in bdevs:
3491 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3492 3c0cdc83 Michael Hanselmann
3493 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3494 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3495 3c0cdc83 Michael Hanselmann
3496 6b93ec9d Iustin Pop
      if stats.is_standalone:
3497 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3498 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3499 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3500 6b93ec9d Iustin Pop
        try:
3501 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3502 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3503 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3504 3c0cdc83 Michael Hanselmann
3505 3c0cdc83 Michael Hanselmann
    if not all_connected:
3506 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3507 3c0cdc83 Michael Hanselmann
3508 3c0cdc83 Michael Hanselmann
  try:
3509 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3510 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3511 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3512 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3513 3c0cdc83 Michael Hanselmann
3514 6b93ec9d Iustin Pop
  if multimaster:
3515 6b93ec9d Iustin Pop
    # change to primary mode
3516 6b93ec9d Iustin Pop
    for rd in bdevs:
3517 d3da87b8 Iustin Pop
      try:
3518 d3da87b8 Iustin Pop
        rd.Open()
3519 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3520 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3521 6b93ec9d Iustin Pop
3522 6b93ec9d Iustin Pop
3523 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3524 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3525 6b93ec9d Iustin Pop

3526 6b93ec9d Iustin Pop
  """
3527 db8667b7 Iustin Pop
  def _helper(rd):
3528 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3529 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3530 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3531 db8667b7 Iustin Pop
    return stats
3532 db8667b7 Iustin Pop
3533 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3534 6b93ec9d Iustin Pop
3535 6b93ec9d Iustin Pop
  min_resync = 100
3536 6b93ec9d Iustin Pop
  alldone = True
3537 6b93ec9d Iustin Pop
  for rd in bdevs:
3538 db8667b7 Iustin Pop
    try:
3539 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3540 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3541 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3542 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3543 db8667b7 Iustin Pop
      # last check
3544 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3545 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3546 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3547 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3548 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3549 afdc3985 Iustin Pop
3550 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3551 6b93ec9d Iustin Pop
3552 6b93ec9d Iustin Pop
3553 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3554 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3555 c46b9782 Luca Bigliardi

3556 c46b9782 Luca Bigliardi
  """
3557 c46b9782 Luca Bigliardi
  try:
3558 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3559 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3560 c46b9782 Luca Bigliardi
    _Fail(str(err))
3561 c46b9782 Luca Bigliardi
3562 c46b9782 Luca Bigliardi
3563 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3564 f5118ade Iustin Pop
  """Hard-powercycle the node.
3565 f5118ade Iustin Pop

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

3569 f5118ade Iustin Pop
  """
3570 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3571 f5118ade Iustin Pop
  try:
3572 f5118ade Iustin Pop
    pid = os.fork()
3573 29921401 Iustin Pop
  except OSError:
3574 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3575 f5118ade Iustin Pop
    pid = 0
3576 f5118ade Iustin Pop
  if pid > 0:
3577 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3578 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3579 1af6ac0f Luca Bigliardi
  try:
3580 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3581 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3582 1af6ac0f Luca Bigliardi
    pass
3583 f5118ade Iustin Pop
  time.sleep(5)
3584 f5118ade Iustin Pop
  hyper.PowercycleNode()
3585 f5118ade Iustin Pop
3586 f5118ade Iustin Pop
3587 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
3588 1a2eb2dc Michael Hanselmann
  """Verifies a remote command name.
3589 1a2eb2dc Michael Hanselmann

3590 1a2eb2dc Michael Hanselmann
  @type cmd: string
3591 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3592 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3593 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3594 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3595 1a2eb2dc Michael Hanselmann

3596 1a2eb2dc Michael Hanselmann
  """
3597 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
3598 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
3599 1a2eb2dc Michael Hanselmann
3600 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
3601 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
3602 1a2eb2dc Michael Hanselmann
3603 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3604 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
3605 1a2eb2dc Michael Hanselmann
3606 1a2eb2dc Michael Hanselmann
  return (True, None)
3607 1a2eb2dc Michael Hanselmann
3608 1a2eb2dc Michael Hanselmann
3609 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
3610 1a2eb2dc Michael Hanselmann
  """Common checks for remote command file system directories and files.
3611 1a2eb2dc Michael Hanselmann

3612 1a2eb2dc Michael Hanselmann
  @type path: string
3613 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3614 1a2eb2dc Michael Hanselmann
  @param owner: C{None} or tuple containing UID and GID
3615 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or C{os.stat} result)
3616 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3617 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's the result of C{os.stat}
3618 1a2eb2dc Michael Hanselmann

3619 1a2eb2dc Michael Hanselmann
  """
3620 1a2eb2dc Michael Hanselmann
  if owner is None:
3621 1a2eb2dc Michael Hanselmann
    # Default to root as owner
3622 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
3623 1a2eb2dc Michael Hanselmann
3624 1a2eb2dc Michael Hanselmann
  try:
3625 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
3626 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
3627 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3628 1a2eb2dc Michael Hanselmann
3629 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3630 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
3631 1a2eb2dc Michael Hanselmann
3632 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
3633 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
3634 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3635 1a2eb2dc Michael Hanselmann
3636 1a2eb2dc Michael Hanselmann
  return (True, st)
3637 1a2eb2dc Michael Hanselmann
3638 1a2eb2dc Michael Hanselmann
3639 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3640 1a2eb2dc Michael Hanselmann
  """Verifies remote command directory.
3641 1a2eb2dc Michael Hanselmann

3642 1a2eb2dc Michael Hanselmann
  @type path: string
3643 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3644 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3645 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3646 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3647 1a2eb2dc Michael Hanselmann

3648 1a2eb2dc Michael Hanselmann
  """
3649 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3650 1a2eb2dc Michael Hanselmann
3651 1a2eb2dc Michael Hanselmann
  if not status:
3652 1a2eb2dc Michael Hanselmann
    return (False, value)
3653 1a2eb2dc Michael Hanselmann
3654 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
3655 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
3656 1a2eb2dc Michael Hanselmann
3657 1a2eb2dc Michael Hanselmann
  return (True, None)
3658 1a2eb2dc Michael Hanselmann
3659 1a2eb2dc Michael Hanselmann
3660 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3661 1a2eb2dc Michael Hanselmann
  """Verifies a whole remote command and returns its executable filename.
3662 1a2eb2dc Michael Hanselmann

3663 1a2eb2dc Michael Hanselmann
  @type path: string
3664 1a2eb2dc Michael Hanselmann
  @param path: Directory containing remote commands
3665 1a2eb2dc Michael Hanselmann
  @type cmd: string
3666 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3667 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
3668 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3669 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
3670 1a2eb2dc Michael Hanselmann
    absolute path to the executable
3671 1a2eb2dc Michael Hanselmann

3672 1a2eb2dc Michael Hanselmann
  """
3673 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
3674 1a2eb2dc Michael Hanselmann
3675 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3676 1a2eb2dc Michael Hanselmann
3677 1a2eb2dc Michael Hanselmann
  if not status:
3678 1a2eb2dc Michael Hanselmann
    return (False, msg)
3679 1a2eb2dc Michael Hanselmann
3680 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
3681 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3682 1a2eb2dc Michael Hanselmann
3683 1a2eb2dc Michael Hanselmann
  return (True, executable)
3684 1a2eb2dc Michael Hanselmann
3685 1a2eb2dc Michael Hanselmann
3686 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
3687 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3688 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
3689 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
3690 1a2eb2dc Michael Hanselmann
  """Performs a number of tests on a remote command.
3691 1a2eb2dc Michael Hanselmann

3692 1a2eb2dc Michael Hanselmann
  @type path: string
3693 1a2eb2dc Michael Hanselmann
  @param path: Directory containing remote commands
3694 1a2eb2dc Michael Hanselmann
  @type cmd: string
3695 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3696 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
3697 1a2eb2dc Michael Hanselmann

3698 1a2eb2dc Michael Hanselmann
  """
3699 1a2eb2dc Michael Hanselmann
  # Verify the directory first
3700 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
3701 1a2eb2dc Michael Hanselmann
  if status:
3702 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
3703 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
3704 1a2eb2dc Michael Hanselmann
3705 1a2eb2dc Michael Hanselmann
  if not status:
3706 1a2eb2dc Michael Hanselmann
    return (False, msg)
3707 1a2eb2dc Michael Hanselmann
3708 1a2eb2dc Michael Hanselmann
  # Check actual executable
3709 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
3710 1a2eb2dc Michael Hanselmann
3711 1a2eb2dc Michael Hanselmann
3712 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
3713 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3714 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3715 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3716 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
3717 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
3718 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
3719 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3720 1a2eb2dc Michael Hanselmann
  """Executes a remote command after performing strict tests.
3721 1a2eb2dc Michael Hanselmann

3722 1a2eb2dc Michael Hanselmann
  @type cmd: string
3723 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3724 1a2eb2dc Michael Hanselmann
  @rtype: string
3725 1a2eb2dc Michael Hanselmann
  @return: Command output
3726 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
3727 1a2eb2dc Michael Hanselmann

3728 1a2eb2dc Michael Hanselmann
  """
3729 1a2eb2dc Michael Hanselmann
  logging.info("Preparing to run remote command '%s'", cmd)
3730 1a2eb2dc Michael Hanselmann
3731 1a2eb2dc Michael Hanselmann
  if not _enabled:
3732 1a2eb2dc Michael Hanselmann
    _Fail("Remote commands disabled at configure time")
3733 1a2eb2dc Michael Hanselmann
3734 1a2eb2dc Michael Hanselmann
  lock = None
3735 1a2eb2dc Michael Hanselmann
  try:
3736 1a2eb2dc Michael Hanselmann
    cmdresult = None
3737 1a2eb2dc Michael Hanselmann
    try:
3738 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
3739 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3740 1a2eb2dc Michael Hanselmann
3741 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
3742 1a2eb2dc Michael Hanselmann
3743 1a2eb2dc Michael Hanselmann
      if status:
3744 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3745 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
3746 1a2eb2dc Michael Hanselmann
      else:
3747 1a2eb2dc Michael Hanselmann
        logging.error(value)
3748 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
3749 1a2eb2dc Michael Hanselmann
      # Keep original error in log
3750 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
3751 1a2eb2dc Michael Hanselmann
3752 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
3753 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
3754 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
3755 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
3756 1a2eb2dc Michael Hanselmann
3757 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
3758 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
3759 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
3760 1a2eb2dc Michael Hanselmann
      _Fail("Remote command '%s' failed: %s; output: %s",
3761 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
3762 1a2eb2dc Michael Hanselmann
    else:
3763 1a2eb2dc Michael Hanselmann
      return cmdresult.output
3764 1a2eb2dc Michael Hanselmann
  finally:
3765 1a2eb2dc Michael Hanselmann
    if lock is not None:
3766 1a2eb2dc Michael Hanselmann
      # Release lock at last
3767 1a2eb2dc Michael Hanselmann
      lock.Close()
3768 1a2eb2dc Michael Hanselmann
      lock = None
3769 1a2eb2dc Michael Hanselmann
3770 1a2eb2dc Michael Hanselmann
3771 a8083063 Iustin Pop
class HooksRunner(object):
3772 a8083063 Iustin Pop
  """Hook runner.
3773 a8083063 Iustin Pop

3774 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3775 10c2650b Iustin Pop
  on the master side.
3776 a8083063 Iustin Pop

3777 a8083063 Iustin Pop
  """
3778 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3779 a8083063 Iustin Pop
    """Constructor for hooks runner.
3780 a8083063 Iustin Pop

3781 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
3782 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
3783 3329f4de Michael Hanselmann
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
3784 a8083063 Iustin Pop

3785 a8083063 Iustin Pop
    """
3786 a8083063 Iustin Pop
    if hooks_base_dir is None:
3787 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3788 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3789 fe267188 Iustin Pop
    # constant
3790 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3791 a8083063 Iustin Pop
3792 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3793 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3794 0fa481f5 Andrea Spadaccini

3795 0fa481f5 Andrea Spadaccini
    """
3796 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3797 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3798 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3799 0fa481f5 Andrea Spadaccini
    assert node == myself
3800 0fa481f5 Andrea Spadaccini
3801 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3802 0fa481f5 Andrea Spadaccini
3803 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3804 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3805 0fa481f5 Andrea Spadaccini
3806 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3807 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3808 a8083063 Iustin Pop

3809 10c2650b Iustin Pop
    @type hpath: str
3810 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3811 10c2650b Iustin Pop
        holds the scripts
3812 10c2650b Iustin Pop
    @type phase: str
3813 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3814 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3815 10c2650b Iustin Pop
    @type env: dict
3816 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3817 10c2650b Iustin Pop
    @rtype: list
3818 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3819 10c2650b Iustin Pop
      - script path
3820 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3821 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3822 10c2650b Iustin Pop
      - output of the script
3823 10c2650b Iustin Pop

3824 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3825 10c2650b Iustin Pop
        parameters
3826 a8083063 Iustin Pop

3827 a8083063 Iustin Pop
    """
3828 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3829 a8083063 Iustin Pop
      suffix = "pre"
3830 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3831 a8083063 Iustin Pop
      suffix = "post"
3832 a8083063 Iustin Pop
    else:
3833 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3834 3fb4f740 Iustin Pop
3835 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3836 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3837 6bb65e3a Guido Trotter
3838 6bb65e3a Guido Trotter
    results = []
3839 a9b7e346 Iustin Pop
3840 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3841 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3842 a9b7e346 Iustin Pop
      # warning at every operation
3843 a9b7e346 Iustin Pop
      return results
3844 a9b7e346 Iustin Pop
3845 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3846 a9b7e346 Iustin Pop
3847 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
3848 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3849 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3850 a8083063 Iustin Pop
        output = ""
3851 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3852 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3853 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3854 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3855 6bb65e3a Guido Trotter
        if runresult.failed:
3856 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3857 a8083063 Iustin Pop
        else:
3858 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3859 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3860 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3861 6bb65e3a Guido Trotter
3862 6bb65e3a Guido Trotter
    return results
3863 3f78eef2 Iustin Pop
3864 3f78eef2 Iustin Pop
3865 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3866 8d528b7c Iustin Pop
  """IAllocator runner.
3867 8d528b7c Iustin Pop

3868 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3869 8d528b7c Iustin Pop
  the master side.
3870 8d528b7c Iustin Pop

3871 8d528b7c Iustin Pop
  """
3872 7e950d31 Iustin Pop
  @staticmethod
3873 7e950d31 Iustin Pop
  def Run(name, idata):
3874 8d528b7c Iustin Pop
    """Run an iallocator script.
3875 8d528b7c Iustin Pop

3876 10c2650b Iustin Pop
    @type name: str
3877 10c2650b Iustin Pop
    @param name: the iallocator script name
3878 10c2650b Iustin Pop
    @type idata: str
3879 10c2650b Iustin Pop
    @param idata: the allocator input data
3880 10c2650b Iustin Pop

3881 10c2650b Iustin Pop
    @rtype: tuple
3882 87f5c298 Iustin Pop
    @return: two element tuple of:
3883 87f5c298 Iustin Pop
       - status
3884 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3885 8d528b7c Iustin Pop

3886 8d528b7c Iustin Pop
    """
3887 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3888 8d528b7c Iustin Pop
                                  os.path.isfile)
3889 8d528b7c Iustin Pop
    if alloc_script is None:
3890 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3891 8d528b7c Iustin Pop
3892 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3893 8d528b7c Iustin Pop
    try:
3894 8d528b7c Iustin Pop
      os.write(fd, idata)
3895 8d528b7c Iustin Pop
      os.close(fd)
3896 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3897 8d528b7c Iustin Pop
      if result.failed:
3898 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3899 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3900 8d528b7c Iustin Pop
    finally:
3901 8d528b7c Iustin Pop
      os.unlink(fin_name)
3902 8d528b7c Iustin Pop
3903 c26a6bd2 Iustin Pop
    return result.stdout
3904 8d528b7c Iustin Pop
3905 8d528b7c Iustin Pop
3906 3f78eef2 Iustin Pop
class DevCacheManager(object):
3907 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3908 3f78eef2 Iustin Pop

3909 3f78eef2 Iustin Pop
  """
3910 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3911 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
3912 3f78eef2 Iustin Pop
3913 3f78eef2 Iustin Pop
  @classmethod
3914 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3915 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3916 3f78eef2 Iustin Pop

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

3920 10c2650b Iustin Pop
    @type dev_path: str
3921 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3922 10c2650b Iustin Pop
    @rtype: str
3923 10c2650b Iustin Pop
    @return: the converted path name
3924 3f78eef2 Iustin Pop

3925 3f78eef2 Iustin Pop
    """
3926 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3927 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3928 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3929 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3930 3f78eef2 Iustin Pop
    return fpath
3931 3f78eef2 Iustin Pop
3932 3f78eef2 Iustin Pop
  @classmethod
3933 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3934 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3935 3f78eef2 Iustin Pop

3936 10c2650b Iustin Pop
    @type dev_path: str
3937 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3938 10c2650b Iustin Pop
    @type owner: str
3939 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3940 10c2650b Iustin Pop
    @type on_primary: bool
3941 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3942 10c2650b Iustin Pop
        node nor not
3943 10c2650b Iustin Pop
    @type iv_name: str
3944 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3945 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3946 10c2650b Iustin Pop

3947 10c2650b Iustin Pop
    @rtype: None
3948 10c2650b Iustin Pop

3949 3f78eef2 Iustin Pop
    """
3950 cf5a8306 Iustin Pop
    if dev_path is None:
3951 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3952 cf5a8306 Iustin Pop
      return
3953 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3954 3f78eef2 Iustin Pop
    if on_primary:
3955 3f78eef2 Iustin Pop
      state = "primary"
3956 3f78eef2 Iustin Pop
    else:
3957 3f78eef2 Iustin Pop
      state = "secondary"
3958 3f78eef2 Iustin Pop
    if iv_name is None:
3959 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3960 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3961 3f78eef2 Iustin Pop
    try:
3962 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3963 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3964 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3965 3f78eef2 Iustin Pop
3966 3f78eef2 Iustin Pop
  @classmethod
3967 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3968 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3969 3f78eef2 Iustin Pop

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

3973 10c2650b Iustin Pop
    @type dev_path: str
3974 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3975 10c2650b Iustin Pop

3976 10c2650b Iustin Pop
    @rtype: None
3977 10c2650b Iustin Pop

3978 3f78eef2 Iustin Pop
    """
3979 cf5a8306 Iustin Pop
    if dev_path is None:
3980 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3981 cf5a8306 Iustin Pop
      return
3982 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3983 3f78eef2 Iustin Pop
    try:
3984 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3985 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3986 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)