Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 19e1b715

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

595 78519c10 Michael Hanselmann
  @type vg_names: list of string
596 78519c10 Michael Hanselmann
  @param vg_names: Names of the volume groups to ask for disk space information
597 78519c10 Michael Hanselmann
  @type hv_names: list of string
598 78519c10 Michael Hanselmann
  @param hv_names: Names of the hypervisors to ask for node information
599 1a3c5d4e Bernardo Dal Seno
  @type excl_stor: boolean
600 1a3c5d4e Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
601 78519c10 Michael Hanselmann
  @rtype: tuple; (string, None/dict, None/dict)
602 78519c10 Michael Hanselmann
  @return: Tuple containing boot ID, volume group information and hypervisor
603 78519c10 Michael Hanselmann
    information
604 a8083063 Iustin Pop

605 098c0958 Michael Hanselmann
  """
606 78519c10 Michael Hanselmann
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
607 1a3c5d4e Bernardo Dal Seno
  vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
608 78519c10 Michael Hanselmann
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
609 78519c10 Michael Hanselmann
610 78519c10 Michael Hanselmann
  return (bootid, vg_info, hv_info)
611 a8083063 Iustin Pop
612 a8083063 Iustin Pop
613 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
614 a8083063 Iustin Pop
  """Verify the status of the local node.
615 a8083063 Iustin Pop

616 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
617 e69d05fd Iustin Pop
  local node.
618 e69d05fd Iustin Pop

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

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

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

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

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

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

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

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

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

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

878 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
879 10c2650b Iustin Pop
      details.
880 a8083063 Iustin Pop

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

914 10c2650b Iustin Pop
  @rtype: dict
915 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
916 10c2650b Iustin Pop
      size of the volume
917 a8083063 Iustin Pop

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

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

933 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
934 10c2650b Iustin Pop
    error.
935 10c2650b Iustin Pop

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

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

971 b1206984 Iustin Pop
  @rtype: boolean
972 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
973 a8083063 Iustin Pop

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

987 e69d05fd Iustin Pop
  @type hypervisor_list: list
988 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
989 e69d05fd Iustin Pop

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

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

1011 e69d05fd Iustin Pop
  @type instance: string
1012 e69d05fd Iustin Pop
  @param instance: the instance name
1013 e69d05fd Iustin Pop
  @type hname: string
1014 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1015 a8083063 Iustin Pop

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

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

1039 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1040 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1041 56e7640c Iustin Pop

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

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

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

1067 e69d05fd Iustin Pop
  @type hypervisor_list: list
1068 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1069 e69d05fd Iustin Pop

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

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

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

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

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

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

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

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

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

1204 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1205 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1206 9332fd8a Iustin Pop

1207 9332fd8a Iustin Pop

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

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

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

1245 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1246 a8083063 Iustin Pop
  devices must be already assembled.
1247 a8083063 Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

1434 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1435 6906a9d8 Guido Trotter
  @param instance: the instance definition
1436 6906a9d8 Guido Trotter

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1622 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1623 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1624 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1625 69dd363f René Nussbaumer

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

1645 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1646 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1647 da63bb4e René Nussbaumer
  @type offset: int
1648 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1649 da63bb4e René Nussbaumer
  @type size: int
1650 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1651 69dd363f René Nussbaumer

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

1677 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1678 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1679 5119c79e René Nussbaumer
  @type pause: bool
1680 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1681 5119c79e René Nussbaumer

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

1712 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1713 10c2650b Iustin Pop

1714 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1715 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1716 10c2650b Iustin Pop
  @rtype: boolean
1717 10c2650b Iustin Pop
  @return: the success of the operation
1718 a8083063 Iustin Pop

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

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

1752 10c2650b Iustin Pop
  @note: this function is called recursively.
1753 a8083063 Iustin Pop

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

1762 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1763 10c2650b Iustin Pop
      was assembled)
1764 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1765 10c2650b Iustin Pop
      during the activation of the children or the device
1766 10c2650b Iustin Pop
      itself
1767 a8083063 Iustin Pop

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

1803 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1804 a8083063 Iustin Pop

1805 b1206984 Iustin Pop
  @rtype: str or boolean
1806 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1807 b1206984 Iustin Pop
      C{True} for secondary nodes
1808 a8083063 Iustin Pop

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

1828 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1829 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1830 c41eea6e Iustin Pop
  shutdown.
1831 a8083063 Iustin Pop

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

1836 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1837 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1838 10c2650b Iustin Pop
      shutdown
1839 c26a6bd2 Iustin Pop
  @rtype: None
1840 10c2650b Iustin Pop

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

1866 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1867 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1868 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1869 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1870 c26a6bd2 Iustin Pop
  @rtype: None
1871 10c2650b Iustin Pop

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

1885 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1886 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1887 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1888 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1889 c26a6bd2 Iustin Pop
  @rtype: None
1890 10c2650b Iustin Pop

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

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

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

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

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

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

1969 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1970 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1971 a8083063 Iustin Pop

1972 10c2650b Iustin Pop
  @return: None if the device can't be found,
1973 10c2650b Iustin Pop
      otherwise the device instance
1974 a8083063 Iustin Pop

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

1987 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1988 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1989 f2e07bb4 Michael Hanselmann

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

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

2005 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2006 10c2650b Iustin Pop
  @param disk: the disk to find
2007 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2008 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2009 96acbc09 Michael Hanselmann
           information
2010 a8083063 Iustin Pop

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

2026 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2027 968a7623 Iustin Pop

2028 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2029 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2030 968a7623 Iustin Pop
  @rtype: list
2031 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2032 968a7623 Iustin Pop
      otherwise the size
2033 968a7623 Iustin Pop

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

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

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

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

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

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

2142 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2143 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2144 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2145 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2146 b2f29800 René Nussbaumer

2147 b2f29800 René Nussbaumer
  @return: stdout
2148 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2149 b2f29800 René Nussbaumer

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

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

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

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

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

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

2251 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2252 8e70b181 Iustin Pop
  valid OS name.
2253 a8083063 Iustin Pop

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

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

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

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

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

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

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

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

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

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

2487 b954f097 Constantinos Venetsanopoulos
  @type top_dirs: list
2488 b954f097 Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
2489 b954f097 Constantinos Venetsanopoulos
      search (if not given defaults to
2490 b954f097 Constantinos Venetsanopoulos
      L{pathutils.ES_SEARCH_PATH})
2491 b954f097 Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
2492 b954f097 Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
2493 b954f097 Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
2494 b954f097 Constantinos Venetsanopoulos
      search paths, where:
2495 b954f097 Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
2496 b954f097 Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
2497 b954f097 Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
2498 b954f097 Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
2499 b954f097 Constantinos Venetsanopoulos
            otherwise empty
2500 b954f097 Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
2501 b954f097 Constantinos Venetsanopoulos

2502 b954f097 Constantinos Venetsanopoulos
  """
2503 b954f097 Constantinos Venetsanopoulos
  if top_dirs is None:
2504 b954f097 Constantinos Venetsanopoulos
    top_dirs = pathutils.ES_SEARCH_PATH
2505 b954f097 Constantinos Venetsanopoulos
2506 b954f097 Constantinos Venetsanopoulos
  result = []
2507 b954f097 Constantinos Venetsanopoulos
  for dir_name in top_dirs:
2508 b954f097 Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
2509 b954f097 Constantinos Venetsanopoulos
      try:
2510 b954f097 Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
2511 b954f097 Constantinos Venetsanopoulos
      except EnvironmentError, err:
2512 b954f097 Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
2513 b954f097 Constantinos Venetsanopoulos
                          dir_name, err)
2514 b954f097 Constantinos Venetsanopoulos
        break
2515 b954f097 Constantinos Venetsanopoulos
      for name in f_names:
2516 b954f097 Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
2517 b954f097 Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2518 b954f097 Constantinos Venetsanopoulos
        if status:
2519 b954f097 Constantinos Venetsanopoulos
          diagnose = ""
2520 b954f097 Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
2521 b954f097 Constantinos Venetsanopoulos
        else:
2522 b954f097 Constantinos Venetsanopoulos
          diagnose = es_inst
2523 b954f097 Constantinos Venetsanopoulos
          parameters = []
2524 b954f097 Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
2525 b954f097 Constantinos Venetsanopoulos
2526 b954f097 Constantinos Venetsanopoulos
  return result
2527 b954f097 Constantinos Venetsanopoulos
2528 b954f097 Constantinos Venetsanopoulos
2529 cad0723b Iustin Pop
def BlockdevGrow(disk, amount, dryrun, backingstore):
2530 594609c0 Iustin Pop
  """Grow a stack of block devices.
2531 594609c0 Iustin Pop

2532 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2533 10c2650b Iustin Pop
  first ones to resize.
2534 594609c0 Iustin Pop

2535 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2536 10c2650b Iustin Pop
  @param disk: the disk to be grown
2537 a59faf4b Iustin Pop
  @type amount: integer
2538 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2539 a59faf4b Iustin Pop
  @type dryrun: boolean
2540 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2541 a59faf4b Iustin Pop
      only, without actually increasing the size
2542 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
2543 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2544 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
2545 10c2650b Iustin Pop
  @rtype: (status, result)
2546 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2547 a59faf4b Iustin Pop
      the errors message if status is False
2548 594609c0 Iustin Pop

2549 594609c0 Iustin Pop
  """
2550 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2551 594609c0 Iustin Pop
  if r_dev is None:
2552 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2553 594609c0 Iustin Pop
2554 594609c0 Iustin Pop
  try:
2555 cad0723b Iustin Pop
    r_dev.Grow(amount, dryrun, backingstore)
2556 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2557 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2558 594609c0 Iustin Pop
2559 594609c0 Iustin Pop
2560 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2561 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2562 a8083063 Iustin Pop

2563 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2564 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2565 a8083063 Iustin Pop

2566 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2567 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2568 e9e9263d Guido Trotter
  @rtype: string
2569 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2570 a8083063 Iustin Pop

2571 098c0958 Michael Hanselmann
  """
2572 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2573 433c63aa Iustin Pop
    if not disk.children:
2574 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2575 433c63aa Iustin Pop
            disk.unique_id)
2576 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2577 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2578 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2579 a8083063 Iustin Pop
    if r_dev is not None:
2580 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2581 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2582 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2583 a8083063 Iustin Pop
    else:
2584 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2585 a8083063 Iustin Pop
  else:
2586 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2587 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2588 a8083063 Iustin Pop
2589 a8083063 Iustin Pop
2590 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
2591 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
2592 48e175a2 Iustin Pop

2593 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
2594 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
2595 48e175a2 Iustin Pop
  for example after renames.
2596 48e175a2 Iustin Pop

2597 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
2598 48e175a2 Iustin Pop
  @param disk: the disk to be grown
2599 48e175a2 Iustin Pop
  @type info: string
2600 48e175a2 Iustin Pop
  @param info: new 'info' metadata
2601 48e175a2 Iustin Pop
  @rtype: (status, result)
2602 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2603 48e175a2 Iustin Pop
      the errors message if status is False
2604 48e175a2 Iustin Pop

2605 48e175a2 Iustin Pop
  """
2606 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2607 48e175a2 Iustin Pop
  if r_dev is None:
2608 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2609 48e175a2 Iustin Pop
2610 48e175a2 Iustin Pop
  try:
2611 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
2612 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
2613 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
2614 48e175a2 Iustin Pop
2615 48e175a2 Iustin Pop
2616 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2617 a8083063 Iustin Pop
  """Write out the export configuration information.
2618 a8083063 Iustin Pop

2619 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2620 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2621 10c2650b Iustin Pop
      saving configuration
2622 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2623 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2624 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2625 a8083063 Iustin Pop

2626 c26a6bd2 Iustin Pop
  @rtype: None
2627 a8083063 Iustin Pop

2628 098c0958 Michael Hanselmann
  """
2629 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2630 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2631 a8083063 Iustin Pop
2632 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2633 a8083063 Iustin Pop
2634 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2635 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
2636 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2637 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2638 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
2639 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2640 a8083063 Iustin Pop
2641 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2642 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
2643 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2644 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2645 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
2646 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
2647 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2648 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
2649 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2650 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2651 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2652 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2653 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2654 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2655 66f93869 Manuel Franceschini
2656 95268cc3 Iustin Pop
  nic_total = 0
2657 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2658 95268cc3 Iustin Pop
    nic_total += 1
2659 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
2660 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
2661 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2662 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2663 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
2664 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2665 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2666 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
2667 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2668 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2669 a8083063 Iustin Pop
2670 726d7d68 Iustin Pop
  disk_total = 0
2671 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2672 19d7f90a Guido Trotter
    if disk:
2673 726d7d68 Iustin Pop
      disk_total += 1
2674 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2675 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
2676 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2677 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
2678 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2679 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
2680 d0c8c01d Iustin Pop
2681 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2682 a8083063 Iustin Pop
2683 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2684 3c8954ad Iustin Pop
2685 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2686 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2687 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2688 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2689 3c8954ad Iustin Pop
2690 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2691 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2692 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2693 3c8954ad Iustin Pop
2694 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2695 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2696 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2697 535b49cb Iustin Pop
2698 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2699 726d7d68 Iustin Pop
                  data=config.Dumps())
2700 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2701 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2702 a8083063 Iustin Pop
2703 a8083063 Iustin Pop
2704 a8083063 Iustin Pop
def ExportInfo(dest):
2705 a8083063 Iustin Pop
  """Get export configuration information.
2706 a8083063 Iustin Pop

2707 10c2650b Iustin Pop
  @type dest: str
2708 10c2650b Iustin Pop
  @param dest: directory containing the export
2709 a8083063 Iustin Pop

2710 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2711 10c2650b Iustin Pop
  @return: a serializable config file containing the
2712 10c2650b Iustin Pop
      export info
2713 a8083063 Iustin Pop

2714 a8083063 Iustin Pop
  """
2715 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2716 a8083063 Iustin Pop
2717 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2718 a8083063 Iustin Pop
  config.read(cff)
2719 a8083063 Iustin Pop
2720 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2721 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2722 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2723 a8083063 Iustin Pop
2724 c26a6bd2 Iustin Pop
  return config.Dumps()
2725 a8083063 Iustin Pop
2726 a8083063 Iustin Pop
2727 a8083063 Iustin Pop
def ListExports():
2728 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2729 098c0958 Michael Hanselmann

2730 10c2650b Iustin Pop
  @rtype: list
2731 10c2650b Iustin Pop
  @return: list of the exports
2732 10c2650b Iustin Pop

2733 a8083063 Iustin Pop
  """
2734 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
2735 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2736 a8083063 Iustin Pop
  else:
2737 afdc3985 Iustin Pop
    _Fail("No exports directory")
2738 a8083063 Iustin Pop
2739 a8083063 Iustin Pop
2740 a8083063 Iustin Pop
def RemoveExport(export):
2741 a8083063 Iustin Pop
  """Remove an existing export from the node.
2742 a8083063 Iustin Pop

2743 10c2650b Iustin Pop
  @type export: str
2744 10c2650b Iustin Pop
  @param export: the name of the export to remove
2745 c26a6bd2 Iustin Pop
  @rtype: None
2746 a8083063 Iustin Pop

2747 098c0958 Michael Hanselmann
  """
2748 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2749 a8083063 Iustin Pop
2750 35fbcd11 Iustin Pop
  try:
2751 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2752 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2753 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2754 a8083063 Iustin Pop
2755 a8083063 Iustin Pop
2756 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2757 f3e513ad Iustin Pop
  """Rename a list of block devices.
2758 f3e513ad Iustin Pop

2759 10c2650b Iustin Pop
  @type devlist: list of tuples
2760 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2761 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2762 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2763 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2764 10c2650b Iustin Pop
      rename it to
2765 10c2650b Iustin Pop
  @rtype: boolean
2766 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2767 f3e513ad Iustin Pop

2768 f3e513ad Iustin Pop
  """
2769 6b5e3f70 Iustin Pop
  msgs = []
2770 f3e513ad Iustin Pop
  result = True
2771 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2772 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2773 f3e513ad Iustin Pop
    if dev is None:
2774 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2775 f3e513ad Iustin Pop
      result = False
2776 f3e513ad Iustin Pop
      continue
2777 f3e513ad Iustin Pop
    try:
2778 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2779 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2780 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2781 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2782 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2783 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2784 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2785 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2786 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2787 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2788 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2789 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2790 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2791 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2792 f3e513ad Iustin Pop
      result = False
2793 afdc3985 Iustin Pop
  if not result:
2794 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2795 f3e513ad Iustin Pop
2796 f3e513ad Iustin Pop
2797 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2798 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2799 778b75bb Manuel Franceschini

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

2804 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2805 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2806 d61cbe76 Iustin Pop

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

2809 778b75bb Manuel Franceschini
  """
2810 63a3d8f7 Michael Hanselmann
  if not (constants.ENABLE_FILE_STORAGE or
2811 63a3d8f7 Michael Hanselmann
          constants.ENABLE_SHARED_FILE_STORAGE):
2812 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2813 5e09a309 Michael Hanselmann
2814 5e09a309 Michael Hanselmann
  bdev.CheckFileStoragePath(fs_dir)
2815 5e09a309 Michael Hanselmann
2816 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
2817 778b75bb Manuel Franceschini
2818 778b75bb Manuel Franceschini
2819 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2820 778b75bb Manuel Franceschini
  """Create file storage directory.
2821 778b75bb Manuel Franceschini

2822 b1206984 Iustin Pop
  @type file_storage_dir: str
2823 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2824 778b75bb Manuel Franceschini

2825 b1206984 Iustin Pop
  @rtype: tuple
2826 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2827 b1206984 Iustin Pop
      creation was successful or not
2828 778b75bb Manuel Franceschini

2829 778b75bb Manuel Franceschini
  """
2830 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2831 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2832 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2833 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2834 b2b8bcce Iustin Pop
            file_storage_dir)
2835 778b75bb Manuel Franceschini
  else:
2836 b2b8bcce Iustin Pop
    try:
2837 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2838 b2b8bcce Iustin Pop
    except OSError, err:
2839 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2840 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2841 778b75bb Manuel Franceschini
2842 778b75bb Manuel Franceschini
2843 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2844 778b75bb Manuel Franceschini
  """Remove file storage directory.
2845 778b75bb Manuel Franceschini

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

2848 10c2650b Iustin Pop
  @type file_storage_dir: str
2849 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2850 10c2650b Iustin Pop
  @rtype: tuple (success,)
2851 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2852 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2853 778b75bb Manuel Franceschini

2854 778b75bb Manuel Franceschini
  """
2855 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2856 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2857 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2858 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2859 b2b8bcce Iustin Pop
            file_storage_dir)
2860 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2861 b2b8bcce Iustin Pop
    try:
2862 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2863 b2b8bcce Iustin Pop
    except OSError, err:
2864 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2865 b2b8bcce Iustin Pop
            file_storage_dir, err)
2866 b2b8bcce Iustin Pop
2867 778b75bb Manuel Franceschini
2868 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2869 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2870 778b75bb Manuel Franceschini

2871 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2872 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2873 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2874 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2875 10c2650b Iustin Pop
  @rtype: tuple (success,)
2876 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2877 10c2650b Iustin Pop
      whether the operation was successful
2878 778b75bb Manuel Franceschini

2879 778b75bb Manuel Franceschini
  """
2880 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2881 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2882 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2883 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2884 b2b8bcce Iustin Pop
      try:
2885 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2886 b2b8bcce Iustin Pop
      except OSError, err:
2887 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2888 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2889 778b75bb Manuel Franceschini
    else:
2890 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2891 b2b8bcce Iustin Pop
            old_file_storage_dir)
2892 b2b8bcce Iustin Pop
  else:
2893 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2894 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2895 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2896 778b75bb Manuel Franceschini
2897 778b75bb Manuel Franceschini
2898 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2899 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2900 ca52cdeb Michael Hanselmann

2901 10c2650b Iustin Pop
  @type file_name: str
2902 10c2650b Iustin Pop
  @param file_name: the file name we should check
2903 c8457ce7 Iustin Pop
  @rtype: None
2904 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2905 10c2650b Iustin Pop

2906 ca52cdeb Michael Hanselmann
  """
2907 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2908 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2909 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2910 dc31eae3 Michael Hanselmann
2911 dc31eae3 Michael Hanselmann
2912 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2913 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2914 dc31eae3 Michael Hanselmann

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

2918 10c2650b Iustin Pop
  @type file_name: str
2919 10c2650b Iustin Pop
  @param file_name: the job file name
2920 10c2650b Iustin Pop
  @type content: str
2921 10c2650b Iustin Pop
  @param content: the new job contents
2922 10c2650b Iustin Pop
  @rtype: boolean
2923 10c2650b Iustin Pop
  @return: the success of the operation
2924 10c2650b Iustin Pop

2925 dc31eae3 Michael Hanselmann
  """
2926 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2927 cffbbae7 Michael Hanselmann
2928 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2929 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2930 ca52cdeb Michael Hanselmann
2931 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2932 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2933 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2934 ca52cdeb Michael Hanselmann
2935 ca52cdeb Michael Hanselmann
2936 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2937 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2938 af5ebcb1 Michael Hanselmann

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

2941 10c2650b Iustin Pop
  @type old: str
2942 10c2650b Iustin Pop
  @param old: the old (actual) file name
2943 10c2650b Iustin Pop
  @type new: str
2944 10c2650b Iustin Pop
  @param new: the desired file name
2945 c8457ce7 Iustin Pop
  @rtype: tuple
2946 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2947 10c2650b Iustin Pop

2948 af5ebcb1 Michael Hanselmann
  """
2949 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
2950 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
2951 cffbbae7 Michael Hanselmann
2952 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2953 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2954 af5ebcb1 Michael Hanselmann
2955 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
2956 8e5a705d René Nussbaumer
2957 8e5a705d René Nussbaumer
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2958 8e5a705d René Nussbaumer
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2959 af5ebcb1 Michael Hanselmann
2960 af5ebcb1 Michael Hanselmann
2961 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2962 d61cbe76 Iustin Pop
  """Closes the given block devices.
2963 d61cbe76 Iustin Pop

2964 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2965 10c2650b Iustin Pop
  DRBD).
2966 10c2650b Iustin Pop

2967 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2968 b2e7666a Iustin Pop
      of this instance will be removed
2969 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2970 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2971 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2972 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2973 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2974 10c2650b Iustin Pop
      which will contain the error details in case we
2975 10c2650b Iustin Pop
      failed
2976 d61cbe76 Iustin Pop

2977 d61cbe76 Iustin Pop
  """
2978 d61cbe76 Iustin Pop
  bdevs = []
2979 d61cbe76 Iustin Pop
  for cf in disks:
2980 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2981 d61cbe76 Iustin Pop
    if rd is None:
2982 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2983 d61cbe76 Iustin Pop
    bdevs.append(rd)
2984 d61cbe76 Iustin Pop
2985 d61cbe76 Iustin Pop
  msg = []
2986 d61cbe76 Iustin Pop
  for rd in bdevs:
2987 d61cbe76 Iustin Pop
    try:
2988 d61cbe76 Iustin Pop
      rd.Close()
2989 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2990 d61cbe76 Iustin Pop
      msg.append(str(err))
2991 d61cbe76 Iustin Pop
  if msg:
2992 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2993 d61cbe76 Iustin Pop
  else:
2994 b2e7666a Iustin Pop
    if instance_name:
2995 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2996 d61cbe76 Iustin Pop
2997 d61cbe76 Iustin Pop
2998 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2999 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
3000 6217e295 Iustin Pop

3001 6217e295 Iustin Pop
  @type hvname: string
3002 6217e295 Iustin Pop
  @param hvname: the hypervisor name
3003 6217e295 Iustin Pop
  @type hvparams: dict
3004 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
3005 c26a6bd2 Iustin Pop
  @rtype: None
3006 6217e295 Iustin Pop

3007 6217e295 Iustin Pop
  """
3008 6217e295 Iustin Pop
  try:
3009 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
3010 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
3011 6217e295 Iustin Pop
  except errors.HypervisorError, err:
3012 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
3013 6217e295 Iustin Pop
3014 6217e295 Iustin Pop
3015 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
3016 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
3017 acd9ff9e Iustin Pop

3018 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
3019 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
3020 acd9ff9e Iustin Pop
  @type parameters: list
3021 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
3022 acd9ff9e Iustin Pop

3023 acd9ff9e Iustin Pop
  """
3024 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
3025 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
3026 acd9ff9e Iustin Pop
  if delta:
3027 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
3028 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3029 acd9ff9e Iustin Pop
3030 acd9ff9e Iustin Pop
3031 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
3032 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
3033 acd9ff9e Iustin Pop

3034 acd9ff9e Iustin Pop
  @type required: boolean
3035 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3036 acd9ff9e Iustin Pop
      failure or not
3037 acd9ff9e Iustin Pop
  @type osname: string
3038 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3039 acd9ff9e Iustin Pop
  @type checks: list
3040 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3041 acd9ff9e Iustin Pop
  @type osparams: dict
3042 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
3043 acd9ff9e Iustin Pop
  @rtype: boolean
3044 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3045 acd9ff9e Iustin Pop
      found and L{required} was false
3046 acd9ff9e Iustin Pop

3047 acd9ff9e Iustin Pop
  """
3048 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3049 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3050 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3051 acd9ff9e Iustin Pop
3052 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3053 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3054 acd9ff9e Iustin Pop
3055 acd9ff9e Iustin Pop
  if not status:
3056 acd9ff9e Iustin Pop
    if required:
3057 acd9ff9e Iustin Pop
      _Fail(tbv)
3058 acd9ff9e Iustin Pop
    else:
3059 acd9ff9e Iustin Pop
      return False
3060 acd9ff9e Iustin Pop
3061 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3062 72db3fd7 Iustin Pop
    return True
3063 72db3fd7 Iustin Pop
3064 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3065 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3066 acd9ff9e Iustin Pop
3067 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3068 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3069 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3070 acd9ff9e Iustin Pop
  if result.failed:
3071 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3072 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3073 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3074 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3075 acd9ff9e Iustin Pop
3076 acd9ff9e Iustin Pop
  return True
3077 acd9ff9e Iustin Pop
3078 acd9ff9e Iustin Pop
3079 56aa9fd5 Iustin Pop
def DemoteFromMC():
3080 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3081 56aa9fd5 Iustin Pop

3082 56aa9fd5 Iustin Pop
  """
3083 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3084 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3085 56aa9fd5 Iustin Pop
  if master == myself:
3086 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3087 f154a7a3 Michael Hanselmann
3088 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3089 f154a7a3 Michael Hanselmann
  if not result.failed:
3090 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3091 f154a7a3 Michael Hanselmann
3092 56aa9fd5 Iustin Pop
  try:
3093 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3094 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3095 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3096 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3097 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3098 f154a7a3 Michael Hanselmann
3099 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3100 56aa9fd5 Iustin Pop
3101 56aa9fd5 Iustin Pop
3102 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3103 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3104 f942a838 Michael Hanselmann

3105 f942a838 Michael Hanselmann
  """
3106 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3107 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3108 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3109 f942a838 Michael Hanselmann
3110 f942a838 Michael Hanselmann
3111 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3112 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3113 f942a838 Michael Hanselmann

3114 f942a838 Michael Hanselmann
  @type validity: int
3115 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3116 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3117 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3118 f942a838 Michael Hanselmann

3119 f942a838 Michael Hanselmann
  """
3120 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3121 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3122 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3123 f942a838 Michael Hanselmann
3124 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3125 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3126 f942a838 Michael Hanselmann
  try:
3127 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3128 f942a838 Michael Hanselmann
    assert len(name) > 5
3129 f942a838 Michael Hanselmann
3130 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3131 f942a838 Michael Hanselmann
3132 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3133 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3134 f942a838 Michael Hanselmann
3135 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3136 f942a838 Michael Hanselmann
    return (name, cert_pem)
3137 f942a838 Michael Hanselmann
  except Exception:
3138 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3139 f942a838 Michael Hanselmann
    raise
3140 f942a838 Michael Hanselmann
3141 f942a838 Michael Hanselmann
3142 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3143 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3144 f942a838 Michael Hanselmann

3145 f942a838 Michael Hanselmann
  @type name: string
3146 f942a838 Michael Hanselmann
  @param name: Certificate name
3147 f942a838 Michael Hanselmann

3148 f942a838 Michael Hanselmann
  """
3149 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3150 f942a838 Michael Hanselmann
3151 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3152 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3153 f942a838 Michael Hanselmann
3154 f942a838 Michael Hanselmann
  try:
3155 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3156 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3157 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3158 f942a838 Michael Hanselmann
          cert_dir, err)
3159 f942a838 Michael Hanselmann
3160 f942a838 Michael Hanselmann
3161 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3162 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3163 1651d116 Michael Hanselmann

3164 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3165 1651d116 Michael Hanselmann
  @param instance: The instance object
3166 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3167 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3168 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3169 1651d116 Michael Hanselmann

3170 1651d116 Michael Hanselmann
  """
3171 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3172 1651d116 Michael Hanselmann
3173 1651d116 Michael Hanselmann
  env = None
3174 1651d116 Michael Hanselmann
  prefix = None
3175 1651d116 Michael Hanselmann
  suffix = None
3176 2ad5550d Michael Hanselmann
  exp_size = None
3177 1651d116 Michael Hanselmann
3178 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
3179 1651d116 Michael Hanselmann
    (filename, ) = ieargs
3180 1651d116 Michael Hanselmann
3181 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
3182 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
3183 1651d116 Michael Hanselmann
3184 748c9884 René Nussbaumer
    real_filename = os.path.realpath(filename)
3185 748c9884 René Nussbaumer
    directory = os.path.dirname(real_filename)
3186 1651d116 Michael Hanselmann
3187 710f30ec Michael Hanselmann
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3188 748c9884 René Nussbaumer
      _Fail("File '%s' is not under exports directory '%s': %s",
3189 710f30ec Michael Hanselmann
            filename, pathutils.EXPORT_DIR, real_filename)
3190 1651d116 Michael Hanselmann
3191 1651d116 Michael Hanselmann
    # Create directory
3192 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
3193 1651d116 Michael Hanselmann
3194 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
3195 1651d116 Michael Hanselmann
3196 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3197 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
3198 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3199 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
3200 1651d116 Michael Hanselmann
3201 2ad5550d Michael Hanselmann
      # Retrieve file size
3202 2ad5550d Michael Hanselmann
      try:
3203 2ad5550d Michael Hanselmann
        st = os.stat(filename)
3204 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
3205 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
3206 2ad5550d Michael Hanselmann
      else:
3207 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
3208 2ad5550d Michael Hanselmann
3209 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
3210 1651d116 Michael Hanselmann
    (disk, ) = ieargs
3211 1651d116 Michael Hanselmann
3212 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3213 1651d116 Michael Hanselmann
3214 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3215 1651d116 Michael Hanselmann
      # we set here a smaller block size as, due to transport buffering, more
3216 1651d116 Michael Hanselmann
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3217 1651d116 Michael Hanselmann
      # is not already there or we pass a wrong path; we use notrunc to no
3218 1651d116 Michael Hanselmann
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3219 1651d116 Michael Hanselmann
      # much memory; this means that at best, we flush every 64k, which will
3220 1651d116 Michael Hanselmann
      # not be very fast
3221 1651d116 Michael Hanselmann
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3222 1651d116 Michael Hanselmann
                                    " bs=%s oflag=dsync"),
3223 1651d116 Michael Hanselmann
                                    real_disk.dev_path,
3224 1651d116 Michael Hanselmann
                                    str(64 * 1024))
3225 1651d116 Michael Hanselmann
3226 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3227 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
3228 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3229 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
3230 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
3231 1651d116 Michael Hanselmann
                                   str(disk.size))
3232 2ad5550d Michael Hanselmann
      exp_size = disk.size
3233 1651d116 Michael Hanselmann
3234 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
3235 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
3236 1651d116 Michael Hanselmann
3237 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
3238 1651d116 Michael Hanselmann
3239 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3240 1651d116 Michael Hanselmann
3241 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
3242 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
3243 1651d116 Michael Hanselmann
3244 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3245 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3246 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
3247 1651d116 Michael Hanselmann
      script = inst_os.import_script
3248 1651d116 Michael Hanselmann
3249 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3250 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
3251 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
3252 1651d116 Michael Hanselmann
      script = inst_os.export_script
3253 1651d116 Michael Hanselmann
3254 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
3255 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3256 1651d116 Michael Hanselmann
3257 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3258 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
3259 1651d116 Michael Hanselmann
3260 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3261 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
3262 1651d116 Michael Hanselmann
3263 2ad5550d Michael Hanselmann
    # Let script predict size
3264 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
3265 2ad5550d Michael Hanselmann
3266 1651d116 Michael Hanselmann
  else:
3267 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3268 1651d116 Michael Hanselmann
3269 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
3270 1651d116 Michael Hanselmann
3271 1651d116 Michael Hanselmann
3272 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
3273 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
3274 1651d116 Michael Hanselmann

3275 1651d116 Michael Hanselmann
  """
3276 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3277 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3278 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3279 1651d116 Michael Hanselmann
3280 1651d116 Michael Hanselmann
3281 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3282 6613661a Iustin Pop
                            ieio, ieioargs):
3283 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3284 1651d116 Michael Hanselmann

3285 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3286 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3287 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3288 1651d116 Michael Hanselmann
  @type host: string
3289 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3290 1651d116 Michael Hanselmann
  @type port: int
3291 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3292 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3293 1651d116 Michael Hanselmann
  @param instance: Instance object
3294 6613661a Iustin Pop
  @type component: string
3295 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3296 6613661a Iustin Pop
      e.g. 'disk/0'
3297 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3298 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3299 1651d116 Michael Hanselmann

3300 1651d116 Michael Hanselmann
  """
3301 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
3302 1651d116 Michael Hanselmann
    prefix = "import"
3303 1651d116 Michael Hanselmann
3304 1651d116 Michael Hanselmann
    if not (host is None and port is None):
3305 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
3306 1651d116 Michael Hanselmann
3307 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
3308 1651d116 Michael Hanselmann
    prefix = "export"
3309 1651d116 Michael Hanselmann
3310 1651d116 Michael Hanselmann
    if host is None or port is None:
3311 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
3312 1651d116 Michael Hanselmann
3313 1651d116 Michael Hanselmann
  else:
3314 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
3315 1651d116 Michael Hanselmann
3316 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
3317 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
3318 1651d116 Michael Hanselmann
3319 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3320 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3321 1651d116 Michael Hanselmann
3322 eb630f50 Michael Hanselmann
  if opts.key_name is None:
3323 1651d116 Michael Hanselmann
    # Use server.pem
3324 710f30ec Michael Hanselmann
    key_path = pathutils.NODED_CERT_FILE
3325 710f30ec Michael Hanselmann
    cert_path = pathutils.NODED_CERT_FILE
3326 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
3327 1651d116 Michael Hanselmann
  else:
3328 710f30ec Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3329 eb630f50 Michael Hanselmann
                                                 opts.key_name)
3330 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
3331 1651d116 Michael Hanselmann
3332 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
3333 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
3334 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
3335 63bcea2a Michael Hanselmann
3336 6613661a Iustin Pop
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3337 1651d116 Michael Hanselmann
  try:
3338 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3339 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3340 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3341 1651d116 Michael Hanselmann
3342 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
3343 1651d116 Michael Hanselmann
      # Use server.pem
3344 710f30ec Michael Hanselmann
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3345 eb630f50 Michael Hanselmann
    else:
3346 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
3347 63bcea2a Michael Hanselmann
3348 eb630f50 Michael Hanselmann
    # Write CA file
3349 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
3350 1651d116 Michael Hanselmann
3351 1651d116 Michael Hanselmann
    cmd = [
3352 710f30ec Michael Hanselmann
      pathutils.IMPORT_EXPORT_DAEMON,
3353 1651d116 Michael Hanselmann
      status_file, mode,
3354 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
3355 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
3356 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
3357 1651d116 Michael Hanselmann
      ]
3358 1651d116 Michael Hanselmann
3359 1651d116 Michael Hanselmann
    if host:
3360 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
3361 1651d116 Michael Hanselmann
3362 1651d116 Michael Hanselmann
    if port:
3363 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
3364 1651d116 Michael Hanselmann
3365 855d2fc7 Michael Hanselmann
    if opts.ipv6:
3366 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
3367 855d2fc7 Michael Hanselmann
    else:
3368 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
3369 855d2fc7 Michael Hanselmann
3370 a5310c2a Michael Hanselmann
    if opts.compress:
3371 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
3372 a5310c2a Michael Hanselmann
3373 af1d39b1 Michael Hanselmann
    if opts.magic:
3374 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
3375 af1d39b1 Michael Hanselmann
3376 2ad5550d Michael Hanselmann
    if exp_size is not None:
3377 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
3378 2ad5550d Michael Hanselmann
3379 1651d116 Michael Hanselmann
    if cmd_prefix:
3380 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3381 1651d116 Michael Hanselmann
3382 1651d116 Michael Hanselmann
    if cmd_suffix:
3383 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3384 1651d116 Michael Hanselmann
3385 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
3386 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
3387 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3388 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3389 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
3390 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
3391 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
3392 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3393 4478301b Michael Hanselmann
3394 6aa7a354 Iustin Pop
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3395 1651d116 Michael Hanselmann
3396 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3397 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
3398 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3399 1651d116 Michael Hanselmann
                      output=logfile)
3400 1651d116 Michael Hanselmann
3401 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
3402 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
3403 1651d116 Michael Hanselmann
3404 1651d116 Michael Hanselmann
  except Exception:
3405 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
3406 1651d116 Michael Hanselmann
    raise
3407 1651d116 Michael Hanselmann
3408 1651d116 Michael Hanselmann
3409 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
3410 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
3411 1651d116 Michael Hanselmann

3412 1651d116 Michael Hanselmann
  @type names: sequence
3413 1651d116 Michael Hanselmann
  @param names: List of names
3414 1651d116 Michael Hanselmann
  @rtype: List of dicts
3415 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3416 1651d116 Michael Hanselmann
           status couldn't be read
3417 1651d116 Michael Hanselmann

3418 1651d116 Michael Hanselmann
  """
3419 1651d116 Michael Hanselmann
  result = []
3420 1651d116 Michael Hanselmann
3421 1651d116 Michael Hanselmann
  for name in names:
3422 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3423 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3424 1651d116 Michael Hanselmann
3425 1651d116 Michael Hanselmann
    try:
3426 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3427 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3428 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3429 1651d116 Michael Hanselmann
        raise
3430 1651d116 Michael Hanselmann
      data = None
3431 1651d116 Michael Hanselmann
3432 1651d116 Michael Hanselmann
    if not data:
3433 1651d116 Michael Hanselmann
      result.append(None)
3434 1651d116 Michael Hanselmann
      continue
3435 1651d116 Michael Hanselmann
3436 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3437 1651d116 Michael Hanselmann
3438 1651d116 Michael Hanselmann
  return result
3439 1651d116 Michael Hanselmann
3440 1651d116 Michael Hanselmann
3441 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3442 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3443 f81c4737 Michael Hanselmann

3444 f81c4737 Michael Hanselmann
  """
3445 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3446 f81c4737 Michael Hanselmann
3447 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3448 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3449 f81c4737 Michael Hanselmann
3450 f81c4737 Michael Hanselmann
  if pid:
3451 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3452 f81c4737 Michael Hanselmann
                 name, pid)
3453 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3454 f81c4737 Michael Hanselmann
3455 f81c4737 Michael Hanselmann
3456 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3457 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3458 1651d116 Michael Hanselmann

3459 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3460 1651d116 Michael Hanselmann
  whole status directory is removed.
3461 1651d116 Michael Hanselmann

3462 1651d116 Michael Hanselmann
  """
3463 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3464 1651d116 Michael Hanselmann
3465 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3466 1651d116 Michael Hanselmann
3467 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3468 1651d116 Michael Hanselmann
3469 1651d116 Michael Hanselmann
  if pid:
3470 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3471 1651d116 Michael Hanselmann
                 name, pid)
3472 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3473 1651d116 Michael Hanselmann
3474 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3475 1651d116 Michael Hanselmann
3476 1651d116 Michael Hanselmann
3477 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3478 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3479 6b93ec9d Iustin Pop

3480 6b93ec9d Iustin Pop
  """
3481 6b93ec9d Iustin Pop
  # set the correct physical ID
3482 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3483 6b93ec9d Iustin Pop
  for cf in disks:
3484 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3485 6b93ec9d Iustin Pop
3486 6b93ec9d Iustin Pop
  bdevs = []
3487 6b93ec9d Iustin Pop
3488 6b93ec9d Iustin Pop
  for cf in disks:
3489 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3490 6b93ec9d Iustin Pop
    if rd is None:
3491 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3492 6b93ec9d Iustin Pop
    bdevs.append(rd)
3493 5a533f8a Iustin Pop
  return bdevs
3494 6b93ec9d Iustin Pop
3495 6b93ec9d Iustin Pop
3496 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3497 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3498 6b93ec9d Iustin Pop

3499 6b93ec9d Iustin Pop
  """
3500 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3501 6b93ec9d Iustin Pop
3502 6b93ec9d Iustin Pop
  # disconnect disks
3503 6b93ec9d Iustin Pop
  for rd in bdevs:
3504 6b93ec9d Iustin Pop
    try:
3505 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3506 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3507 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3508 2cc6781a Iustin Pop
            err, exc=True)
3509 6b93ec9d Iustin Pop
3510 6b93ec9d Iustin Pop
3511 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3512 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3513 6b93ec9d Iustin Pop

3514 6b93ec9d Iustin Pop
  """
3515 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3516 6b93ec9d Iustin Pop
3517 6b93ec9d Iustin Pop
  if multimaster:
3518 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3519 6b93ec9d Iustin Pop
      try:
3520 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3521 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3522 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3523 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3524 6b93ec9d Iustin Pop
  # needed primary mode
3525 6b93ec9d Iustin Pop
  for rd in bdevs:
3526 6b93ec9d Iustin Pop
    try:
3527 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3528 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3529 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3530 3c0cdc83 Michael Hanselmann
3531 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3532 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3533 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3534 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3535 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3536 3c0cdc83 Michael Hanselmann
3537 3c0cdc83 Michael Hanselmann
  def _Attach():
3538 6b93ec9d Iustin Pop
    all_connected = True
3539 3c0cdc83 Michael Hanselmann
3540 6b93ec9d Iustin Pop
    for rd in bdevs:
3541 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3542 3c0cdc83 Michael Hanselmann
3543 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3544 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3545 3c0cdc83 Michael Hanselmann
3546 6b93ec9d Iustin Pop
      if stats.is_standalone:
3547 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3548 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3549 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3550 6b93ec9d Iustin Pop
        try:
3551 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3552 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3553 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3554 3c0cdc83 Michael Hanselmann
3555 3c0cdc83 Michael Hanselmann
    if not all_connected:
3556 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3557 3c0cdc83 Michael Hanselmann
3558 3c0cdc83 Michael Hanselmann
  try:
3559 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3560 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3561 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3562 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3563 3c0cdc83 Michael Hanselmann
3564 6b93ec9d Iustin Pop
  if multimaster:
3565 6b93ec9d Iustin Pop
    # change to primary mode
3566 6b93ec9d Iustin Pop
    for rd in bdevs:
3567 d3da87b8 Iustin Pop
      try:
3568 d3da87b8 Iustin Pop
        rd.Open()
3569 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3570 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3571 6b93ec9d Iustin Pop
3572 6b93ec9d Iustin Pop
3573 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3574 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3575 6b93ec9d Iustin Pop

3576 6b93ec9d Iustin Pop
  """
3577 db8667b7 Iustin Pop
  def _helper(rd):
3578 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3579 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3580 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3581 db8667b7 Iustin Pop
    return stats
3582 db8667b7 Iustin Pop
3583 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3584 6b93ec9d Iustin Pop
3585 6b93ec9d Iustin Pop
  min_resync = 100
3586 6b93ec9d Iustin Pop
  alldone = True
3587 6b93ec9d Iustin Pop
  for rd in bdevs:
3588 db8667b7 Iustin Pop
    try:
3589 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3590 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3591 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3592 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3593 db8667b7 Iustin Pop
      # last check
3594 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3595 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3596 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3597 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3598 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3599 afdc3985 Iustin Pop
3600 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3601 6b93ec9d Iustin Pop
3602 6b93ec9d Iustin Pop
3603 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3604 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3605 c46b9782 Luca Bigliardi

3606 c46b9782 Luca Bigliardi
  """
3607 c46b9782 Luca Bigliardi
  try:
3608 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3609 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3610 c46b9782 Luca Bigliardi
    _Fail(str(err))
3611 c46b9782 Luca Bigliardi
3612 c46b9782 Luca Bigliardi
3613 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3614 f5118ade Iustin Pop
  """Hard-powercycle the node.
3615 f5118ade Iustin Pop

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

3619 f5118ade Iustin Pop
  """
3620 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3621 f5118ade Iustin Pop
  try:
3622 f5118ade Iustin Pop
    pid = os.fork()
3623 29921401 Iustin Pop
  except OSError:
3624 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3625 f5118ade Iustin Pop
    pid = 0
3626 f5118ade Iustin Pop
  if pid > 0:
3627 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3628 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3629 1af6ac0f Luca Bigliardi
  try:
3630 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3631 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3632 1af6ac0f Luca Bigliardi
    pass
3633 f5118ade Iustin Pop
  time.sleep(5)
3634 f5118ade Iustin Pop
  hyper.PowercycleNode()
3635 f5118ade Iustin Pop
3636 f5118ade Iustin Pop
3637 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
3638 1a2eb2dc Michael Hanselmann
  """Verifies a remote command name.
3639 1a2eb2dc Michael Hanselmann

3640 1a2eb2dc Michael Hanselmann
  @type cmd: string
3641 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3642 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3643 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3644 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3645 1a2eb2dc Michael Hanselmann

3646 1a2eb2dc Michael Hanselmann
  """
3647 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
3648 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
3649 1a2eb2dc Michael Hanselmann
3650 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
3651 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
3652 1a2eb2dc Michael Hanselmann
3653 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3654 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
3655 1a2eb2dc Michael Hanselmann
3656 1a2eb2dc Michael Hanselmann
  return (True, None)
3657 1a2eb2dc Michael Hanselmann
3658 1a2eb2dc Michael Hanselmann
3659 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
3660 1a2eb2dc Michael Hanselmann
  """Common checks for remote command file system directories and files.
3661 1a2eb2dc Michael Hanselmann

3662 1a2eb2dc Michael Hanselmann
  @type path: string
3663 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3664 1a2eb2dc Michael Hanselmann
  @param owner: C{None} or tuple containing UID and GID
3665 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or C{os.stat} result)
3666 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3667 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's the result of C{os.stat}
3668 1a2eb2dc Michael Hanselmann

3669 1a2eb2dc Michael Hanselmann
  """
3670 1a2eb2dc Michael Hanselmann
  if owner is None:
3671 1a2eb2dc Michael Hanselmann
    # Default to root as owner
3672 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
3673 1a2eb2dc Michael Hanselmann
3674 1a2eb2dc Michael Hanselmann
  try:
3675 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
3676 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
3677 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3678 1a2eb2dc Michael Hanselmann
3679 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3680 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
3681 1a2eb2dc Michael Hanselmann
3682 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
3683 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
3684 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3685 1a2eb2dc Michael Hanselmann
3686 1a2eb2dc Michael Hanselmann
  return (True, st)
3687 1a2eb2dc Michael Hanselmann
3688 1a2eb2dc Michael Hanselmann
3689 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3690 1a2eb2dc Michael Hanselmann
  """Verifies remote command directory.
3691 1a2eb2dc Michael Hanselmann

3692 1a2eb2dc Michael Hanselmann
  @type path: string
3693 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3694 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3695 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3696 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3697 1a2eb2dc Michael Hanselmann

3698 1a2eb2dc Michael Hanselmann
  """
3699 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3700 1a2eb2dc Michael Hanselmann
3701 1a2eb2dc Michael Hanselmann
  if not status:
3702 1a2eb2dc Michael Hanselmann
    return (False, value)
3703 1a2eb2dc Michael Hanselmann
3704 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
3705 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
3706 1a2eb2dc Michael Hanselmann
3707 1a2eb2dc Michael Hanselmann
  return (True, None)
3708 1a2eb2dc Michael Hanselmann
3709 1a2eb2dc Michael Hanselmann
3710 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3711 1a2eb2dc Michael Hanselmann
  """Verifies a whole remote command and returns its executable filename.
3712 1a2eb2dc Michael Hanselmann

3713 1a2eb2dc Michael Hanselmann
  @type path: string
3714 1a2eb2dc Michael Hanselmann
  @param path: Directory containing remote commands
3715 1a2eb2dc Michael Hanselmann
  @type cmd: string
3716 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3717 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
3718 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3719 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
3720 1a2eb2dc Michael Hanselmann
    absolute path to the executable
3721 1a2eb2dc Michael Hanselmann

3722 1a2eb2dc Michael Hanselmann
  """
3723 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
3724 1a2eb2dc Michael Hanselmann
3725 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3726 1a2eb2dc Michael Hanselmann
3727 1a2eb2dc Michael Hanselmann
  if not status:
3728 1a2eb2dc Michael Hanselmann
    return (False, msg)
3729 1a2eb2dc Michael Hanselmann
3730 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
3731 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3732 1a2eb2dc Michael Hanselmann
3733 1a2eb2dc Michael Hanselmann
  return (True, executable)
3734 1a2eb2dc Michael Hanselmann
3735 1a2eb2dc Michael Hanselmann
3736 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
3737 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3738 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
3739 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
3740 1a2eb2dc Michael Hanselmann
  """Performs a number of tests on a remote command.
3741 1a2eb2dc Michael Hanselmann

3742 1a2eb2dc Michael Hanselmann
  @type path: string
3743 1a2eb2dc Michael Hanselmann
  @param path: Directory containing remote commands
3744 1a2eb2dc Michael Hanselmann
  @type cmd: string
3745 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3746 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
3747 1a2eb2dc Michael Hanselmann

3748 1a2eb2dc Michael Hanselmann
  """
3749 1a2eb2dc Michael Hanselmann
  # Verify the directory first
3750 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
3751 1a2eb2dc Michael Hanselmann
  if status:
3752 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
3753 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
3754 1a2eb2dc Michael Hanselmann
3755 1a2eb2dc Michael Hanselmann
  if not status:
3756 1a2eb2dc Michael Hanselmann
    return (False, msg)
3757 1a2eb2dc Michael Hanselmann
3758 1a2eb2dc Michael Hanselmann
  # Check actual executable
3759 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
3760 1a2eb2dc Michael Hanselmann
3761 1a2eb2dc Michael Hanselmann
3762 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
3763 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3764 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3765 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3766 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
3767 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
3768 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
3769 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3770 1a2eb2dc Michael Hanselmann
  """Executes a remote command after performing strict tests.
3771 1a2eb2dc Michael Hanselmann

3772 1a2eb2dc Michael Hanselmann
  @type cmd: string
3773 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3774 1a2eb2dc Michael Hanselmann
  @rtype: string
3775 1a2eb2dc Michael Hanselmann
  @return: Command output
3776 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
3777 1a2eb2dc Michael Hanselmann

3778 1a2eb2dc Michael Hanselmann
  """
3779 1a2eb2dc Michael Hanselmann
  logging.info("Preparing to run remote command '%s'", cmd)
3780 1a2eb2dc Michael Hanselmann
3781 1a2eb2dc Michael Hanselmann
  if not _enabled:
3782 1a2eb2dc Michael Hanselmann
    _Fail("Remote commands disabled at configure time")
3783 1a2eb2dc Michael Hanselmann
3784 1a2eb2dc Michael Hanselmann
  lock = None
3785 1a2eb2dc Michael Hanselmann
  try:
3786 1a2eb2dc Michael Hanselmann
    cmdresult = None
3787 1a2eb2dc Michael Hanselmann
    try:
3788 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
3789 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3790 1a2eb2dc Michael Hanselmann
3791 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
3792 1a2eb2dc Michael Hanselmann
3793 1a2eb2dc Michael Hanselmann
      if status:
3794 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3795 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
3796 1a2eb2dc Michael Hanselmann
      else:
3797 1a2eb2dc Michael Hanselmann
        logging.error(value)
3798 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
3799 1a2eb2dc Michael Hanselmann
      # Keep original error in log
3800 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
3801 1a2eb2dc Michael Hanselmann
3802 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
3803 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
3804 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
3805 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
3806 1a2eb2dc Michael Hanselmann
3807 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
3808 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
3809 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
3810 1a2eb2dc Michael Hanselmann
      _Fail("Remote command '%s' failed: %s; output: %s",
3811 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
3812 1a2eb2dc Michael Hanselmann
    else:
3813 1a2eb2dc Michael Hanselmann
      return cmdresult.output
3814 1a2eb2dc Michael Hanselmann
  finally:
3815 1a2eb2dc Michael Hanselmann
    if lock is not None:
3816 1a2eb2dc Michael Hanselmann
      # Release lock at last
3817 1a2eb2dc Michael Hanselmann
      lock.Close()
3818 1a2eb2dc Michael Hanselmann
      lock = None
3819 1a2eb2dc Michael Hanselmann
3820 1a2eb2dc Michael Hanselmann
3821 99e222b1 Michael Hanselmann
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3822 99e222b1 Michael Hanselmann
  """Creates or removes the watcher pause file.
3823 99e222b1 Michael Hanselmann

3824 99e222b1 Michael Hanselmann
  @type until: None or number
3825 99e222b1 Michael Hanselmann
  @param until: Unix timestamp saying until when the watcher shouldn't run
3826 99e222b1 Michael Hanselmann

3827 99e222b1 Michael Hanselmann
  """
3828 99e222b1 Michael Hanselmann
  if until is None:
3829 99e222b1 Michael Hanselmann
    logging.info("Received request to no longer pause watcher")
3830 99e222b1 Michael Hanselmann
    utils.RemoveFile(_filename)
3831 99e222b1 Michael Hanselmann
  else:
3832 99e222b1 Michael Hanselmann
    logging.info("Received request to pause watcher until %s", until)
3833 99e222b1 Michael Hanselmann
3834 99e222b1 Michael Hanselmann
    if not ht.TNumber(until):
3835 99e222b1 Michael Hanselmann
      _Fail("Duration must be numeric")
3836 99e222b1 Michael Hanselmann
3837 99e222b1 Michael Hanselmann
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
3838 99e222b1 Michael Hanselmann
3839 99e222b1 Michael Hanselmann
3840 a8083063 Iustin Pop
class HooksRunner(object):
3841 a8083063 Iustin Pop
  """Hook runner.
3842 a8083063 Iustin Pop

3843 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3844 10c2650b Iustin Pop
  on the master side.
3845 a8083063 Iustin Pop

3846 a8083063 Iustin Pop
  """
3847 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3848 a8083063 Iustin Pop
    """Constructor for hooks runner.
3849 a8083063 Iustin Pop

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

3854 a8083063 Iustin Pop
    """
3855 a8083063 Iustin Pop
    if hooks_base_dir is None:
3856 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3857 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3858 fe267188 Iustin Pop
    # constant
3859 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3860 a8083063 Iustin Pop
3861 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3862 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3863 0fa481f5 Andrea Spadaccini

3864 0fa481f5 Andrea Spadaccini
    """
3865 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3866 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3867 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3868 0fa481f5 Andrea Spadaccini
    assert node == myself
3869 0fa481f5 Andrea Spadaccini
3870 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3871 0fa481f5 Andrea Spadaccini
3872 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3873 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3874 0fa481f5 Andrea Spadaccini
3875 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3876 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3877 a8083063 Iustin Pop

3878 10c2650b Iustin Pop
    @type hpath: str
3879 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3880 10c2650b Iustin Pop
        holds the scripts
3881 10c2650b Iustin Pop
    @type phase: str
3882 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3883 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3884 10c2650b Iustin Pop
    @type env: dict
3885 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3886 10c2650b Iustin Pop
    @rtype: list
3887 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3888 10c2650b Iustin Pop
      - script path
3889 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3890 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3891 10c2650b Iustin Pop
      - output of the script
3892 10c2650b Iustin Pop

3893 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3894 10c2650b Iustin Pop
        parameters
3895 a8083063 Iustin Pop

3896 a8083063 Iustin Pop
    """
3897 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3898 a8083063 Iustin Pop
      suffix = "pre"
3899 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3900 a8083063 Iustin Pop
      suffix = "post"
3901 a8083063 Iustin Pop
    else:
3902 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3903 3fb4f740 Iustin Pop
3904 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3905 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3906 6bb65e3a Guido Trotter
3907 6bb65e3a Guido Trotter
    results = []
3908 a9b7e346 Iustin Pop
3909 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3910 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3911 a9b7e346 Iustin Pop
      # warning at every operation
3912 a9b7e346 Iustin Pop
      return results
3913 a9b7e346 Iustin Pop
3914 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3915 a9b7e346 Iustin Pop
3916 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
3917 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3918 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3919 a8083063 Iustin Pop
        output = ""
3920 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3921 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3922 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3923 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3924 6bb65e3a Guido Trotter
        if runresult.failed:
3925 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3926 a8083063 Iustin Pop
        else:
3927 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3928 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3929 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3930 6bb65e3a Guido Trotter
3931 6bb65e3a Guido Trotter
    return results
3932 3f78eef2 Iustin Pop
3933 3f78eef2 Iustin Pop
3934 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3935 8d528b7c Iustin Pop
  """IAllocator runner.
3936 8d528b7c Iustin Pop

3937 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3938 8d528b7c Iustin Pop
  the master side.
3939 8d528b7c Iustin Pop

3940 8d528b7c Iustin Pop
  """
3941 7e950d31 Iustin Pop
  @staticmethod
3942 7e950d31 Iustin Pop
  def Run(name, idata):
3943 8d528b7c Iustin Pop
    """Run an iallocator script.
3944 8d528b7c Iustin Pop

3945 10c2650b Iustin Pop
    @type name: str
3946 10c2650b Iustin Pop
    @param name: the iallocator script name
3947 10c2650b Iustin Pop
    @type idata: str
3948 10c2650b Iustin Pop
    @param idata: the allocator input data
3949 10c2650b Iustin Pop

3950 10c2650b Iustin Pop
    @rtype: tuple
3951 87f5c298 Iustin Pop
    @return: two element tuple of:
3952 87f5c298 Iustin Pop
       - status
3953 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3954 8d528b7c Iustin Pop

3955 8d528b7c Iustin Pop
    """
3956 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3957 8d528b7c Iustin Pop
                                  os.path.isfile)
3958 8d528b7c Iustin Pop
    if alloc_script is None:
3959 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3960 8d528b7c Iustin Pop
3961 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3962 8d528b7c Iustin Pop
    try:
3963 8d528b7c Iustin Pop
      os.write(fd, idata)
3964 8d528b7c Iustin Pop
      os.close(fd)
3965 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3966 8d528b7c Iustin Pop
      if result.failed:
3967 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3968 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3969 8d528b7c Iustin Pop
    finally:
3970 8d528b7c Iustin Pop
      os.unlink(fin_name)
3971 8d528b7c Iustin Pop
3972 c26a6bd2 Iustin Pop
    return result.stdout
3973 8d528b7c Iustin Pop
3974 8d528b7c Iustin Pop
3975 3f78eef2 Iustin Pop
class DevCacheManager(object):
3976 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3977 3f78eef2 Iustin Pop

3978 3f78eef2 Iustin Pop
  """
3979 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3980 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
3981 3f78eef2 Iustin Pop
3982 3f78eef2 Iustin Pop
  @classmethod
3983 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3984 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3985 3f78eef2 Iustin Pop

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

3989 10c2650b Iustin Pop
    @type dev_path: str
3990 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3991 10c2650b Iustin Pop
    @rtype: str
3992 10c2650b Iustin Pop
    @return: the converted path name
3993 3f78eef2 Iustin Pop

3994 3f78eef2 Iustin Pop
    """
3995 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3996 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3997 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3998 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3999 3f78eef2 Iustin Pop
    return fpath
4000 3f78eef2 Iustin Pop
4001 3f78eef2 Iustin Pop
  @classmethod
4002 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4003 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
4004 3f78eef2 Iustin Pop

4005 10c2650b Iustin Pop
    @type dev_path: str
4006 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4007 10c2650b Iustin Pop
    @type owner: str
4008 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
4009 10c2650b Iustin Pop
    @type on_primary: bool
4010 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
4011 10c2650b Iustin Pop
        node nor not
4012 10c2650b Iustin Pop
    @type iv_name: str
4013 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
4014 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
4015 10c2650b Iustin Pop

4016 10c2650b Iustin Pop
    @rtype: None
4017 10c2650b Iustin Pop

4018 3f78eef2 Iustin Pop
    """
4019 cf5a8306 Iustin Pop
    if dev_path is None:
4020 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4021 cf5a8306 Iustin Pop
      return
4022 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4023 3f78eef2 Iustin Pop
    if on_primary:
4024 3f78eef2 Iustin Pop
      state = "primary"
4025 3f78eef2 Iustin Pop
    else:
4026 3f78eef2 Iustin Pop
      state = "secondary"
4027 3f78eef2 Iustin Pop
    if iv_name is None:
4028 3f78eef2 Iustin Pop
      iv_name = "not_visible"
4029 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4030 3f78eef2 Iustin Pop
    try:
4031 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
4032 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4033 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4034 3f78eef2 Iustin Pop
4035 3f78eef2 Iustin Pop
  @classmethod
4036 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
4037 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
4038 3f78eef2 Iustin Pop

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

4042 10c2650b Iustin Pop
    @type dev_path: str
4043 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4044 10c2650b Iustin Pop

4045 10c2650b Iustin Pop
    @rtype: None
4046 10c2650b Iustin Pop

4047 3f78eef2 Iustin Pop
    """
4048 cf5a8306 Iustin Pop
    if dev_path is None:
4049 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4050 cf5a8306 Iustin Pop
      return
4051 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4052 3f78eef2 Iustin Pop
    try:
4053 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
4054 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4055 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)