Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ b3589802

History | View | Annotate | Download (113.6 kB)

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

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

29 360b0dc2 Iustin Pop
"""
30 a8083063 Iustin Pop
31 b459a848 Andrea Spadaccini
# pylint: disable=E1103
32 6c881c52 Iustin Pop
33 6c881c52 Iustin Pop
# E1103: %s %r has no %r member (but some types could not be
34 6c881c52 Iustin Pop
# inferred), because the _TryOSFromDisk returns either (True, os_obj)
35 6c881c52 Iustin Pop
# or (False, "string") which confuses pylint
36 6c881c52 Iustin Pop
37 a8083063 Iustin Pop
38 a8083063 Iustin Pop
import os
39 a8083063 Iustin Pop
import os.path
40 a8083063 Iustin Pop
import shutil
41 a8083063 Iustin Pop
import time
42 a8083063 Iustin Pop
import stat
43 a8083063 Iustin Pop
import errno
44 a8083063 Iustin Pop
import re
45 b544cfe0 Iustin Pop
import random
46 18682bca Iustin Pop
import logging
47 3b9e6a30 Iustin Pop
import tempfile
48 12bce260 Michael Hanselmann
import zlib
49 12bce260 Michael Hanselmann
import base64
50 f81c4737 Michael Hanselmann
import signal
51 a8083063 Iustin Pop
52 a8083063 Iustin Pop
from ganeti import errors
53 a8083063 Iustin Pop
from ganeti import utils
54 a8083063 Iustin Pop
from ganeti import ssh
55 a8083063 Iustin Pop
from ganeti import hypervisor
56 a8083063 Iustin Pop
from ganeti import constants
57 a8083063 Iustin Pop
from ganeti import bdev
58 a8083063 Iustin Pop
from ganeti import objects
59 880478f8 Iustin Pop
from ganeti import ssconf
60 1651d116 Michael Hanselmann
from ganeti import serializer
61 a744b676 Manuel Franceschini
from ganeti import netutils
62 82b22e19 René Nussbaumer
from ganeti import runtime
63 0fa481f5 Andrea Spadaccini
from ganeti import mcpu
64 3ccd3243 Andrea Spadaccini
from ganeti import compat
65 710f30ec Michael Hanselmann
from ganeti import pathutils
66 cffbbae7 Michael Hanselmann
from ganeti import vcluster
67 a8083063 Iustin Pop
68 a8083063 Iustin Pop
69 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
70 714ea7ca Iustin Pop
_ALLOWED_CLEAN_DIRS = frozenset([
71 710f30ec Michael Hanselmann
  pathutils.DATA_DIR,
72 710f30ec Michael Hanselmann
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
73 710f30ec Michael Hanselmann
  pathutils.QUEUE_DIR,
74 710f30ec Michael Hanselmann
  pathutils.CRYPTO_KEYS_DIR,
75 714ea7ca Iustin Pop
  ])
76 f942a838 Michael Hanselmann
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
77 f942a838 Michael Hanselmann
_X509_KEY_FILE = "key"
78 f942a838 Michael Hanselmann
_X509_CERT_FILE = "cert"
79 1651d116 Michael Hanselmann
_IES_STATUS_FILE = "status"
80 1651d116 Michael Hanselmann
_IES_PID_FILE = "pid"
81 1651d116 Michael Hanselmann
_IES_CA_FILE = "ca"
82 13998ef2 Michael Hanselmann
83 0b5303da Iustin Pop
#: Valid LVS output line regex
84 a1f38213 Iustin Pop
_LVSLINE_REGEX = re.compile("^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
85 0b5303da Iustin Pop
86 702eff21 Andrea Spadaccini
# Actions for the master setup script
87 702eff21 Andrea Spadaccini
_MASTER_START = "start"
88 702eff21 Andrea Spadaccini
_MASTER_STOP = "stop"
89 702eff21 Andrea Spadaccini
90 13998ef2 Michael Hanselmann
91 2cc6781a Iustin Pop
class RPCFail(Exception):
92 2cc6781a Iustin Pop
  """Class denoting RPC failure.
93 2cc6781a Iustin Pop

94 2cc6781a Iustin Pop
  Its argument is the error message.
95 2cc6781a Iustin Pop

96 2cc6781a Iustin Pop
  """
97 2cc6781a Iustin Pop
98 13998ef2 Michael Hanselmann
99 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
100 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
101 2cc6781a Iustin Pop

102 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
103 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
104 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
105 2cc6781a Iustin Pop
  daemon.
106 2cc6781a Iustin Pop

107 2cc6781a Iustin Pop
  @type msg: string
108 2cc6781a Iustin Pop
  @param msg: the text of the exception
109 2cc6781a Iustin Pop
  @raise RPCFail
110 2cc6781a Iustin Pop

111 2cc6781a Iustin Pop
  """
112 2cc6781a Iustin Pop
  if args:
113 2cc6781a Iustin Pop
    msg = msg % args
114 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
115 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
116 afdc3985 Iustin Pop
      logging.exception(msg)
117 afdc3985 Iustin Pop
    else:
118 afdc3985 Iustin Pop
      logging.error(msg)
119 2cc6781a Iustin Pop
  raise RPCFail(msg)
120 2cc6781a Iustin Pop
121 2cc6781a Iustin Pop
122 c657dcc9 Michael Hanselmann
def _GetConfig():
123 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
124 10c2650b Iustin Pop

125 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
126 93384844 Iustin Pop
  @return: a SimpleStore instance
127 10c2650b Iustin Pop

128 10c2650b Iustin Pop
  """
129 93384844 Iustin Pop
  return ssconf.SimpleStore()
130 c657dcc9 Michael Hanselmann
131 c657dcc9 Michael Hanselmann
132 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
133 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
134 10c2650b Iustin Pop

135 10c2650b Iustin Pop
  @type cluster_name: str
136 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
137 10c2650b Iustin Pop
      by the SshRunner constructor
138 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
139 10c2650b Iustin Pop
  @return: an SshRunner instance
140 10c2650b Iustin Pop

141 10c2650b Iustin Pop
  """
142 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
143 c92b310a Michael Hanselmann
144 c92b310a Michael Hanselmann
145 12bce260 Michael Hanselmann
def _Decompress(data):
146 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
147 12bce260 Michael Hanselmann

148 12bce260 Michael Hanselmann
  @type data: list or tuple
149 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
150 12bce260 Michael Hanselmann
  @rtype: str
151 12bce260 Michael Hanselmann
  @return: Decompressed data
152 12bce260 Michael Hanselmann

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

168 10c2650b Iustin Pop
  @type path: str
169 10c2650b Iustin Pop
  @param path: the directory to clean
170 76ab5558 Michael Hanselmann
  @type exclude: list
171 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
172 10c2650b Iustin Pop
      to the empty list
173 76ab5558 Michael Hanselmann

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

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

200 360b0dc2 Iustin Pop
  """
201 b397a7d2 Iustin Pop
  allowed_files = set([
202 710f30ec Michael Hanselmann
    pathutils.CLUSTER_CONF_FILE,
203 b397a7d2 Iustin Pop
    constants.ETC_HOSTS,
204 710f30ec Michael Hanselmann
    pathutils.SSH_KNOWN_HOSTS_FILE,
205 710f30ec Michael Hanselmann
    pathutils.VNC_PASSWORD_FILE,
206 710f30ec Michael Hanselmann
    pathutils.RAPI_CERT_FILE,
207 710f30ec Michael Hanselmann
    pathutils.SPICE_CERT_FILE,
208 710f30ec Michael Hanselmann
    pathutils.SPICE_CACERT_FILE,
209 710f30ec Michael Hanselmann
    pathutils.RAPI_USERS_FILE,
210 710f30ec Michael Hanselmann
    pathutils.CONFD_HMAC_KEY,
211 710f30ec Michael Hanselmann
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
212 b397a7d2 Iustin Pop
    ])
213 b397a7d2 Iustin Pop
214 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
215 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
216 69ab2e12 Guido Trotter
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
217 b397a7d2 Iustin Pop
218 3439fd6b Michael Hanselmann
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
219 3439fd6b Michael Hanselmann
    "Allowed file storage paths should never be uploaded via RPC"
220 3439fd6b Michael Hanselmann
221 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
222 360b0dc2 Iustin Pop
223 360b0dc2 Iustin Pop
224 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
225 360b0dc2 Iustin Pop
226 360b0dc2 Iustin Pop
227 1bc59f76 Michael Hanselmann
def JobQueuePurge():
228 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
229 10c2650b Iustin Pop

230 c8457ce7 Iustin Pop
  @rtype: tuple
231 c8457ce7 Iustin Pop
  @return: True, None
232 24fc781f Michael Hanselmann

233 24fc781f Michael Hanselmann
  """
234 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
235 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
236 24fc781f Michael Hanselmann
237 24fc781f Michael Hanselmann
238 bd1e4562 Iustin Pop
def GetMasterInfo():
239 bd1e4562 Iustin Pop
  """Returns master information.
240 bd1e4562 Iustin Pop

241 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
242 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
243 bd1e4562 Iustin Pop

244 bd1e4562 Iustin Pop
  @rtype: tuple
245 909b3a0e Andrea Spadaccini
  @return: master_netdev, master_ip, master_name, primary_ip_family,
246 909b3a0e Andrea Spadaccini
    master_netmask
247 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
248 b1b6ea87 Iustin Pop

249 b1b6ea87 Iustin Pop
  """
250 b1b6ea87 Iustin Pop
  try:
251 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
252 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
253 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
254 5a8648eb Andrea Spadaccini
    master_netmask = cfg.GetMasterNetmask()
255 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
256 d8e0caa6 Manuel Franceschini
    primary_ip_family = cfg.GetPrimaryIPFamily()
257 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
258 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
259 909b3a0e Andrea Spadaccini
  return (master_netdev, master_ip, master_node, primary_ip_family,
260 5ae4945a Iustin Pop
          master_netmask)
261 b1b6ea87 Iustin Pop
262 b1b6ea87 Iustin Pop
263 0fa481f5 Andrea Spadaccini
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
264 0fa481f5 Andrea Spadaccini
  """Decorator that runs hooks before and after the decorated function.
265 0fa481f5 Andrea Spadaccini

266 0fa481f5 Andrea Spadaccini
  @type hook_opcode: string
267 0fa481f5 Andrea Spadaccini
  @param hook_opcode: opcode of the hook
268 0fa481f5 Andrea Spadaccini
  @type hooks_path: string
269 0fa481f5 Andrea Spadaccini
  @param hooks_path: path of the hooks
270 0fa481f5 Andrea Spadaccini
  @type env_builder_fn: function
271 0fa481f5 Andrea Spadaccini
  @param env_builder_fn: function that returns a dictionary containing the
272 3ccd3243 Andrea Spadaccini
    environment variables for the hooks. Will get all the parameters of the
273 3ccd3243 Andrea Spadaccini
    decorated function.
274 0fa481f5 Andrea Spadaccini
  @raise RPCFail: in case of pre-hook failure
275 0fa481f5 Andrea Spadaccini

276 0fa481f5 Andrea Spadaccini
  """
277 0fa481f5 Andrea Spadaccini
  def decorator(fn):
278 0fa481f5 Andrea Spadaccini
    def wrapper(*args, **kwargs):
279 0fa481f5 Andrea Spadaccini
      _, myself = ssconf.GetMasterAndMyself()
280 0fa481f5 Andrea Spadaccini
      nodes = ([myself], [myself])  # these hooks run locally
281 0fa481f5 Andrea Spadaccini
282 3ccd3243 Andrea Spadaccini
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
283 3ccd3243 Andrea Spadaccini
284 0fa481f5 Andrea Spadaccini
      cfg = _GetConfig()
285 0fa481f5 Andrea Spadaccini
      hr = HooksRunner()
286 0fa481f5 Andrea Spadaccini
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
287 3ccd3243 Andrea Spadaccini
                            None, env_fn, logging.warning, cfg.GetClusterName(),
288 3ccd3243 Andrea Spadaccini
                            cfg.GetMasterNode())
289 0fa481f5 Andrea Spadaccini
290 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
291 0fa481f5 Andrea Spadaccini
      result = fn(*args, **kwargs)
292 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_POST)
293 0fa481f5 Andrea Spadaccini
294 0fa481f5 Andrea Spadaccini
      return result
295 0fa481f5 Andrea Spadaccini
    return wrapper
296 0fa481f5 Andrea Spadaccini
  return decorator
297 0fa481f5 Andrea Spadaccini
298 0fa481f5 Andrea Spadaccini
299 57c7bc57 Andrea Spadaccini
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
300 2d88fdd3 Andrea Spadaccini
  """Builds environment variables for master IP hooks.
301 2d88fdd3 Andrea Spadaccini

302 3ccd3243 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
303 3ccd3243 Andrea Spadaccini
  @param master_params: network parameters of the master
304 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
305 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
306 57c7bc57 Andrea Spadaccini
    address setup script (unused, but necessary per the implementation of the
307 57c7bc57 Andrea Spadaccini
    _RunLocalHooks decorator)
308 3ccd3243 Andrea Spadaccini

309 2d88fdd3 Andrea Spadaccini
  """
310 57c7bc57 Andrea Spadaccini
  # pylint: disable=W0613
311 3ccd3243 Andrea Spadaccini
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
312 2d88fdd3 Andrea Spadaccini
  env = {
313 3ccd3243 Andrea Spadaccini
    "MASTER_NETDEV": master_params.netdev,
314 3ccd3243 Andrea Spadaccini
    "MASTER_IP": master_params.ip,
315 702eff21 Andrea Spadaccini
    "MASTER_NETMASK": str(master_params.netmask),
316 3ccd3243 Andrea Spadaccini
    "CLUSTER_IP_VERSION": str(ver),
317 2d88fdd3 Andrea Spadaccini
  }
318 2d88fdd3 Andrea Spadaccini
319 2d88fdd3 Andrea Spadaccini
  return env
320 2d88fdd3 Andrea Spadaccini
321 2d88fdd3 Andrea Spadaccini
322 702eff21 Andrea Spadaccini
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
323 702eff21 Andrea Spadaccini
  """Execute the master IP address setup script.
324 702eff21 Andrea Spadaccini

325 702eff21 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
326 702eff21 Andrea Spadaccini
  @param master_params: network parameters of the master
327 702eff21 Andrea Spadaccini
  @type action: string
328 702eff21 Andrea Spadaccini
  @param action: action to pass to the script. Must be one of
329 702eff21 Andrea Spadaccini
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
330 702eff21 Andrea Spadaccini
  @type use_external_mip_script: boolean
331 702eff21 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
332 702eff21 Andrea Spadaccini
    address setup script
333 702eff21 Andrea Spadaccini
  @raise backend.RPCFail: if there are errors during the execution of the
334 702eff21 Andrea Spadaccini
    script
335 702eff21 Andrea Spadaccini

336 702eff21 Andrea Spadaccini
  """
337 702eff21 Andrea Spadaccini
  env = _BuildMasterIpEnv(master_params)
338 702eff21 Andrea Spadaccini
339 702eff21 Andrea Spadaccini
  if use_external_mip_script:
340 710f30ec Michael Hanselmann
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
341 702eff21 Andrea Spadaccini
  else:
342 710f30ec Michael Hanselmann
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
343 702eff21 Andrea Spadaccini
344 702eff21 Andrea Spadaccini
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
345 702eff21 Andrea Spadaccini
346 702eff21 Andrea Spadaccini
  if result.failed:
347 702eff21 Andrea Spadaccini
    _Fail("Failed to %s the master IP. Script return value: %s" %
348 702eff21 Andrea Spadaccini
          (action, result.exit_code), log=True)
349 702eff21 Andrea Spadaccini
350 702eff21 Andrea Spadaccini
351 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
352 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
353 57c7bc57 Andrea Spadaccini
def ActivateMasterIp(master_params, use_external_mip_script):
354 fb460cf7 Andrea Spadaccini
  """Activate the IP address of the master daemon.
355 fb460cf7 Andrea Spadaccini

356 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
357 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
358 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
359 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
360 57c7bc57 Andrea Spadaccini
    address setup script
361 702eff21 Andrea Spadaccini
  @raise RPCFail: in case of errors during the IP startup
362 8da2bd43 Andrea Spadaccini

363 fb460cf7 Andrea Spadaccini
  """
364 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_START,
365 702eff21 Andrea Spadaccini
                        use_external_mip_script)
366 fb460cf7 Andrea Spadaccini
367 fb460cf7 Andrea Spadaccini
368 fb460cf7 Andrea Spadaccini
def StartMasterDaemons(no_voting):
369 a8083063 Iustin Pop
  """Activate local node as master node.
370 a8083063 Iustin Pop

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

373 3583908a Guido Trotter
  @type no_voting: boolean
374 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
375 fb460cf7 Andrea Spadaccini
      but still non-interactively
376 10c2650b Iustin Pop
  @rtype: None
377 a8083063 Iustin Pop

378 a8083063 Iustin Pop
  """
379 a8083063 Iustin Pop
380 fb460cf7 Andrea Spadaccini
  if no_voting:
381 fb460cf7 Andrea Spadaccini
    masterd_args = "--no-voting --yes-do-it"
382 fb460cf7 Andrea Spadaccini
  else:
383 fb460cf7 Andrea Spadaccini
    masterd_args = ""
384 f154a7a3 Michael Hanselmann
385 fb460cf7 Andrea Spadaccini
  env = {
386 fb460cf7 Andrea Spadaccini
    "EXTRA_MASTERD_ARGS": masterd_args,
387 fb460cf7 Andrea Spadaccini
    }
388 fb460cf7 Andrea Spadaccini
389 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
390 fb460cf7 Andrea Spadaccini
  if result.failed:
391 fb460cf7 Andrea Spadaccini
    msg = "Can't start Ganeti master: %s" % result.output
392 fb460cf7 Andrea Spadaccini
    logging.error(msg)
393 fb460cf7 Andrea Spadaccini
    _Fail(msg)
394 f154a7a3 Michael Hanselmann
395 fb460cf7 Andrea Spadaccini
396 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
397 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
398 57c7bc57 Andrea Spadaccini
def DeactivateMasterIp(master_params, use_external_mip_script):
399 fb460cf7 Andrea Spadaccini
  """Deactivate the master IP on this node.
400 a8083063 Iustin Pop

401 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
402 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
403 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
404 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
405 57c7bc57 Andrea Spadaccini
    address setup script
406 702eff21 Andrea Spadaccini
  @raise RPCFail: in case of errors during the IP turndown
407 96e0d5cc Andrea Spadaccini

408 a8083063 Iustin Pop
  """
409 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_STOP,
410 702eff21 Andrea Spadaccini
                        use_external_mip_script)
411 b1b6ea87 Iustin Pop
412 fb460cf7 Andrea Spadaccini
413 fb460cf7 Andrea Spadaccini
def StopMasterDaemons():
414 fb460cf7 Andrea Spadaccini
  """Stop the master daemons on this node.
415 fb460cf7 Andrea Spadaccini

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

418 fb460cf7 Andrea Spadaccini
  @rtype: None
419 fb460cf7 Andrea Spadaccini

420 fb460cf7 Andrea Spadaccini
  """
421 fb460cf7 Andrea Spadaccini
  # TODO: log and report back to the caller the error failures; we
422 fb460cf7 Andrea Spadaccini
  # need to decide in which case we fail the RPC for this
423 fb460cf7 Andrea Spadaccini
424 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
425 fb460cf7 Andrea Spadaccini
  if result.failed:
426 fb460cf7 Andrea Spadaccini
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
427 fb460cf7 Andrea Spadaccini
                  " and error %s",
428 fb460cf7 Andrea Spadaccini
                  result.cmd, result.exit_code, result.output)
429 a8083063 Iustin Pop
430 a8083063 Iustin Pop
431 41e079ce Andrea Spadaccini
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
432 5a8648eb Andrea Spadaccini
  """Change the netmask of the master IP.
433 5a8648eb Andrea Spadaccini

434 41e079ce Andrea Spadaccini
  @param old_netmask: the old value of the netmask
435 41e079ce Andrea Spadaccini
  @param netmask: the new value of the netmask
436 41e079ce Andrea Spadaccini
  @param master_ip: the master IP
437 41e079ce Andrea Spadaccini
  @param master_netdev: the master network device
438 41e079ce Andrea Spadaccini

439 5a8648eb Andrea Spadaccini
  """
440 5a8648eb Andrea Spadaccini
  if old_netmask == netmask:
441 5a8648eb Andrea Spadaccini
    return
442 5a8648eb Andrea Spadaccini
443 9e6014b9 Andrea Spadaccini
  if not netutils.IPAddress.Own(master_ip):
444 9e6014b9 Andrea Spadaccini
    _Fail("The master IP address is not up, not attempting to change its"
445 9e6014b9 Andrea Spadaccini
          " netmask")
446 9e6014b9 Andrea Spadaccini
447 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
448 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, netmask),
449 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
450 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
451 5a8648eb Andrea Spadaccini
  if result.failed:
452 9e6014b9 Andrea Spadaccini
    _Fail("Could not set the new netmask on the master IP address")
453 5a8648eb Andrea Spadaccini
454 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
455 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, old_netmask),
456 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
457 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
458 5a8648eb Andrea Spadaccini
  if result.failed:
459 9e6014b9 Andrea Spadaccini
    _Fail("Could not bring down the master IP address with the old netmask")
460 5a8648eb Andrea Spadaccini
461 5a8648eb Andrea Spadaccini
462 19ddc57a René Nussbaumer
def EtcHostsModify(mode, host, ip):
463 19ddc57a René Nussbaumer
  """Modify a host entry in /etc/hosts.
464 19ddc57a René Nussbaumer

465 19ddc57a René Nussbaumer
  @param mode: The mode to operate. Either add or remove entry
466 19ddc57a René Nussbaumer
  @param host: The host to operate on
467 19ddc57a René Nussbaumer
  @param ip: The ip associated with the entry
468 19ddc57a René Nussbaumer

469 19ddc57a René Nussbaumer
  """
470 19ddc57a René Nussbaumer
  if mode == constants.ETC_HOSTS_ADD:
471 19ddc57a René Nussbaumer
    if not ip:
472 19ddc57a René Nussbaumer
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
473 19ddc57a René Nussbaumer
              " present")
474 19ddc57a René Nussbaumer
    utils.AddHostToEtcHosts(host, ip)
475 19ddc57a René Nussbaumer
  elif mode == constants.ETC_HOSTS_REMOVE:
476 19ddc57a René Nussbaumer
    if ip:
477 19ddc57a René Nussbaumer
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
478 19ddc57a René Nussbaumer
              " parameter is present")
479 19ddc57a René Nussbaumer
    utils.RemoveHostFromEtcHosts(host)
480 19ddc57a René Nussbaumer
  else:
481 19ddc57a René Nussbaumer
    RPCFail("Mode not supported")
482 19ddc57a René Nussbaumer
483 19ddc57a René Nussbaumer
484 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
485 10c2650b Iustin Pop
  """Cleans up and remove the current node.
486 10c2650b Iustin Pop

487 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
488 10c2650b Iustin Pop
  from the cluster.
489 10c2650b Iustin Pop

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

494 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
495 b989b9d9 Ken Wehr

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

533 78519c10 Michael Hanselmann
  """
534 78519c10 Michael Hanselmann
  # TODO: GetVGInfo supports returning information for multiple VGs at once
535 78519c10 Michael Hanselmann
  vginfo = bdev.LogicalVolume.GetVGInfo([name])
536 78519c10 Michael Hanselmann
  if vginfo:
537 78519c10 Michael Hanselmann
    vg_free = int(round(vginfo[0][0], 0))
538 78519c10 Michael Hanselmann
    vg_size = int(round(vginfo[0][1], 0))
539 78519c10 Michael Hanselmann
  else:
540 78519c10 Michael Hanselmann
    vg_free = None
541 78519c10 Michael Hanselmann
    vg_size = None
542 78519c10 Michael Hanselmann
543 78519c10 Michael Hanselmann
  return {
544 78519c10 Michael Hanselmann
    "name": name,
545 1e89a135 Michael Hanselmann
    "vg_free": vg_free,
546 1e89a135 Michael Hanselmann
    "vg_size": vg_size,
547 78519c10 Michael Hanselmann
    }
548 78519c10 Michael Hanselmann
549 78519c10 Michael Hanselmann
550 78519c10 Michael Hanselmann
def _GetHvInfo(name):
551 78519c10 Michael Hanselmann
  """Retrieves node information from a hypervisor.
552 78519c10 Michael Hanselmann

553 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
554 78519c10 Michael Hanselmann

555 78519c10 Michael Hanselmann
    - vg_size is the size of the configured volume group in MiB
556 78519c10 Michael Hanselmann
    - vg_free is the free size of the volume group in MiB
557 78519c10 Michael Hanselmann
    - memory_dom0 is the memory allocated for domain0 in MiB
558 78519c10 Michael Hanselmann
    - memory_free is the currently available (free) ram in MiB
559 78519c10 Michael Hanselmann
    - memory_total is the total number of ram in MiB
560 78519c10 Michael Hanselmann
    - hv_version: the hypervisor version, if available
561 78519c10 Michael Hanselmann

562 78519c10 Michael Hanselmann
  """
563 78519c10 Michael Hanselmann
  return hypervisor.GetHypervisor(name).GetNodeInfo()
564 78519c10 Michael Hanselmann
565 78519c10 Michael Hanselmann
566 78519c10 Michael Hanselmann
def _GetNamedNodeInfo(names, fn):
567 78519c10 Michael Hanselmann
  """Calls C{fn} for all names in C{names} and returns a dictionary.
568 78519c10 Michael Hanselmann

569 78519c10 Michael Hanselmann
  @rtype: None or dict
570 78519c10 Michael Hanselmann

571 78519c10 Michael Hanselmann
  """
572 78519c10 Michael Hanselmann
  if names is None:
573 78519c10 Michael Hanselmann
    return None
574 78519c10 Michael Hanselmann
  else:
575 ff3be305 Michael Hanselmann
    return map(fn, names)
576 78519c10 Michael Hanselmann
577 78519c10 Michael Hanselmann
578 78519c10 Michael Hanselmann
def GetNodeInfo(vg_names, hv_names):
579 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
580 a8083063 Iustin Pop

581 78519c10 Michael Hanselmann
  @type vg_names: list of string
582 78519c10 Michael Hanselmann
  @param vg_names: Names of the volume groups to ask for disk space information
583 78519c10 Michael Hanselmann
  @type hv_names: list of string
584 78519c10 Michael Hanselmann
  @param hv_names: Names of the hypervisors to ask for node information
585 78519c10 Michael Hanselmann
  @rtype: tuple; (string, None/dict, None/dict)
586 78519c10 Michael Hanselmann
  @return: Tuple containing boot ID, volume group information and hypervisor
587 78519c10 Michael Hanselmann
    information
588 a8083063 Iustin Pop

589 098c0958 Michael Hanselmann
  """
590 78519c10 Michael Hanselmann
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
591 78519c10 Michael Hanselmann
  vg_info = _GetNamedNodeInfo(vg_names, _GetVgInfo)
592 78519c10 Michael Hanselmann
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
593 78519c10 Michael Hanselmann
594 78519c10 Michael Hanselmann
  return (bootid, vg_info, hv_info)
595 a8083063 Iustin Pop
596 a8083063 Iustin Pop
597 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
598 a8083063 Iustin Pop
  """Verify the status of the local node.
599 a8083063 Iustin Pop

600 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
601 e69d05fd Iustin Pop
  local node.
602 e69d05fd Iustin Pop

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

606 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
607 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
608 e69d05fd Iustin Pop
  report).
609 a8083063 Iustin Pop

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

614 e69d05fd Iustin Pop
  @type what: C{dict}
615 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
616 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
617 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
618 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
619 e69d05fd Iustin Pop
        connectivity with
620 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
621 10c2650b Iustin Pop
  @rtype: dict
622 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
623 10c2650b Iustin Pop
      values representing the result of the checks
624 a8083063 Iustin Pop

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

806 2be7273c Apollon Oikonomopoulos
  @type devices: list
807 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
808 2be7273c Apollon Oikonomopoulos
  @rtype: dict
809 2be7273c Apollon Oikonomopoulos
  @return:
810 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
811 2be7273c Apollon Oikonomopoulos
    size in MiB.
812 2be7273c Apollon Oikonomopoulos

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

815 2be7273c Apollon Oikonomopoulos
  """
816 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
817 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
818 2be7273c Apollon Oikonomopoulos
819 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
820 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
821 2be7273c Apollon Oikonomopoulos
      continue
822 2be7273c Apollon Oikonomopoulos
823 2be7273c Apollon Oikonomopoulos
    try:
824 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
825 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
826 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
827 2be7273c Apollon Oikonomopoulos
      continue
828 2be7273c Apollon Oikonomopoulos
829 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
830 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
831 2be7273c Apollon Oikonomopoulos
      if result.failed:
832 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
833 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
834 2be7273c Apollon Oikonomopoulos
        continue
835 2be7273c Apollon Oikonomopoulos
836 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
837 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
838 2be7273c Apollon Oikonomopoulos
  return blockdevs
839 2be7273c Apollon Oikonomopoulos
840 2be7273c Apollon Oikonomopoulos
841 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
842 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
843 a8083063 Iustin Pop

844 84d7e26b Dmitry Chernyak
  @type vg_names: list
845 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
846 397693d3 Iustin Pop
      empty for all volume groups
847 10c2650b Iustin Pop
  @rtype: dict
848 10c2650b Iustin Pop
  @return:
849 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
850 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
851 10c2650b Iustin Pop

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

854 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
855 10c2650b Iustin Pop
      details.
856 a8083063 Iustin Pop

857 a8083063 Iustin Pop
  """
858 cb2037a2 Iustin Pop
  lvs = {}
859 d0c8c01d Iustin Pop
  sep = "|"
860 397693d3 Iustin Pop
  if not vg_names:
861 397693d3 Iustin Pop
    vg_names = []
862 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
863 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
864 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
865 a8083063 Iustin Pop
  if result.failed:
866 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
867 cb2037a2 Iustin Pop
868 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
869 df4c2628 Iustin Pop
    line = line.strip()
870 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
871 df4c2628 Iustin Pop
    if not match:
872 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
873 df4c2628 Iustin Pop
      continue
874 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
875 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
876 d0c8c01d Iustin Pop
    online = attr[5] == "o"
877 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
878 33f2a81a Iustin Pop
    if virtual:
879 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
880 33f2a81a Iustin Pop
      # don't really hold data
881 33f2a81a Iustin Pop
      continue
882 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
883 cb2037a2 Iustin Pop
884 cb2037a2 Iustin Pop
  return lvs
885 a8083063 Iustin Pop
886 a8083063 Iustin Pop
887 a8083063 Iustin Pop
def ListVolumeGroups():
888 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
889 a8083063 Iustin Pop

890 10c2650b Iustin Pop
  @rtype: dict
891 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
892 10c2650b Iustin Pop
      size of the volume
893 a8083063 Iustin Pop

894 a8083063 Iustin Pop
  """
895 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
896 a8083063 Iustin Pop
897 a8083063 Iustin Pop
898 dcb93971 Michael Hanselmann
def NodeVolumes():
899 dcb93971 Michael Hanselmann
  """List all volumes on this node.
900 dcb93971 Michael Hanselmann

901 10c2650b Iustin Pop
  @rtype: list
902 10c2650b Iustin Pop
  @return:
903 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
904 10c2650b Iustin Pop
      - name: the logical volume name,
905 10c2650b Iustin Pop
      - size: the size of the logical volume
906 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
907 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
908 10c2650b Iustin Pop

909 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
910 10c2650b Iustin Pop
    error.
911 10c2650b Iustin Pop

912 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
913 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
914 10c2650b Iustin Pop
    multiple times.
915 10c2650b Iustin Pop

916 dcb93971 Michael Hanselmann
  """
917 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
918 dcb93971 Michael Hanselmann
                         "--separator=|",
919 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
920 dcb93971 Michael Hanselmann
  if result.failed:
921 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
922 10bfe6cb Iustin Pop
          result.output)
923 dcb93971 Michael Hanselmann
924 dcb93971 Michael Hanselmann
  def parse_dev(dev):
925 d0c8c01d Iustin Pop
    return dev.split("(")[0]
926 89e5ab02 Iustin Pop
927 89e5ab02 Iustin Pop
  def handle_dev(dev):
928 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
929 dcb93971 Michael Hanselmann
930 dcb93971 Michael Hanselmann
  def map_line(line):
931 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
932 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
933 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
934 89e5ab02 Iustin Pop
935 89e5ab02 Iustin Pop
  all_devs = []
936 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
937 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
938 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
939 89e5ab02 Iustin Pop
    else:
940 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
941 89e5ab02 Iustin Pop
  return all_devs
942 dcb93971 Michael Hanselmann
943 dcb93971 Michael Hanselmann
944 a8083063 Iustin Pop
def BridgesExist(bridges_list):
945 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
946 a8083063 Iustin Pop

947 b1206984 Iustin Pop
  @rtype: boolean
948 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
949 a8083063 Iustin Pop

950 a8083063 Iustin Pop
  """
951 35c0c8da Iustin Pop
  missing = []
952 a8083063 Iustin Pop
  for bridge in bridges_list:
953 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
954 35c0c8da Iustin Pop
      missing.append(bridge)
955 a8083063 Iustin Pop
956 35c0c8da Iustin Pop
  if missing:
957 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
958 35c0c8da Iustin Pop
959 a8083063 Iustin Pop
960 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
961 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
962 a8083063 Iustin Pop

963 e69d05fd Iustin Pop
  @type hypervisor_list: list
964 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
965 e69d05fd Iustin Pop

966 e69d05fd Iustin Pop
  @rtype: list
967 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
968 10c2650b Iustin Pop
    - instance1.example.com
969 10c2650b Iustin Pop
    - instance2.example.com
970 a8083063 Iustin Pop

971 098c0958 Michael Hanselmann
  """
972 e69d05fd Iustin Pop
  results = []
973 e69d05fd Iustin Pop
  for hname in hypervisor_list:
974 e69d05fd Iustin Pop
    try:
975 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
976 e69d05fd Iustin Pop
      results.extend(names)
977 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
978 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
979 aca13712 Iustin Pop
            hname, err, exc=True)
980 a8083063 Iustin Pop
981 e69d05fd Iustin Pop
  return results
982 a8083063 Iustin Pop
983 a8083063 Iustin Pop
984 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
985 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
986 a8083063 Iustin Pop

987 e69d05fd Iustin Pop
  @type instance: string
988 e69d05fd Iustin Pop
  @param instance: the instance name
989 e69d05fd Iustin Pop
  @type hname: string
990 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
991 a8083063 Iustin Pop

992 e69d05fd Iustin Pop
  @rtype: dict
993 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
994 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
995 e69d05fd Iustin Pop
      - state: xen state of instance (string)
996 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
997 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
998 a8083063 Iustin Pop

999 098c0958 Michael Hanselmann
  """
1000 a8083063 Iustin Pop
  output = {}
1001 a8083063 Iustin Pop
1002 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1003 a8083063 Iustin Pop
  if iinfo is not None:
1004 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1005 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1006 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1007 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1008 a8083063 Iustin Pop
1009 c26a6bd2 Iustin Pop
  return output
1010 a8083063 Iustin Pop
1011 a8083063 Iustin Pop
1012 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1013 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
1014 56e7640c Iustin Pop

1015 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1016 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1017 56e7640c Iustin Pop

1018 56e7640c Iustin Pop
  @rtype: tuple
1019 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1020 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1021 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1022 56e7640c Iustin Pop

1023 56e7640c Iustin Pop
  """
1024 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1025 afdc3985 Iustin Pop
  iname = instance.name
1026 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
1027 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1028 56e7640c Iustin Pop
1029 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1030 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1031 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1032 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1033 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1034 56e7640c Iustin Pop
1035 56e7640c Iustin Pop
1036 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
1037 a8083063 Iustin Pop
  """Gather data about all instances.
1038 a8083063 Iustin Pop

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

1043 e69d05fd Iustin Pop
  @type hypervisor_list: list
1044 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1045 e69d05fd Iustin Pop

1046 955db481 Guido Trotter
  @rtype: dict
1047 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1048 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1049 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1050 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1051 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1052 a8083063 Iustin Pop

1053 098c0958 Michael Hanselmann
  """
1054 a8083063 Iustin Pop
  output = {}
1055 a8083063 Iustin Pop
1056 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1057 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1058 e69d05fd Iustin Pop
    if iinfo:
1059 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1060 f23b5ae8 Iustin Pop
        value = {
1061 d0c8c01d Iustin Pop
          "memory": memory,
1062 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1063 d0c8c01d Iustin Pop
          "state": state,
1064 d0c8c01d Iustin Pop
          "time": times,
1065 e69d05fd Iustin Pop
          }
1066 b33b6f55 Iustin Pop
        if name in output:
1067 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1068 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1069 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1070 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1071 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1072 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1073 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1074 f23b5ae8 Iustin Pop
        output[name] = value
1075 a8083063 Iustin Pop
1076 c26a6bd2 Iustin Pop
  return output
1077 a8083063 Iustin Pop
1078 a8083063 Iustin Pop
1079 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1080 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1081 81a3406c Iustin Pop

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

1085 81a3406c Iustin Pop
  @type kind: string
1086 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1087 81a3406c Iustin Pop
  @type os_name: string
1088 81a3406c Iustin Pop
  @param os_name: the os name
1089 81a3406c Iustin Pop
  @type instance: string
1090 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1091 6aa7a354 Iustin Pop
  @type component: string or None
1092 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1093 6aa7a354 Iustin Pop
      transferred
1094 81a3406c Iustin Pop

1095 81a3406c Iustin Pop
  """
1096 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1097 6aa7a354 Iustin Pop
  if component:
1098 6aa7a354 Iustin Pop
    assert "/" not in component
1099 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1100 6aa7a354 Iustin Pop
  else:
1101 6aa7a354 Iustin Pop
    c_msg = ""
1102 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1103 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1104 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1105 81a3406c Iustin Pop
1106 81a3406c Iustin Pop
1107 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1108 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1109 a8083063 Iustin Pop

1110 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1111 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1112 e557bae9 Guido Trotter
  @type reinstall: boolean
1113 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1114 4a0e011f Iustin Pop
  @type debug: integer
1115 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1116 c26a6bd2 Iustin Pop
  @rtype: None
1117 a8083063 Iustin Pop

1118 a8083063 Iustin Pop
  """
1119 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1120 255dcebd Iustin Pop
1121 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1122 e557bae9 Guido Trotter
  if reinstall:
1123 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1124 a8083063 Iustin Pop
1125 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1126 decd5f45 Iustin Pop
1127 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1128 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1129 decd5f45 Iustin Pop
  if result.failed:
1130 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1131 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1132 18682bca Iustin Pop
                  result.output)
1133 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1134 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1135 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1136 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1137 decd5f45 Iustin Pop
1138 decd5f45 Iustin Pop
1139 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1140 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1141 decd5f45 Iustin Pop

1142 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1143 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1144 d15a9ad3 Guido Trotter
  @type old_name: string
1145 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1146 4a0e011f Iustin Pop
  @type debug: integer
1147 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1148 10c2650b Iustin Pop
  @rtype: boolean
1149 10c2650b Iustin Pop
  @return: the success of the operation
1150 decd5f45 Iustin Pop

1151 decd5f45 Iustin Pop
  """
1152 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1153 decd5f45 Iustin Pop
1154 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1155 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1156 decd5f45 Iustin Pop
1157 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1158 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1159 a8083063 Iustin Pop
1160 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1161 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1162 a8083063 Iustin Pop
1163 a8083063 Iustin Pop
  if result.failed:
1164 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1165 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1166 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1167 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1168 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1169 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1170 a8083063 Iustin Pop
1171 a8083063 Iustin Pop
1172 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
1173 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.DISK_LINKS_DIR, "%s%s%d" %
1174 3536c792 Iustin Pop
                        (instance_name, constants.DISK_SEPARATOR, idx))
1175 5282084b Iustin Pop
1176 5282084b Iustin Pop
1177 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1178 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1179 9332fd8a Iustin Pop

1180 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1181 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1182 9332fd8a Iustin Pop

1183 9332fd8a Iustin Pop

1184 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1185 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1186 5282084b Iustin Pop
  @param idx: the disk index
1187 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1188 9332fd8a Iustin Pop

1189 9332fd8a Iustin Pop
  """
1190 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1191 9332fd8a Iustin Pop
  try:
1192 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1193 5282084b Iustin Pop
  except OSError, err:
1194 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1195 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1196 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1197 9332fd8a Iustin Pop
        os.remove(link_name)
1198 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1199 9332fd8a Iustin Pop
    else:
1200 9332fd8a Iustin Pop
      raise
1201 9332fd8a Iustin Pop
1202 9332fd8a Iustin Pop
  return link_name
1203 9332fd8a Iustin Pop
1204 9332fd8a Iustin Pop
1205 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1206 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1207 3c9c571d Iustin Pop

1208 3c9c571d Iustin Pop
  """
1209 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1210 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1211 5282084b Iustin Pop
    if os.path.islink(link_name):
1212 3c9c571d Iustin Pop
      try:
1213 03dfa658 Iustin Pop
        os.remove(link_name)
1214 03dfa658 Iustin Pop
      except OSError:
1215 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1216 3c9c571d Iustin Pop
1217 3c9c571d Iustin Pop
1218 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1219 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1220 a8083063 Iustin Pop

1221 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1222 a8083063 Iustin Pop
  devices must be already assembled.
1223 a8083063 Iustin Pop

1224 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1225 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1226 069cfbf1 Iustin Pop
  @rtype: list
1227 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1228 10c2650b Iustin Pop

1229 a8083063 Iustin Pop
  """
1230 a8083063 Iustin Pop
  block_devices = []
1231 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1232 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1233 a8083063 Iustin Pop
    if device is None:
1234 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1235 a8083063 Iustin Pop
                                    str(disk))
1236 a8083063 Iustin Pop
    device.Open()
1237 9332fd8a Iustin Pop
    try:
1238 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1239 9332fd8a Iustin Pop
    except OSError, e:
1240 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1241 9332fd8a Iustin Pop
                                    e.strerror)
1242 9332fd8a Iustin Pop
1243 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1244 9332fd8a Iustin Pop
1245 a8083063 Iustin Pop
  return block_devices
1246 a8083063 Iustin Pop
1247 a8083063 Iustin Pop
1248 323f9095 Stephen Shirley
def StartInstance(instance, startup_paused):
1249 a8083063 Iustin Pop
  """Start an instance.
1250 a8083063 Iustin Pop

1251 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1252 e69d05fd Iustin Pop
  @param instance: the instance object
1253 323f9095 Stephen Shirley
  @type startup_paused: bool
1254 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1255 c26a6bd2 Iustin Pop
  @rtype: None
1256 a8083063 Iustin Pop

1257 098c0958 Michael Hanselmann
  """
1258 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1259 a8083063 Iustin Pop
1260 a8083063 Iustin Pop
  if instance.name in running_instances:
1261 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1262 c26a6bd2 Iustin Pop
    return
1263 a8083063 Iustin Pop
1264 a8083063 Iustin Pop
  try:
1265 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1266 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1267 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1268 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1269 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1270 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1271 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1272 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1273 a8083063 Iustin Pop
1274 a8083063 Iustin Pop
1275 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1276 a8083063 Iustin Pop
  """Shut an instance down.
1277 a8083063 Iustin Pop

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

1280 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1281 e69d05fd Iustin Pop
  @param instance: the instance object
1282 6263189c Guido Trotter
  @type timeout: integer
1283 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1284 c26a6bd2 Iustin Pop
  @rtype: None
1285 a8083063 Iustin Pop

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

1347 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1348 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1349 10c2650b Iustin Pop
  @type reboot_type: str
1350 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1351 10c2650b Iustin Pop
    constants:
1352 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1353 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1354 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1355 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1356 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1357 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1358 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1359 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1360 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1361 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1362 c26a6bd2 Iustin Pop
  @rtype: None
1363 007a2f3e Alexander Schreiber

1364 007a2f3e Alexander Schreiber
  """
1365 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1366 007a2f3e Alexander Schreiber
1367 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1368 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1369 007a2f3e Alexander Schreiber
1370 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1371 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1372 007a2f3e Alexander Schreiber
    try:
1373 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1374 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1375 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1376 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1377 007a2f3e Alexander Schreiber
    try:
1378 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1379 82bc21e2 Stephen Shirley
      return StartInstance(instance, False)
1380 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1381 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1382 007a2f3e Alexander Schreiber
  else:
1383 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1384 007a2f3e Alexander Schreiber
1385 007a2f3e Alexander Schreiber
1386 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1387 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1388 ebe466d8 Guido Trotter

1389 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1390 ebe466d8 Guido Trotter
  @param instance: the instance object
1391 ebe466d8 Guido Trotter
  @type memory: int
1392 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1393 ebe466d8 Guido Trotter
  @rtype: None
1394 ebe466d8 Guido Trotter

1395 ebe466d8 Guido Trotter
  """
1396 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1397 ebe466d8 Guido Trotter
  running = hyper.ListInstances()
1398 ebe466d8 Guido Trotter
  if instance.name not in running:
1399 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1400 ebe466d8 Guido Trotter
    return
1401 ebe466d8 Guido Trotter
  try:
1402 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1403 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1404 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1405 ebe466d8 Guido Trotter
1406 ebe466d8 Guido Trotter
1407 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1408 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1409 6906a9d8 Guido Trotter

1410 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1411 6906a9d8 Guido Trotter
  @param instance: the instance definition
1412 6906a9d8 Guido Trotter

1413 6906a9d8 Guido Trotter
  """
1414 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1415 cd42d0ad Guido Trotter
  try:
1416 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1417 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1418 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1419 c26a6bd2 Iustin Pop
  return info
1420 6906a9d8 Guido Trotter
1421 6906a9d8 Guido Trotter
1422 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1423 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1424 6906a9d8 Guido Trotter

1425 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1426 6906a9d8 Guido Trotter
  @param instance: the instance definition
1427 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1428 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1429 6906a9d8 Guido Trotter
  @type target: string
1430 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1431 6906a9d8 Guido Trotter

1432 6906a9d8 Guido Trotter
  """
1433 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1434 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1435 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1436 77fcff4a Apollon Oikonomopoulos
    # in any way
1437 77fcff4a Apollon Oikonomopoulos
    try:
1438 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1439 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1440 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1441 77fcff4a Apollon Oikonomopoulos
1442 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1443 cd42d0ad Guido Trotter
  try:
1444 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1445 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1446 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1447 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1448 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1449 6906a9d8 Guido Trotter
1450 6906a9d8 Guido Trotter
1451 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1452 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1453 6906a9d8 Guido Trotter

1454 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1455 6906a9d8 Guido Trotter
  @param instance: the instance definition
1456 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1457 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1458 6906a9d8 Guido Trotter
  @type success: boolean
1459 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1460 6906a9d8 Guido Trotter

1461 6906a9d8 Guido Trotter
  """
1462 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1463 cd42d0ad Guido Trotter
  try:
1464 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1465 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1466 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1467 6906a9d8 Guido Trotter
1468 6906a9d8 Guido Trotter
1469 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1470 2a10865c Iustin Pop
  """Migrates an instance to another node.
1471 2a10865c Iustin Pop

1472 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1473 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1474 9f0e6b37 Iustin Pop
  @type target: string
1475 9f0e6b37 Iustin Pop
  @param target: the target node name
1476 9f0e6b37 Iustin Pop
  @type live: boolean
1477 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1478 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1479 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1480 9f0e6b37 Iustin Pop

1481 2a10865c Iustin Pop
  """
1482 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1483 2a10865c Iustin Pop
1484 2a10865c Iustin Pop
  try:
1485 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1486 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1487 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1488 2a10865c Iustin Pop
1489 2a10865c Iustin Pop
1490 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1491 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1492 6a1434d7 Andrea Spadaccini

1493 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1494 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1495 6a1434d7 Andrea Spadaccini
  @type success: bool
1496 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1497 6a1434d7 Andrea Spadaccini
  @type live: bool
1498 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1499 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1500 6a1434d7 Andrea Spadaccini

1501 6a1434d7 Andrea Spadaccini
  """
1502 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1503 6a1434d7 Andrea Spadaccini
1504 6a1434d7 Andrea Spadaccini
  try:
1505 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1506 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1507 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1508 6a1434d7 Andrea Spadaccini
          exc=True)
1509 6a1434d7 Andrea Spadaccini
1510 6a1434d7 Andrea Spadaccini
1511 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1512 6a1434d7 Andrea Spadaccini
  """Get the migration status
1513 6a1434d7 Andrea Spadaccini

1514 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1515 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1516 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1517 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1518 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1519 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1520 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1521 6a1434d7 Andrea Spadaccini

1522 6a1434d7 Andrea Spadaccini
  """
1523 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1524 6a1434d7 Andrea Spadaccini
  try:
1525 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1526 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1527 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1528 6a1434d7 Andrea Spadaccini
1529 6a1434d7 Andrea Spadaccini
1530 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1531 a8083063 Iustin Pop
  """Creates a block device for an instance.
1532 a8083063 Iustin Pop

1533 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1534 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1535 b1206984 Iustin Pop
  @type size: int
1536 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1537 b1206984 Iustin Pop
  @type owner: str
1538 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1539 b1206984 Iustin Pop
      used for device cache data
1540 b1206984 Iustin Pop
  @type on_primary: boolean
1541 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1542 b1206984 Iustin Pop
  @type info: string
1543 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1544 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1545 b1206984 Iustin Pop

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

1550 a8083063 Iustin Pop
  """
1551 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
1552 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
1553 a8083063 Iustin Pop
  clist = []
1554 a8083063 Iustin Pop
  if disk.children:
1555 a8083063 Iustin Pop
    for child in disk.children:
1556 1063abd1 Iustin Pop
      try:
1557 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1558 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1559 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1560 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1561 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1562 a8083063 Iustin Pop
        # be assembled
1563 1063abd1 Iustin Pop
        try:
1564 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
1565 1063abd1 Iustin Pop
          crdev.Open()
1566 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1567 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1568 a8083063 Iustin Pop
      clist.append(crdev)
1569 a8083063 Iustin Pop
1570 dab69e97 Iustin Pop
  try:
1571 94dcbdb0 Andrea Spadaccini
    device = bdev.Create(disk, clist)
1572 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1573 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1574 6c626518 Iustin Pop
1575 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1576 1063abd1 Iustin Pop
    try:
1577 1063abd1 Iustin Pop
      device.Assemble()
1578 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1579 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1580 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1581 1063abd1 Iustin Pop
      try:
1582 1063abd1 Iustin Pop
        device.Open(force=True)
1583 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1584 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1585 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1586 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1587 a0c3fea1 Michael Hanselmann
1588 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1589 a0c3fea1 Michael Hanselmann
1590 c26a6bd2 Iustin Pop
  return device.unique_id
1591 a8083063 Iustin Pop
1592 a8083063 Iustin Pop
1593 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1594 69dd363f René Nussbaumer
  """This function actually wipes the device.
1595 69dd363f René Nussbaumer

1596 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1597 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1598 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1599 69dd363f René Nussbaumer

1600 69dd363f René Nussbaumer
  """
1601 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
1602 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
1603 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
1604 0188611b Michael Hanselmann
  block_size = 1024 * 1024
1605 0188611b Michael Hanselmann
1606 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1607 0188611b Michael Hanselmann
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1608 da63bb4e René Nussbaumer
         "count=%d" % size]
1609 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1610 69dd363f René Nussbaumer
1611 69dd363f René Nussbaumer
  if result.failed:
1612 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1613 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1614 69dd363f René Nussbaumer
1615 69dd363f René Nussbaumer
1616 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1617 69dd363f René Nussbaumer
  """Wipes a block device.
1618 69dd363f René Nussbaumer

1619 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1620 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1621 da63bb4e René Nussbaumer
  @type offset: int
1622 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1623 da63bb4e René Nussbaumer
  @type size: int
1624 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1625 69dd363f René Nussbaumer

1626 69dd363f René Nussbaumer
  """
1627 69dd363f René Nussbaumer
  try:
1628 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1629 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1630 da63bb4e René Nussbaumer
    rdev = None
1631 da63bb4e René Nussbaumer
1632 da63bb4e René Nussbaumer
  if not rdev:
1633 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1634 da63bb4e René Nussbaumer
1635 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1636 0188611b Michael Hanselmann
  if offset < 0:
1637 0188611b Michael Hanselmann
    _Fail("Negative offset")
1638 0188611b Michael Hanselmann
  if size < 0:
1639 0188611b Michael Hanselmann
    _Fail("Negative size")
1640 da63bb4e René Nussbaumer
  if offset > rdev.size:
1641 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1642 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1643 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1644 69dd363f René Nussbaumer
1645 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1646 69dd363f René Nussbaumer
1647 69dd363f René Nussbaumer
1648 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1649 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1650 5119c79e René Nussbaumer

1651 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1652 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1653 5119c79e René Nussbaumer
  @type pause: bool
1654 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1655 5119c79e René Nussbaumer

1656 5119c79e René Nussbaumer
  """
1657 5119c79e René Nussbaumer
  success = []
1658 5119c79e René Nussbaumer
  for disk in disks:
1659 5119c79e René Nussbaumer
    try:
1660 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1661 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1662 5119c79e René Nussbaumer
      rdev = None
1663 5119c79e René Nussbaumer
1664 5119c79e René Nussbaumer
    if not rdev:
1665 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1666 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1667 5119c79e René Nussbaumer
      continue
1668 5119c79e René Nussbaumer
1669 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1670 5119c79e René Nussbaumer
1671 5119c79e René Nussbaumer
    if result:
1672 5119c79e René Nussbaumer
      success.append((result, None))
1673 5119c79e René Nussbaumer
    else:
1674 5119c79e René Nussbaumer
      if pause:
1675 5119c79e René Nussbaumer
        msg = "Pause"
1676 5119c79e René Nussbaumer
      else:
1677 5119c79e René Nussbaumer
        msg = "Resume"
1678 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1679 5119c79e René Nussbaumer
1680 5119c79e René Nussbaumer
  return success
1681 5119c79e René Nussbaumer
1682 5119c79e René Nussbaumer
1683 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1684 a8083063 Iustin Pop
  """Remove a block device.
1685 a8083063 Iustin Pop

1686 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1687 10c2650b Iustin Pop

1688 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1689 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1690 10c2650b Iustin Pop
  @rtype: boolean
1691 10c2650b Iustin Pop
  @return: the success of the operation
1692 a8083063 Iustin Pop

1693 a8083063 Iustin Pop
  """
1694 e1bc0878 Iustin Pop
  msgs = []
1695 a8083063 Iustin Pop
  try:
1696 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1697 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1698 a8083063 Iustin Pop
    # probably can't attach
1699 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1700 a8083063 Iustin Pop
    rdev = None
1701 a8083063 Iustin Pop
  if rdev is not None:
1702 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1703 e1bc0878 Iustin Pop
    try:
1704 0c6c04ec Iustin Pop
      rdev.Remove()
1705 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1706 e1bc0878 Iustin Pop
      msgs.append(str(err))
1707 c26a6bd2 Iustin Pop
    if not msgs:
1708 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1709 e1bc0878 Iustin Pop
1710 a8083063 Iustin Pop
  if disk.children:
1711 a8083063 Iustin Pop
    for child in disk.children:
1712 c26a6bd2 Iustin Pop
      try:
1713 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1714 c26a6bd2 Iustin Pop
      except RPCFail, err:
1715 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1716 e1bc0878 Iustin Pop
1717 c26a6bd2 Iustin Pop
  if msgs:
1718 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1719 afdc3985 Iustin Pop
1720 a8083063 Iustin Pop
1721 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1722 a8083063 Iustin Pop
  """Activate a block device for an instance.
1723 a8083063 Iustin Pop

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

1726 10c2650b Iustin Pop
  @note: this function is called recursively.
1727 a8083063 Iustin Pop

1728 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1729 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1730 10c2650b Iustin Pop
  @type owner: str
1731 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1732 10c2650b Iustin Pop
  @type as_primary: boolean
1733 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1734 10c2650b Iustin Pop
      read/write
1735 a8083063 Iustin Pop

1736 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1737 10c2650b Iustin Pop
      was assembled)
1738 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1739 10c2650b Iustin Pop
      during the activation of the children or the device
1740 10c2650b Iustin Pop
      itself
1741 a8083063 Iustin Pop

1742 a8083063 Iustin Pop
  """
1743 a8083063 Iustin Pop
  children = []
1744 a8083063 Iustin Pop
  if disk.children:
1745 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1746 fc1dc9d7 Iustin Pop
    if mcn == -1:
1747 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1748 fc1dc9d7 Iustin Pop
    else:
1749 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1750 a8083063 Iustin Pop
    for chld_disk in disk.children:
1751 fc1dc9d7 Iustin Pop
      try:
1752 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1753 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1754 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1755 fc1dc9d7 Iustin Pop
          raise
1756 fc1dc9d7 Iustin Pop
        cdev = None
1757 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1758 1063abd1 Iustin Pop
                      str(err))
1759 fc1dc9d7 Iustin Pop
      children.append(cdev)
1760 a8083063 Iustin Pop
1761 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1762 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
1763 a8083063 Iustin Pop
    result = r_dev
1764 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1765 a8083063 Iustin Pop
      r_dev.Open()
1766 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1767 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1768 3f78eef2 Iustin Pop
1769 a8083063 Iustin Pop
  else:
1770 a8083063 Iustin Pop
    result = True
1771 a8083063 Iustin Pop
  return result
1772 a8083063 Iustin Pop
1773 a8083063 Iustin Pop
1774 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
1775 a8083063 Iustin Pop
  """Activate a block device for an instance.
1776 a8083063 Iustin Pop

1777 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1778 a8083063 Iustin Pop

1779 b1206984 Iustin Pop
  @rtype: str or boolean
1780 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1781 b1206984 Iustin Pop
      C{True} for secondary nodes
1782 a8083063 Iustin Pop

1783 a8083063 Iustin Pop
  """
1784 53c14ef1 Iustin Pop
  try:
1785 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1786 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1787 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
1788 53c14ef1 Iustin Pop
      result = result.dev_path
1789 c417e115 Iustin Pop
      if as_primary:
1790 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
1791 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1792 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1793 c417e115 Iustin Pop
  except OSError, err:
1794 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
1795 afdc3985 Iustin Pop
1796 c26a6bd2 Iustin Pop
  return result
1797 a8083063 Iustin Pop
1798 a8083063 Iustin Pop
1799 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1800 a8083063 Iustin Pop
  """Shut down a block device.
1801 a8083063 Iustin Pop

1802 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1803 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1804 c41eea6e Iustin Pop
  shutdown.
1805 a8083063 Iustin Pop

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

1810 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1811 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1812 10c2650b Iustin Pop
      shutdown
1813 c26a6bd2 Iustin Pop
  @rtype: None
1814 10c2650b Iustin Pop

1815 a8083063 Iustin Pop
  """
1816 cacfd1fd Iustin Pop
  msgs = []
1817 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1818 a8083063 Iustin Pop
  if r_dev is not None:
1819 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1820 cacfd1fd Iustin Pop
    try:
1821 746f7476 Iustin Pop
      r_dev.Shutdown()
1822 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1823 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1824 cacfd1fd Iustin Pop
      msgs.append(str(err))
1825 746f7476 Iustin Pop
1826 a8083063 Iustin Pop
  if disk.children:
1827 a8083063 Iustin Pop
    for child in disk.children:
1828 c26a6bd2 Iustin Pop
      try:
1829 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1830 c26a6bd2 Iustin Pop
      except RPCFail, err:
1831 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1832 746f7476 Iustin Pop
1833 c26a6bd2 Iustin Pop
  if msgs:
1834 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1835 a8083063 Iustin Pop
1836 a8083063 Iustin Pop
1837 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1838 153d9724 Iustin Pop
  """Extend a mirrored block device.
1839 a8083063 Iustin Pop

1840 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1841 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1842 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1843 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1844 c26a6bd2 Iustin Pop
  @rtype: None
1845 10c2650b Iustin Pop

1846 a8083063 Iustin Pop
  """
1847 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1848 153d9724 Iustin Pop
  if parent_bdev is None:
1849 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1850 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1851 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1852 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1853 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1854 a8083063 Iustin Pop
1855 a8083063 Iustin Pop
1856 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1857 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1858 a8083063 Iustin Pop

1859 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1860 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1861 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1862 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1863 c26a6bd2 Iustin Pop
  @rtype: None
1864 10c2650b Iustin Pop

1865 a8083063 Iustin Pop
  """
1866 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1867 153d9724 Iustin Pop
  if parent_bdev is None:
1868 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1869 e739bd57 Iustin Pop
  devs = []
1870 e739bd57 Iustin Pop
  for disk in new_cdevs:
1871 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1872 e739bd57 Iustin Pop
    if rpath is None:
1873 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1874 e739bd57 Iustin Pop
      if bd is None:
1875 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1876 e739bd57 Iustin Pop
      else:
1877 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1878 e739bd57 Iustin Pop
    else:
1879 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1880 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1881 e739bd57 Iustin Pop
      devs.append(rpath)
1882 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1883 a8083063 Iustin Pop
1884 a8083063 Iustin Pop
1885 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1886 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1887 a8083063 Iustin Pop

1888 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1889 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1890 10c2650b Iustin Pop
  @rtype: disk
1891 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1892 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1893 10c2650b Iustin Pop
      found
1894 a8083063 Iustin Pop

1895 a8083063 Iustin Pop
  """
1896 a8083063 Iustin Pop
  stats = []
1897 a8083063 Iustin Pop
  for dsk in disks:
1898 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1899 a8083063 Iustin Pop
    if rbd is None:
1900 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1901 96acbc09 Michael Hanselmann
1902 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1903 96acbc09 Michael Hanselmann
1904 c26a6bd2 Iustin Pop
  return stats
1905 a8083063 Iustin Pop
1906 a8083063 Iustin Pop
1907 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1908 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1909 c6a9dffa Michael Hanselmann

1910 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1911 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1912 c6a9dffa Michael Hanselmann
  @rtype: disk
1913 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1914 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
1915 c6a9dffa Michael Hanselmann
    otherwise
1916 c6a9dffa Michael Hanselmann

1917 c6a9dffa Michael Hanselmann
  """
1918 c6a9dffa Michael Hanselmann
  result = []
1919 c6a9dffa Michael Hanselmann
  for disk in disks:
1920 c6a9dffa Michael Hanselmann
    try:
1921 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
1922 c6a9dffa Michael Hanselmann
      if rbd is None:
1923 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
1924 c6a9dffa Michael Hanselmann
        continue
1925 c6a9dffa Michael Hanselmann
1926 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
1927 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
1928 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
1929 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
1930 c6a9dffa Michael Hanselmann
    else:
1931 c6a9dffa Michael Hanselmann
      result.append((True, status))
1932 c6a9dffa Michael Hanselmann
1933 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
1934 c6a9dffa Michael Hanselmann
1935 c6a9dffa Michael Hanselmann
  return result
1936 c6a9dffa Michael Hanselmann
1937 c6a9dffa Michael Hanselmann
1938 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1939 a8083063 Iustin Pop
  """Check if a device is activated.
1940 a8083063 Iustin Pop

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

1943 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1944 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1945 a8083063 Iustin Pop

1946 10c2650b Iustin Pop
  @return: None if the device can't be found,
1947 10c2650b Iustin Pop
      otherwise the device instance
1948 a8083063 Iustin Pop

1949 a8083063 Iustin Pop
  """
1950 a8083063 Iustin Pop
  children = []
1951 a8083063 Iustin Pop
  if disk.children:
1952 a8083063 Iustin Pop
    for chdisk in disk.children:
1953 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1954 a8083063 Iustin Pop
1955 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
1956 a8083063 Iustin Pop
1957 a8083063 Iustin Pop
1958 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1959 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1960 f2e07bb4 Michael Hanselmann

1961 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1962 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1963 f2e07bb4 Michael Hanselmann

1964 f2e07bb4 Michael Hanselmann
  """
1965 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1966 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1967 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1968 f2e07bb4 Michael Hanselmann
1969 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1970 f2e07bb4 Michael Hanselmann
1971 f2e07bb4 Michael Hanselmann
  return real_disk
1972 f2e07bb4 Michael Hanselmann
1973 f2e07bb4 Michael Hanselmann
1974 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1975 a8083063 Iustin Pop
  """Check if a device is activated.
1976 a8083063 Iustin Pop

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

1979 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1980 10c2650b Iustin Pop
  @param disk: the disk to find
1981 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1982 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1983 96acbc09 Michael Hanselmann
           information
1984 a8083063 Iustin Pop

1985 a8083063 Iustin Pop
  """
1986 23829f6f Iustin Pop
  try:
1987 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1988 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1989 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1990 96acbc09 Michael Hanselmann
1991 a8083063 Iustin Pop
  if rbd is None:
1992 c26a6bd2 Iustin Pop
    return None
1993 96acbc09 Michael Hanselmann
1994 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
1995 a8083063 Iustin Pop
1996 a8083063 Iustin Pop
1997 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1998 968a7623 Iustin Pop
  """Computes the size of the given disks.
1999 968a7623 Iustin Pop

2000 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2001 968a7623 Iustin Pop

2002 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2003 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2004 968a7623 Iustin Pop
  @rtype: list
2005 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2006 968a7623 Iustin Pop
      otherwise the size
2007 968a7623 Iustin Pop

2008 968a7623 Iustin Pop
  """
2009 968a7623 Iustin Pop
  result = []
2010 968a7623 Iustin Pop
  for cf in disks:
2011 968a7623 Iustin Pop
    try:
2012 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2013 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2014 968a7623 Iustin Pop
      result.append(None)
2015 968a7623 Iustin Pop
      continue
2016 968a7623 Iustin Pop
    if rbd is None:
2017 968a7623 Iustin Pop
      result.append(None)
2018 968a7623 Iustin Pop
    else:
2019 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
2020 968a7623 Iustin Pop
  return result
2021 968a7623 Iustin Pop
2022 968a7623 Iustin Pop
2023 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2024 858f3d18 Iustin Pop
  """Export a block device to a remote node.
2025 858f3d18 Iustin Pop

2026 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
2027 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
2028 858f3d18 Iustin Pop
  @type dest_node: str
2029 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
2030 858f3d18 Iustin Pop
  @type dest_path: str
2031 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
2032 858f3d18 Iustin Pop
  @type cluster_name: str
2033 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2034 858f3d18 Iustin Pop
  @rtype: None
2035 858f3d18 Iustin Pop

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

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

2073 10c2650b Iustin Pop
  @type file_name: str
2074 10c2650b Iustin Pop
  @param file_name: the target file name
2075 10c2650b Iustin Pop
  @type data: str
2076 10c2650b Iustin Pop
  @param data: the new contents of the file
2077 10c2650b Iustin Pop
  @type mode: int
2078 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2079 9a914f7a René Nussbaumer
  @type uid: string
2080 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2081 9a914f7a René Nussbaumer
  @type gid: string
2082 9a914f7a René Nussbaumer
  @param gid: the group of the file
2083 10c2650b Iustin Pop
  @type atime: float
2084 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2085 10c2650b Iustin Pop
  @type mtime: float
2086 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2087 c26a6bd2 Iustin Pop
  @rtype: None
2088 10c2650b Iustin Pop

2089 a8083063 Iustin Pop
  """
2090 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2091 cffbbae7 Michael Hanselmann
2092 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2093 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2094 a8083063 Iustin Pop
2095 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2096 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2097 2cc6781a Iustin Pop
          file_name)
2098 a8083063 Iustin Pop
2099 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2100 12bce260 Michael Hanselmann
2101 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2102 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2103 9a914f7a René Nussbaumer
2104 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2105 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2106 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2107 9a914f7a René Nussbaumer
2108 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2109 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2110 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2111 a8083063 Iustin Pop
2112 386b57af Iustin Pop
2113 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2114 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2115 b2f29800 René Nussbaumer

2116 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2117 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2118 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2119 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2120 b2f29800 René Nussbaumer

2121 b2f29800 René Nussbaumer
  @return: stdout
2122 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2123 b2f29800 René Nussbaumer

2124 b2f29800 René Nussbaumer
  """
2125 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2126 b2f29800 René Nussbaumer
2127 b2f29800 René Nussbaumer
  if result.failed:
2128 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2129 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2130 b2f29800 René Nussbaumer
2131 b2f29800 René Nussbaumer
  return result.stdout
2132 b2f29800 René Nussbaumer
2133 b2f29800 René Nussbaumer
2134 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2135 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2136 a8083063 Iustin Pop

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

2140 10c2650b Iustin Pop
  @type os_dir: str
2141 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2142 8e70b181 Iustin Pop
  @rtype: tuple
2143 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2144 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2145 a8083063 Iustin Pop

2146 a8083063 Iustin Pop
  """
2147 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2148 a8083063 Iustin Pop
2149 a8083063 Iustin Pop
  try:
2150 a8083063 Iustin Pop
    st = os.stat(api_file)
2151 a8083063 Iustin Pop
  except EnvironmentError, err:
2152 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2153 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2154 a8083063 Iustin Pop
2155 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2156 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2157 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2158 a8083063 Iustin Pop
2159 a8083063 Iustin Pop
  try:
2160 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2161 a8083063 Iustin Pop
  except EnvironmentError, err:
2162 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2163 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2164 a8083063 Iustin Pop
2165 a8083063 Iustin Pop
  try:
2166 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2167 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2168 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2169 255dcebd Iustin Pop
                   str(err))
2170 a8083063 Iustin Pop
2171 255dcebd Iustin Pop
  return True, api_versions
2172 a8083063 Iustin Pop
2173 386b57af Iustin Pop
2174 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2175 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2176 a8083063 Iustin Pop

2177 10c2650b Iustin Pop
  @type top_dirs: list
2178 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2179 10c2650b Iustin Pop
      search (if not given defaults to
2180 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2181 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2182 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2183 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2184 bad78e66 Iustin Pop
      search paths, where:
2185 255dcebd Iustin Pop
          - name is the (potential) OS name
2186 255dcebd Iustin Pop
          - path is the full path to the OS
2187 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2188 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2189 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2190 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2191 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2192 a8083063 Iustin Pop

2193 a8083063 Iustin Pop
  """
2194 7c3d51d4 Guido Trotter
  if top_dirs is None:
2195 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2196 a8083063 Iustin Pop
2197 a8083063 Iustin Pop
  result = []
2198 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2199 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2200 7c3d51d4 Guido Trotter
      try:
2201 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2202 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2203 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2204 7c3d51d4 Guido Trotter
        break
2205 7c3d51d4 Guido Trotter
      for name in f_names:
2206 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2207 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2208 255dcebd Iustin Pop
        if status:
2209 255dcebd Iustin Pop
          diagnose = ""
2210 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2211 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2212 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2213 255dcebd Iustin Pop
        else:
2214 255dcebd Iustin Pop
          diagnose = os_inst
2215 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2216 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2217 bad78e66 Iustin Pop
                       parameters, api_versions))
2218 a8083063 Iustin Pop
2219 c26a6bd2 Iustin Pop
  return result
2220 a8083063 Iustin Pop
2221 a8083063 Iustin Pop
2222 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2223 a8083063 Iustin Pop
  """Create an OS instance from disk.
2224 a8083063 Iustin Pop

2225 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2226 8e70b181 Iustin Pop
  valid OS name.
2227 a8083063 Iustin Pop

2228 8ee4dc80 Guido Trotter
  @type base_dir: string
2229 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2230 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2231 255dcebd Iustin Pop
  @rtype: tuple
2232 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2233 255dcebd Iustin Pop
      or error message
2234 7c3d51d4 Guido Trotter

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

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

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

2331 255dcebd Iustin Pop
  @type base_dir: string
2332 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2333 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2334 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2335 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2336 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2337 255dcebd Iustin Pop

2338 255dcebd Iustin Pop
  """
2339 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2340 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2341 255dcebd Iustin Pop
2342 255dcebd Iustin Pop
  if not status:
2343 255dcebd Iustin Pop
    _Fail(payload)
2344 a8083063 Iustin Pop
2345 255dcebd Iustin Pop
  return payload
2346 a8083063 Iustin Pop
2347 a8083063 Iustin Pop
2348 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2349 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2350 2266edb2 Guido Trotter

2351 a025e535 Vitaly Kuznetsov
  @type os_name: str
2352 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2353 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2354 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2355 1bdcbbab Iustin Pop
  @type os_params: dict
2356 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2357 2266edb2 Guido Trotter
  @type debug: integer
2358 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2359 2266edb2 Guido Trotter
  @rtype: dict
2360 2266edb2 Guido Trotter
  @return: dict of environment variables
2361 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2362 10c2650b Iustin Pop
      cannot be found
2363 2266edb2 Guido Trotter

2364 2266edb2 Guido Trotter
  """
2365 2266edb2 Guido Trotter
  result = {}
2366 099c52ad Iustin Pop
  api_version = \
2367 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2368 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2369 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2370 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2371 efaa9b06 Iustin Pop
2372 efaa9b06 Iustin Pop
  # OS variants
2373 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2374 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2375 870dc44c Iustin Pop
    if not variant:
2376 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2377 35007011 Iustin Pop
  else:
2378 35007011 Iustin Pop
    variant = ""
2379 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2380 efaa9b06 Iustin Pop
2381 1bdcbbab Iustin Pop
  # OS params
2382 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2383 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2384 1bdcbbab Iustin Pop
2385 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
2386 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
2387 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
2388 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
2389 9a6ade06 Iustin Pop
2390 efaa9b06 Iustin Pop
  return result
2391 efaa9b06 Iustin Pop
2392 efaa9b06 Iustin Pop
2393 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2394 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2395 efaa9b06 Iustin Pop

2396 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2397 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2398 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2399 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2400 efaa9b06 Iustin Pop
  @type debug: integer
2401 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2402 efaa9b06 Iustin Pop
  @rtype: dict
2403 efaa9b06 Iustin Pop
  @return: dict of environment variables
2404 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2405 efaa9b06 Iustin Pop
      cannot be found
2406 efaa9b06 Iustin Pop

2407 efaa9b06 Iustin Pop
  """
2408 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2409 efaa9b06 Iustin Pop
2410 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2411 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2412 f2165b8a Iustin Pop
2413 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2414 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2415 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2416 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2417 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2418 efaa9b06 Iustin Pop
2419 efaa9b06 Iustin Pop
  # Disks
2420 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2421 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2422 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2423 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2424 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2425 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2426 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2427 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2428 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2429 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2430 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2431 d0c8c01d Iustin Pop
        "file:%s" % disk.physical_id[0]
2432 efaa9b06 Iustin Pop
2433 efaa9b06 Iustin Pop
  # NICs
2434 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2435 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2436 2266edb2 Guido Trotter
    if nic.ip:
2437 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2438 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2439 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2440 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2441 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2442 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2443 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2444 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2445 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2446 2266edb2 Guido Trotter
2447 efaa9b06 Iustin Pop
  # HV/BE params
2448 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2449 67fc3042 Iustin Pop
    for key, value in source.items():
2450 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2451 67fc3042 Iustin Pop
2452 2266edb2 Guido Trotter
  return result
2453 a8083063 Iustin Pop
2454 f2e07bb4 Michael Hanselmann
2455 cad0723b Iustin Pop
def BlockdevGrow(disk, amount, dryrun, backingstore):
2456 594609c0 Iustin Pop
  """Grow a stack of block devices.
2457 594609c0 Iustin Pop

2458 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2459 10c2650b Iustin Pop
  first ones to resize.
2460 594609c0 Iustin Pop

2461 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2462 10c2650b Iustin Pop
  @param disk: the disk to be grown
2463 a59faf4b Iustin Pop
  @type amount: integer
2464 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2465 a59faf4b Iustin Pop
  @type dryrun: boolean
2466 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2467 a59faf4b Iustin Pop
      only, without actually increasing the size
2468 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
2469 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2470 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
2471 10c2650b Iustin Pop
  @rtype: (status, result)
2472 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2473 a59faf4b Iustin Pop
      the errors message if status is False
2474 594609c0 Iustin Pop

2475 594609c0 Iustin Pop
  """
2476 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2477 594609c0 Iustin Pop
  if r_dev is None:
2478 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2479 594609c0 Iustin Pop
2480 594609c0 Iustin Pop
  try:
2481 cad0723b Iustin Pop
    r_dev.Grow(amount, dryrun, backingstore)
2482 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2483 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2484 594609c0 Iustin Pop
2485 594609c0 Iustin Pop
2486 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2487 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2488 a8083063 Iustin Pop

2489 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2490 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2491 a8083063 Iustin Pop

2492 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2493 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2494 e9e9263d Guido Trotter
  @rtype: string
2495 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2496 a8083063 Iustin Pop

2497 098c0958 Michael Hanselmann
  """
2498 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2499 433c63aa Iustin Pop
    if not disk.children:
2500 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2501 433c63aa Iustin Pop
            disk.unique_id)
2502 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2503 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2504 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2505 a8083063 Iustin Pop
    if r_dev is not None:
2506 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2507 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2508 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2509 a8083063 Iustin Pop
    else:
2510 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2511 a8083063 Iustin Pop
  else:
2512 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2513 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2514 a8083063 Iustin Pop
2515 a8083063 Iustin Pop
2516 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2517 a8083063 Iustin Pop
  """Write out the export configuration information.
2518 a8083063 Iustin Pop

2519 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2520 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2521 10c2650b Iustin Pop
      saving configuration
2522 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2523 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2524 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2525 a8083063 Iustin Pop

2526 c26a6bd2 Iustin Pop
  @rtype: None
2527 a8083063 Iustin Pop

2528 098c0958 Michael Hanselmann
  """
2529 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2530 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2531 a8083063 Iustin Pop
2532 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2533 a8083063 Iustin Pop
2534 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2535 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
2536 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2537 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2538 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
2539 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2540 a8083063 Iustin Pop
2541 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2542 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
2543 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2544 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2545 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
2546 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
2547 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2548 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
2549 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2550 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2551 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2552 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2553 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2554 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2555 66f93869 Manuel Franceschini
2556 95268cc3 Iustin Pop
  nic_total = 0
2557 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2558 95268cc3 Iustin Pop
    nic_total += 1
2559 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
2560 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
2561 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2562 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2563 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2564 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
2565 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2566 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2567 a8083063 Iustin Pop
2568 726d7d68 Iustin Pop
  disk_total = 0
2569 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2570 19d7f90a Guido Trotter
    if disk:
2571 726d7d68 Iustin Pop
      disk_total += 1
2572 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2573 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
2574 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2575 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
2576 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2577 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
2578 d0c8c01d Iustin Pop
2579 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2580 a8083063 Iustin Pop
2581 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2582 3c8954ad Iustin Pop
2583 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2584 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2585 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2586 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2587 3c8954ad Iustin Pop
2588 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2589 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2590 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2591 3c8954ad Iustin Pop
2592 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2593 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2594 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2595 535b49cb Iustin Pop
2596 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2597 726d7d68 Iustin Pop
                  data=config.Dumps())
2598 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2599 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2600 a8083063 Iustin Pop
2601 a8083063 Iustin Pop
2602 a8083063 Iustin Pop
def ExportInfo(dest):
2603 a8083063 Iustin Pop
  """Get export configuration information.
2604 a8083063 Iustin Pop

2605 10c2650b Iustin Pop
  @type dest: str
2606 10c2650b Iustin Pop
  @param dest: directory containing the export
2607 a8083063 Iustin Pop

2608 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2609 10c2650b Iustin Pop
  @return: a serializable config file containing the
2610 10c2650b Iustin Pop
      export info
2611 a8083063 Iustin Pop

2612 a8083063 Iustin Pop
  """
2613 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2614 a8083063 Iustin Pop
2615 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2616 a8083063 Iustin Pop
  config.read(cff)
2617 a8083063 Iustin Pop
2618 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2619 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2620 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2621 a8083063 Iustin Pop
2622 c26a6bd2 Iustin Pop
  return config.Dumps()
2623 a8083063 Iustin Pop
2624 a8083063 Iustin Pop
2625 a8083063 Iustin Pop
def ListExports():
2626 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2627 098c0958 Michael Hanselmann

2628 10c2650b Iustin Pop
  @rtype: list
2629 10c2650b Iustin Pop
  @return: list of the exports
2630 10c2650b Iustin Pop

2631 a8083063 Iustin Pop
  """
2632 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
2633 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2634 a8083063 Iustin Pop
  else:
2635 afdc3985 Iustin Pop
    _Fail("No exports directory")
2636 a8083063 Iustin Pop
2637 a8083063 Iustin Pop
2638 a8083063 Iustin Pop
def RemoveExport(export):
2639 a8083063 Iustin Pop
  """Remove an existing export from the node.
2640 a8083063 Iustin Pop

2641 10c2650b Iustin Pop
  @type export: str
2642 10c2650b Iustin Pop
  @param export: the name of the export to remove
2643 c26a6bd2 Iustin Pop
  @rtype: None
2644 a8083063 Iustin Pop

2645 098c0958 Michael Hanselmann
  """
2646 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2647 a8083063 Iustin Pop
2648 35fbcd11 Iustin Pop
  try:
2649 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2650 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2651 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2652 a8083063 Iustin Pop
2653 a8083063 Iustin Pop
2654 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2655 f3e513ad Iustin Pop
  """Rename a list of block devices.
2656 f3e513ad Iustin Pop

2657 10c2650b Iustin Pop
  @type devlist: list of tuples
2658 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2659 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2660 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2661 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2662 10c2650b Iustin Pop
      rename it to
2663 10c2650b Iustin Pop
  @rtype: boolean
2664 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2665 f3e513ad Iustin Pop

2666 f3e513ad Iustin Pop
  """
2667 6b5e3f70 Iustin Pop
  msgs = []
2668 f3e513ad Iustin Pop
  result = True
2669 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2670 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2671 f3e513ad Iustin Pop
    if dev is None:
2672 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2673 f3e513ad Iustin Pop
      result = False
2674 f3e513ad Iustin Pop
      continue
2675 f3e513ad Iustin Pop
    try:
2676 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2677 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2678 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2679 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2680 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2681 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2682 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2683 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2684 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2685 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2686 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2687 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2688 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2689 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2690 f3e513ad Iustin Pop
      result = False
2691 afdc3985 Iustin Pop
  if not result:
2692 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2693 f3e513ad Iustin Pop
2694 f3e513ad Iustin Pop
2695 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2696 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2697 778b75bb Manuel Franceschini

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

2702 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2703 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2704 d61cbe76 Iustin Pop

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

2707 778b75bb Manuel Franceschini
  """
2708 63a3d8f7 Michael Hanselmann
  if not (constants.ENABLE_FILE_STORAGE or
2709 63a3d8f7 Michael Hanselmann
          constants.ENABLE_SHARED_FILE_STORAGE):
2710 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2711 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2712 4b97f902 Apollon Oikonomopoulos
  fs_dir = os.path.normpath(fs_dir)
2713 4b97f902 Apollon Oikonomopoulos
  base_fstore = cfg.GetFileStorageDir()
2714 4b97f902 Apollon Oikonomopoulos
  base_shared = cfg.GetSharedFileStorageDir()
2715 cf00dba0 René Nussbaumer
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2716 cf00dba0 René Nussbaumer
          utils.IsBelowDir(base_shared, fs_dir)):
2717 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2718 4b97f902 Apollon Oikonomopoulos
          " storage directory '%s' or shared storage directory '%s'",
2719 4b97f902 Apollon Oikonomopoulos
          fs_dir, base_fstore, base_shared)
2720 4b97f902 Apollon Oikonomopoulos
  return fs_dir
2721 778b75bb Manuel Franceschini
2722 778b75bb Manuel Franceschini
2723 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2724 778b75bb Manuel Franceschini
  """Create file storage directory.
2725 778b75bb Manuel Franceschini

2726 b1206984 Iustin Pop
  @type file_storage_dir: str
2727 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2728 778b75bb Manuel Franceschini

2729 b1206984 Iustin Pop
  @rtype: tuple
2730 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2731 b1206984 Iustin Pop
      creation was successful or not
2732 778b75bb Manuel Franceschini

2733 778b75bb Manuel Franceschini
  """
2734 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2735 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2736 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2737 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2738 b2b8bcce Iustin Pop
            file_storage_dir)
2739 778b75bb Manuel Franceschini
  else:
2740 b2b8bcce Iustin Pop
    try:
2741 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2742 b2b8bcce Iustin Pop
    except OSError, err:
2743 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2744 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2745 778b75bb Manuel Franceschini
2746 778b75bb Manuel Franceschini
2747 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2748 778b75bb Manuel Franceschini
  """Remove file storage directory.
2749 778b75bb Manuel Franceschini

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

2752 10c2650b Iustin Pop
  @type file_storage_dir: str
2753 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2754 10c2650b Iustin Pop
  @rtype: tuple (success,)
2755 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2756 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2757 778b75bb Manuel Franceschini

2758 778b75bb Manuel Franceschini
  """
2759 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2760 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2761 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2762 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2763 b2b8bcce Iustin Pop
            file_storage_dir)
2764 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2765 b2b8bcce Iustin Pop
    try:
2766 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2767 b2b8bcce Iustin Pop
    except OSError, err:
2768 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2769 b2b8bcce Iustin Pop
            file_storage_dir, err)
2770 b2b8bcce Iustin Pop
2771 778b75bb Manuel Franceschini
2772 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2773 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2774 778b75bb Manuel Franceschini

2775 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2776 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2777 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2778 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2779 10c2650b Iustin Pop
  @rtype: tuple (success,)
2780 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2781 10c2650b Iustin Pop
      whether the operation was successful
2782 778b75bb Manuel Franceschini

2783 778b75bb Manuel Franceschini
  """
2784 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2785 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2786 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2787 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2788 b2b8bcce Iustin Pop
      try:
2789 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2790 b2b8bcce Iustin Pop
      except OSError, err:
2791 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2792 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2793 778b75bb Manuel Franceschini
    else:
2794 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2795 b2b8bcce Iustin Pop
            old_file_storage_dir)
2796 b2b8bcce Iustin Pop
  else:
2797 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2798 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2799 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2800 778b75bb Manuel Franceschini
2801 778b75bb Manuel Franceschini
2802 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2803 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2804 ca52cdeb Michael Hanselmann

2805 10c2650b Iustin Pop
  @type file_name: str
2806 10c2650b Iustin Pop
  @param file_name: the file name we should check
2807 c8457ce7 Iustin Pop
  @rtype: None
2808 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2809 10c2650b Iustin Pop

2810 ca52cdeb Michael Hanselmann
  """
2811 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2812 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2813 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2814 dc31eae3 Michael Hanselmann
2815 dc31eae3 Michael Hanselmann
2816 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2817 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2818 dc31eae3 Michael Hanselmann

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

2822 10c2650b Iustin Pop
  @type file_name: str
2823 10c2650b Iustin Pop
  @param file_name: the job file name
2824 10c2650b Iustin Pop
  @type content: str
2825 10c2650b Iustin Pop
  @param content: the new job contents
2826 10c2650b Iustin Pop
  @rtype: boolean
2827 10c2650b Iustin Pop
  @return: the success of the operation
2828 10c2650b Iustin Pop

2829 dc31eae3 Michael Hanselmann
  """
2830 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2831 cffbbae7 Michael Hanselmann
2832 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2833 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2834 ca52cdeb Michael Hanselmann
2835 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2836 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2837 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2838 ca52cdeb Michael Hanselmann
2839 ca52cdeb Michael Hanselmann
2840 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2841 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2842 af5ebcb1 Michael Hanselmann

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

2845 10c2650b Iustin Pop
  @type old: str
2846 10c2650b Iustin Pop
  @param old: the old (actual) file name
2847 10c2650b Iustin Pop
  @type new: str
2848 10c2650b Iustin Pop
  @param new: the desired file name
2849 c8457ce7 Iustin Pop
  @rtype: tuple
2850 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2851 10c2650b Iustin Pop

2852 af5ebcb1 Michael Hanselmann
  """
2853 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
2854 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
2855 cffbbae7 Michael Hanselmann
2856 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2857 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2858 af5ebcb1 Michael Hanselmann
2859 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
2860 8e5a705d René Nussbaumer
2861 8e5a705d René Nussbaumer
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2862 8e5a705d René Nussbaumer
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2863 af5ebcb1 Michael Hanselmann
2864 af5ebcb1 Michael Hanselmann
2865 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2866 d61cbe76 Iustin Pop
  """Closes the given block devices.
2867 d61cbe76 Iustin Pop

2868 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2869 10c2650b Iustin Pop
  DRBD).
2870 10c2650b Iustin Pop

2871 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2872 b2e7666a Iustin Pop
      of this instance will be removed
2873 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2874 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2875 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2876 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2877 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2878 10c2650b Iustin Pop
      which will contain the error details in case we
2879 10c2650b Iustin Pop
      failed
2880 d61cbe76 Iustin Pop

2881 d61cbe76 Iustin Pop
  """
2882 d61cbe76 Iustin Pop
  bdevs = []
2883 d61cbe76 Iustin Pop
  for cf in disks:
2884 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2885 d61cbe76 Iustin Pop
    if rd is None:
2886 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2887 d61cbe76 Iustin Pop
    bdevs.append(rd)
2888 d61cbe76 Iustin Pop
2889 d61cbe76 Iustin Pop
  msg = []
2890 d61cbe76 Iustin Pop
  for rd in bdevs:
2891 d61cbe76 Iustin Pop
    try:
2892 d61cbe76 Iustin Pop
      rd.Close()
2893 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2894 d61cbe76 Iustin Pop
      msg.append(str(err))
2895 d61cbe76 Iustin Pop
  if msg:
2896 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2897 d61cbe76 Iustin Pop
  else:
2898 b2e7666a Iustin Pop
    if instance_name:
2899 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2900 d61cbe76 Iustin Pop
2901 d61cbe76 Iustin Pop
2902 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2903 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2904 6217e295 Iustin Pop

2905 6217e295 Iustin Pop
  @type hvname: string
2906 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2907 6217e295 Iustin Pop
  @type hvparams: dict
2908 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2909 c26a6bd2 Iustin Pop
  @rtype: None
2910 6217e295 Iustin Pop

2911 6217e295 Iustin Pop
  """
2912 6217e295 Iustin Pop
  try:
2913 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2914 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2915 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2916 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2917 6217e295 Iustin Pop
2918 6217e295 Iustin Pop
2919 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
2920 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
2921 acd9ff9e Iustin Pop

2922 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
2923 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
2924 acd9ff9e Iustin Pop
  @type parameters: list
2925 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
2926 acd9ff9e Iustin Pop

2927 acd9ff9e Iustin Pop
  """
2928 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
2929 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
2930 acd9ff9e Iustin Pop
  if delta:
2931 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
2932 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2933 acd9ff9e Iustin Pop
2934 acd9ff9e Iustin Pop
2935 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
2936 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
2937 acd9ff9e Iustin Pop

2938 acd9ff9e Iustin Pop
  @type required: boolean
2939 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
2940 acd9ff9e Iustin Pop
      failure or not
2941 acd9ff9e Iustin Pop
  @type osname: string
2942 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
2943 acd9ff9e Iustin Pop
  @type checks: list
2944 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
2945 acd9ff9e Iustin Pop
  @type osparams: dict
2946 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
2947 acd9ff9e Iustin Pop
  @rtype: boolean
2948 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
2949 acd9ff9e Iustin Pop
      found and L{required} was false
2950 acd9ff9e Iustin Pop

2951 acd9ff9e Iustin Pop
  """
2952 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2953 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
2954 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2955 acd9ff9e Iustin Pop
2956 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
2957 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
2958 acd9ff9e Iustin Pop
2959 acd9ff9e Iustin Pop
  if not status:
2960 acd9ff9e Iustin Pop
    if required:
2961 acd9ff9e Iustin Pop
      _Fail(tbv)
2962 acd9ff9e Iustin Pop
    else:
2963 acd9ff9e Iustin Pop
      return False
2964 acd9ff9e Iustin Pop
2965 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
2966 72db3fd7 Iustin Pop
    return True
2967 72db3fd7 Iustin Pop
2968 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
2969 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
2970 acd9ff9e Iustin Pop
2971 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
2972 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2973 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
2974 acd9ff9e Iustin Pop
  if result.failed:
2975 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
2976 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
2977 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
2978 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
2979 acd9ff9e Iustin Pop
2980 acd9ff9e Iustin Pop
  return True
2981 acd9ff9e Iustin Pop
2982 acd9ff9e Iustin Pop
2983 56aa9fd5 Iustin Pop
def DemoteFromMC():
2984 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2985 56aa9fd5 Iustin Pop

2986 56aa9fd5 Iustin Pop
  """
2987 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2988 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2989 56aa9fd5 Iustin Pop
  if master == myself:
2990 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2991 f154a7a3 Michael Hanselmann
2992 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
2993 f154a7a3 Michael Hanselmann
  if not result.failed:
2994 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2995 f154a7a3 Michael Hanselmann
2996 56aa9fd5 Iustin Pop
  try:
2997 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
2998 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
2999 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3000 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3001 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3002 f154a7a3 Michael Hanselmann
3003 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3004 56aa9fd5 Iustin Pop
3005 56aa9fd5 Iustin Pop
3006 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3007 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3008 f942a838 Michael Hanselmann

3009 f942a838 Michael Hanselmann
  """
3010 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3011 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3012 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3013 f942a838 Michael Hanselmann
3014 f942a838 Michael Hanselmann
3015 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3016 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3017 f942a838 Michael Hanselmann

3018 f942a838 Michael Hanselmann
  @type validity: int
3019 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3020 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3021 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3022 f942a838 Michael Hanselmann

3023 f942a838 Michael Hanselmann
  """
3024 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3025 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3026 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3027 f942a838 Michael Hanselmann
3028 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3029 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3030 f942a838 Michael Hanselmann
  try:
3031 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3032 f942a838 Michael Hanselmann
    assert len(name) > 5
3033 f942a838 Michael Hanselmann
3034 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3035 f942a838 Michael Hanselmann
3036 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3037 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3038 f942a838 Michael Hanselmann
3039 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3040 f942a838 Michael Hanselmann
    return (name, cert_pem)
3041 f942a838 Michael Hanselmann
  except Exception:
3042 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3043 f942a838 Michael Hanselmann
    raise
3044 f942a838 Michael Hanselmann
3045 f942a838 Michael Hanselmann
3046 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3047 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3048 f942a838 Michael Hanselmann

3049 f942a838 Michael Hanselmann
  @type name: string
3050 f942a838 Michael Hanselmann
  @param name: Certificate name
3051 f942a838 Michael Hanselmann

3052 f942a838 Michael Hanselmann
  """
3053 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3054 f942a838 Michael Hanselmann
3055 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3056 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3057 f942a838 Michael Hanselmann
3058 f942a838 Michael Hanselmann
  try:
3059 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3060 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3061 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3062 f942a838 Michael Hanselmann
          cert_dir, err)
3063 f942a838 Michael Hanselmann
3064 f942a838 Michael Hanselmann
3065 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3066 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3067 1651d116 Michael Hanselmann

3068 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3069 1651d116 Michael Hanselmann
  @param instance: The instance object
3070 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3071 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3072 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3073 1651d116 Michael Hanselmann

3074 1651d116 Michael Hanselmann
  """
3075 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3076 1651d116 Michael Hanselmann
3077 1651d116 Michael Hanselmann
  env = None
3078 1651d116 Michael Hanselmann
  prefix = None
3079 1651d116 Michael Hanselmann
  suffix = None
3080 2ad5550d Michael Hanselmann
  exp_size = None
3081 1651d116 Michael Hanselmann
3082 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
3083 1651d116 Michael Hanselmann
    (filename, ) = ieargs
3084 1651d116 Michael Hanselmann
3085 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
3086 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
3087 1651d116 Michael Hanselmann
3088 748c9884 René Nussbaumer
    real_filename = os.path.realpath(filename)
3089 748c9884 René Nussbaumer
    directory = os.path.dirname(real_filename)
3090 1651d116 Michael Hanselmann
3091 710f30ec Michael Hanselmann
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3092 748c9884 René Nussbaumer
      _Fail("File '%s' is not under exports directory '%s': %s",
3093 710f30ec Michael Hanselmann
            filename, pathutils.EXPORT_DIR, real_filename)
3094 1651d116 Michael Hanselmann
3095 1651d116 Michael Hanselmann
    # Create directory
3096 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
3097 1651d116 Michael Hanselmann
3098 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
3099 1651d116 Michael Hanselmann
3100 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3101 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
3102 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3103 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
3104 1651d116 Michael Hanselmann
3105 2ad5550d Michael Hanselmann
      # Retrieve file size
3106 2ad5550d Michael Hanselmann
      try:
3107 2ad5550d Michael Hanselmann
        st = os.stat(filename)
3108 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
3109 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
3110 2ad5550d Michael Hanselmann
      else:
3111 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
3112 2ad5550d Michael Hanselmann
3113 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
3114 1651d116 Michael Hanselmann
    (disk, ) = ieargs
3115 1651d116 Michael Hanselmann
3116 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3117 1651d116 Michael Hanselmann
3118 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3119 1651d116 Michael Hanselmann
      # we set here a smaller block size as, due to transport buffering, more
3120 1651d116 Michael Hanselmann
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3121 1651d116 Michael Hanselmann
      # is not already there or we pass a wrong path; we use notrunc to no
3122 1651d116 Michael Hanselmann
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3123 1651d116 Michael Hanselmann
      # much memory; this means that at best, we flush every 64k, which will
3124 1651d116 Michael Hanselmann
      # not be very fast
3125 1651d116 Michael Hanselmann
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3126 1651d116 Michael Hanselmann
                                    " bs=%s oflag=dsync"),
3127 1651d116 Michael Hanselmann
                                    real_disk.dev_path,
3128 1651d116 Michael Hanselmann
                                    str(64 * 1024))
3129 1651d116 Michael Hanselmann
3130 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3131 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
3132 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3133 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
3134 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
3135 1651d116 Michael Hanselmann
                                   str(disk.size))
3136 2ad5550d Michael Hanselmann
      exp_size = disk.size
3137 1651d116 Michael Hanselmann
3138 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
3139 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
3140 1651d116 Michael Hanselmann
3141 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
3142 1651d116 Michael Hanselmann
3143 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3144 1651d116 Michael Hanselmann
3145 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
3146 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
3147 1651d116 Michael Hanselmann
3148 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3149 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3150 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
3151 1651d116 Michael Hanselmann
      script = inst_os.import_script
3152 1651d116 Michael Hanselmann
3153 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3154 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
3155 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
3156 1651d116 Michael Hanselmann
      script = inst_os.export_script
3157 1651d116 Michael Hanselmann
3158 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
3159 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3160 1651d116 Michael Hanselmann
3161 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3162 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
3163 1651d116 Michael Hanselmann
3164 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3165 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
3166 1651d116 Michael Hanselmann
3167 2ad5550d Michael Hanselmann
    # Let script predict size
3168 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
3169 2ad5550d Michael Hanselmann
3170 1651d116 Michael Hanselmann
  else:
3171 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3172 1651d116 Michael Hanselmann
3173 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
3174 1651d116 Michael Hanselmann
3175 1651d116 Michael Hanselmann
3176 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
3177 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
3178 1651d116 Michael Hanselmann

3179 1651d116 Michael Hanselmann
  """
3180 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3181 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3182 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3183 1651d116 Michael Hanselmann
3184 1651d116 Michael Hanselmann
3185 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3186 6613661a Iustin Pop
                            ieio, ieioargs):
3187 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3188 1651d116 Michael Hanselmann

3189 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3190 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3191 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3192 1651d116 Michael Hanselmann
  @type host: string
3193 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3194 1651d116 Michael Hanselmann
  @type port: int
3195 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3196 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3197 1651d116 Michael Hanselmann
  @param instance: Instance object
3198 6613661a Iustin Pop
  @type component: string
3199 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3200 6613661a Iustin Pop
      e.g. 'disk/0'
3201 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3202 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3203 1651d116 Michael Hanselmann

3204 1651d116 Michael Hanselmann
  """
3205 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
3206 1651d116 Michael Hanselmann
    prefix = "import"
3207 1651d116 Michael Hanselmann
3208 1651d116 Michael Hanselmann
    if not (host is None and port is None):
3209 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
3210 1651d116 Michael Hanselmann
3211 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
3212 1651d116 Michael Hanselmann
    prefix = "export"
3213 1651d116 Michael Hanselmann
3214 1651d116 Michael Hanselmann
    if host is None or port is None:
3215 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
3216 1651d116 Michael Hanselmann
3217 1651d116 Michael Hanselmann
  else:
3218 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
3219 1651d116 Michael Hanselmann
3220 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
3221 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
3222 1651d116 Michael Hanselmann
3223 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3224 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3225 1651d116 Michael Hanselmann
3226 eb630f50 Michael Hanselmann
  if opts.key_name is None:
3227 1651d116 Michael Hanselmann
    # Use server.pem
3228 710f30ec Michael Hanselmann
    key_path = pathutils.NODED_CERT_FILE
3229 710f30ec Michael Hanselmann
    cert_path = pathutils.NODED_CERT_FILE
3230 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
3231 1651d116 Michael Hanselmann
  else:
3232 710f30ec Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3233 eb630f50 Michael Hanselmann
                                                 opts.key_name)
3234 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
3235 1651d116 Michael Hanselmann
3236 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
3237 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
3238 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
3239 63bcea2a Michael Hanselmann
3240 6613661a Iustin Pop
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3241 1651d116 Michael Hanselmann
  try:
3242 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3243 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3244 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3245 1651d116 Michael Hanselmann
3246 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
3247 1651d116 Michael Hanselmann
      # Use server.pem
3248 710f30ec Michael Hanselmann
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3249 eb630f50 Michael Hanselmann
    else:
3250 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
3251 63bcea2a Michael Hanselmann
3252 eb630f50 Michael Hanselmann
    # Write CA file
3253 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
3254 1651d116 Michael Hanselmann
3255 1651d116 Michael Hanselmann
    cmd = [
3256 710f30ec Michael Hanselmann
      pathutils.IMPORT_EXPORT_DAEMON,
3257 1651d116 Michael Hanselmann
      status_file, mode,
3258 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
3259 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
3260 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
3261 1651d116 Michael Hanselmann
      ]
3262 1651d116 Michael Hanselmann
3263 1651d116 Michael Hanselmann
    if host:
3264 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
3265 1651d116 Michael Hanselmann
3266 1651d116 Michael Hanselmann
    if port:
3267 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
3268 1651d116 Michael Hanselmann
3269 855d2fc7 Michael Hanselmann
    if opts.ipv6:
3270 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
3271 855d2fc7 Michael Hanselmann
    else:
3272 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
3273 855d2fc7 Michael Hanselmann
3274 a5310c2a Michael Hanselmann
    if opts.compress:
3275 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
3276 a5310c2a Michael Hanselmann
3277 af1d39b1 Michael Hanselmann
    if opts.magic:
3278 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
3279 af1d39b1 Michael Hanselmann
3280 2ad5550d Michael Hanselmann
    if exp_size is not None:
3281 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
3282 2ad5550d Michael Hanselmann
3283 1651d116 Michael Hanselmann
    if cmd_prefix:
3284 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3285 1651d116 Michael Hanselmann
3286 1651d116 Michael Hanselmann
    if cmd_suffix:
3287 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3288 1651d116 Michael Hanselmann
3289 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
3290 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
3291 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3292 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3293 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
3294 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
3295 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
3296 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3297 4478301b Michael Hanselmann
3298 6aa7a354 Iustin Pop
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3299 1651d116 Michael Hanselmann
3300 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3301 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
3302 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3303 1651d116 Michael Hanselmann
                      output=logfile)
3304 1651d116 Michael Hanselmann
3305 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
3306 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
3307 1651d116 Michael Hanselmann
3308 1651d116 Michael Hanselmann
  except Exception:
3309 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
3310 1651d116 Michael Hanselmann
    raise
3311 1651d116 Michael Hanselmann
3312 1651d116 Michael Hanselmann
3313 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
3314 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
3315 1651d116 Michael Hanselmann

3316 1651d116 Michael Hanselmann
  @type names: sequence
3317 1651d116 Michael Hanselmann
  @param names: List of names
3318 1651d116 Michael Hanselmann
  @rtype: List of dicts
3319 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3320 1651d116 Michael Hanselmann
           status couldn't be read
3321 1651d116 Michael Hanselmann

3322 1651d116 Michael Hanselmann
  """
3323 1651d116 Michael Hanselmann
  result = []
3324 1651d116 Michael Hanselmann
3325 1651d116 Michael Hanselmann
  for name in names:
3326 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3327 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3328 1651d116 Michael Hanselmann
3329 1651d116 Michael Hanselmann
    try:
3330 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3331 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3332 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3333 1651d116 Michael Hanselmann
        raise
3334 1651d116 Michael Hanselmann
      data = None
3335 1651d116 Michael Hanselmann
3336 1651d116 Michael Hanselmann
    if not data:
3337 1651d116 Michael Hanselmann
      result.append(None)
3338 1651d116 Michael Hanselmann
      continue
3339 1651d116 Michael Hanselmann
3340 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3341 1651d116 Michael Hanselmann
3342 1651d116 Michael Hanselmann
  return result
3343 1651d116 Michael Hanselmann
3344 1651d116 Michael Hanselmann
3345 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3346 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3347 f81c4737 Michael Hanselmann

3348 f81c4737 Michael Hanselmann
  """
3349 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3350 f81c4737 Michael Hanselmann
3351 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3352 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3353 f81c4737 Michael Hanselmann
3354 f81c4737 Michael Hanselmann
  if pid:
3355 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3356 f81c4737 Michael Hanselmann
                 name, pid)
3357 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3358 f81c4737 Michael Hanselmann
3359 f81c4737 Michael Hanselmann
3360 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3361 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3362 1651d116 Michael Hanselmann

3363 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3364 1651d116 Michael Hanselmann
  whole status directory is removed.
3365 1651d116 Michael Hanselmann

3366 1651d116 Michael Hanselmann
  """
3367 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3368 1651d116 Michael Hanselmann
3369 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3370 1651d116 Michael Hanselmann
3371 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3372 1651d116 Michael Hanselmann
3373 1651d116 Michael Hanselmann
  if pid:
3374 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3375 1651d116 Michael Hanselmann
                 name, pid)
3376 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3377 1651d116 Michael Hanselmann
3378 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3379 1651d116 Michael Hanselmann
3380 1651d116 Michael Hanselmann
3381 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3382 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3383 6b93ec9d Iustin Pop

3384 6b93ec9d Iustin Pop
  """
3385 6b93ec9d Iustin Pop
  # set the correct physical ID
3386 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3387 6b93ec9d Iustin Pop
  for cf in disks:
3388 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3389 6b93ec9d Iustin Pop
3390 6b93ec9d Iustin Pop
  bdevs = []
3391 6b93ec9d Iustin Pop
3392 6b93ec9d Iustin Pop
  for cf in disks:
3393 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3394 6b93ec9d Iustin Pop
    if rd is None:
3395 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3396 6b93ec9d Iustin Pop
    bdevs.append(rd)
3397 5a533f8a Iustin Pop
  return bdevs
3398 6b93ec9d Iustin Pop
3399 6b93ec9d Iustin Pop
3400 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3401 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3402 6b93ec9d Iustin Pop

3403 6b93ec9d Iustin Pop
  """
3404 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3405 6b93ec9d Iustin Pop
3406 6b93ec9d Iustin Pop
  # disconnect disks
3407 6b93ec9d Iustin Pop
  for rd in bdevs:
3408 6b93ec9d Iustin Pop
    try:
3409 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3410 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3411 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3412 2cc6781a Iustin Pop
            err, exc=True)
3413 6b93ec9d Iustin Pop
3414 6b93ec9d Iustin Pop
3415 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3416 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3417 6b93ec9d Iustin Pop

3418 6b93ec9d Iustin Pop
  """
3419 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3420 6b93ec9d Iustin Pop
3421 6b93ec9d Iustin Pop
  if multimaster:
3422 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3423 6b93ec9d Iustin Pop
      try:
3424 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3425 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3426 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3427 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3428 6b93ec9d Iustin Pop
  # needed primary mode
3429 6b93ec9d Iustin Pop
  for rd in bdevs:
3430 6b93ec9d Iustin Pop
    try:
3431 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3432 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3433 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3434 3c0cdc83 Michael Hanselmann
3435 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3436 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3437 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3438 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3439 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3440 3c0cdc83 Michael Hanselmann
3441 3c0cdc83 Michael Hanselmann
  def _Attach():
3442 6b93ec9d Iustin Pop
    all_connected = True
3443 3c0cdc83 Michael Hanselmann
3444 6b93ec9d Iustin Pop
    for rd in bdevs:
3445 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3446 3c0cdc83 Michael Hanselmann
3447 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3448 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3449 3c0cdc83 Michael Hanselmann
3450 6b93ec9d Iustin Pop
      if stats.is_standalone:
3451 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3452 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3453 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3454 6b93ec9d Iustin Pop
        try:
3455 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3456 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3457 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3458 3c0cdc83 Michael Hanselmann
3459 3c0cdc83 Michael Hanselmann
    if not all_connected:
3460 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3461 3c0cdc83 Michael Hanselmann
3462 3c0cdc83 Michael Hanselmann
  try:
3463 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3464 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3465 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3466 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3467 3c0cdc83 Michael Hanselmann
3468 6b93ec9d Iustin Pop
  if multimaster:
3469 6b93ec9d Iustin Pop
    # change to primary mode
3470 6b93ec9d Iustin Pop
    for rd in bdevs:
3471 d3da87b8 Iustin Pop
      try:
3472 d3da87b8 Iustin Pop
        rd.Open()
3473 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3474 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3475 6b93ec9d Iustin Pop
3476 6b93ec9d Iustin Pop
3477 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3478 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3479 6b93ec9d Iustin Pop

3480 6b93ec9d Iustin Pop
  """
3481 db8667b7 Iustin Pop
  def _helper(rd):
3482 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3483 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3484 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3485 db8667b7 Iustin Pop
    return stats
3486 db8667b7 Iustin Pop
3487 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3488 6b93ec9d Iustin Pop
3489 6b93ec9d Iustin Pop
  min_resync = 100
3490 6b93ec9d Iustin Pop
  alldone = True
3491 6b93ec9d Iustin Pop
  for rd in bdevs:
3492 db8667b7 Iustin Pop
    try:
3493 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3494 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3495 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3496 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3497 db8667b7 Iustin Pop
      # last check
3498 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3499 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3500 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3501 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3502 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3503 afdc3985 Iustin Pop
3504 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3505 6b93ec9d Iustin Pop
3506 6b93ec9d Iustin Pop
3507 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3508 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3509 c46b9782 Luca Bigliardi

3510 c46b9782 Luca Bigliardi
  """
3511 c46b9782 Luca Bigliardi
  try:
3512 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3513 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3514 c46b9782 Luca Bigliardi
    _Fail(str(err))
3515 c46b9782 Luca Bigliardi
3516 c46b9782 Luca Bigliardi
3517 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3518 f5118ade Iustin Pop
  """Hard-powercycle the node.
3519 f5118ade Iustin Pop

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

3523 f5118ade Iustin Pop
  """
3524 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3525 f5118ade Iustin Pop
  try:
3526 f5118ade Iustin Pop
    pid = os.fork()
3527 29921401 Iustin Pop
  except OSError:
3528 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3529 f5118ade Iustin Pop
    pid = 0
3530 f5118ade Iustin Pop
  if pid > 0:
3531 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3532 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3533 1af6ac0f Luca Bigliardi
  try:
3534 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3535 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3536 1af6ac0f Luca Bigliardi
    pass
3537 f5118ade Iustin Pop
  time.sleep(5)
3538 f5118ade Iustin Pop
  hyper.PowercycleNode()
3539 f5118ade Iustin Pop
3540 f5118ade Iustin Pop
3541 a8083063 Iustin Pop
class HooksRunner(object):
3542 a8083063 Iustin Pop
  """Hook runner.
3543 a8083063 Iustin Pop

3544 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3545 10c2650b Iustin Pop
  on the master side.
3546 a8083063 Iustin Pop

3547 a8083063 Iustin Pop
  """
3548 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3549 a8083063 Iustin Pop
    """Constructor for hooks runner.
3550 a8083063 Iustin Pop

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

3555 a8083063 Iustin Pop
    """
3556 a8083063 Iustin Pop
    if hooks_base_dir is None:
3557 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3558 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3559 fe267188 Iustin Pop
    # constant
3560 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3561 a8083063 Iustin Pop
3562 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3563 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3564 0fa481f5 Andrea Spadaccini

3565 0fa481f5 Andrea Spadaccini
    """
3566 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3567 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3568 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3569 0fa481f5 Andrea Spadaccini
    assert node == myself
3570 0fa481f5 Andrea Spadaccini
3571 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3572 0fa481f5 Andrea Spadaccini
3573 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3574 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3575 0fa481f5 Andrea Spadaccini
3576 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3577 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3578 a8083063 Iustin Pop

3579 10c2650b Iustin Pop
    @type hpath: str
3580 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3581 10c2650b Iustin Pop
        holds the scripts
3582 10c2650b Iustin Pop
    @type phase: str
3583 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3584 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3585 10c2650b Iustin Pop
    @type env: dict
3586 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3587 10c2650b Iustin Pop
    @rtype: list
3588 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3589 10c2650b Iustin Pop
      - script path
3590 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3591 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3592 10c2650b Iustin Pop
      - output of the script
3593 10c2650b Iustin Pop

3594 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3595 10c2650b Iustin Pop
        parameters
3596 a8083063 Iustin Pop

3597 a8083063 Iustin Pop
    """
3598 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3599 a8083063 Iustin Pop
      suffix = "pre"
3600 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3601 a8083063 Iustin Pop
      suffix = "post"
3602 a8083063 Iustin Pop
    else:
3603 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3604 3fb4f740 Iustin Pop
3605 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3606 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3607 6bb65e3a Guido Trotter
3608 6bb65e3a Guido Trotter
    results = []
3609 a9b7e346 Iustin Pop
3610 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3611 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3612 a9b7e346 Iustin Pop
      # warning at every operation
3613 a9b7e346 Iustin Pop
      return results
3614 a9b7e346 Iustin Pop
3615 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3616 a9b7e346 Iustin Pop
3617 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
3618 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3619 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3620 a8083063 Iustin Pop
        output = ""
3621 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3622 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3623 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3624 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3625 6bb65e3a Guido Trotter
        if runresult.failed:
3626 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3627 a8083063 Iustin Pop
        else:
3628 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3629 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3630 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3631 6bb65e3a Guido Trotter
3632 6bb65e3a Guido Trotter
    return results
3633 3f78eef2 Iustin Pop
3634 3f78eef2 Iustin Pop
3635 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3636 8d528b7c Iustin Pop
  """IAllocator runner.
3637 8d528b7c Iustin Pop

3638 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3639 8d528b7c Iustin Pop
  the master side.
3640 8d528b7c Iustin Pop

3641 8d528b7c Iustin Pop
  """
3642 7e950d31 Iustin Pop
  @staticmethod
3643 7e950d31 Iustin Pop
  def Run(name, idata):
3644 8d528b7c Iustin Pop
    """Run an iallocator script.
3645 8d528b7c Iustin Pop

3646 10c2650b Iustin Pop
    @type name: str
3647 10c2650b Iustin Pop
    @param name: the iallocator script name
3648 10c2650b Iustin Pop
    @type idata: str
3649 10c2650b Iustin Pop
    @param idata: the allocator input data
3650 10c2650b Iustin Pop

3651 10c2650b Iustin Pop
    @rtype: tuple
3652 87f5c298 Iustin Pop
    @return: two element tuple of:
3653 87f5c298 Iustin Pop
       - status
3654 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3655 8d528b7c Iustin Pop

3656 8d528b7c Iustin Pop
    """
3657 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3658 8d528b7c Iustin Pop
                                  os.path.isfile)
3659 8d528b7c Iustin Pop
    if alloc_script is None:
3660 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3661 8d528b7c Iustin Pop
3662 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3663 8d528b7c Iustin Pop
    try:
3664 8d528b7c Iustin Pop
      os.write(fd, idata)
3665 8d528b7c Iustin Pop
      os.close(fd)
3666 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3667 8d528b7c Iustin Pop
      if result.failed:
3668 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3669 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3670 8d528b7c Iustin Pop
    finally:
3671 8d528b7c Iustin Pop
      os.unlink(fin_name)
3672 8d528b7c Iustin Pop
3673 c26a6bd2 Iustin Pop
    return result.stdout
3674 8d528b7c Iustin Pop
3675 8d528b7c Iustin Pop
3676 3f78eef2 Iustin Pop
class DevCacheManager(object):
3677 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3678 3f78eef2 Iustin Pop

3679 3f78eef2 Iustin Pop
  """
3680 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3681 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
3682 3f78eef2 Iustin Pop
3683 3f78eef2 Iustin Pop
  @classmethod
3684 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3685 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3686 3f78eef2 Iustin Pop

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

3690 10c2650b Iustin Pop
    @type dev_path: str
3691 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3692 10c2650b Iustin Pop
    @rtype: str
3693 10c2650b Iustin Pop
    @return: the converted path name
3694 3f78eef2 Iustin Pop

3695 3f78eef2 Iustin Pop
    """
3696 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3697 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3698 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3699 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3700 3f78eef2 Iustin Pop
    return fpath
3701 3f78eef2 Iustin Pop
3702 3f78eef2 Iustin Pop
  @classmethod
3703 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3704 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3705 3f78eef2 Iustin Pop

3706 10c2650b Iustin Pop
    @type dev_path: str
3707 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3708 10c2650b Iustin Pop
    @type owner: str
3709 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3710 10c2650b Iustin Pop
    @type on_primary: bool
3711 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3712 10c2650b Iustin Pop
        node nor not
3713 10c2650b Iustin Pop
    @type iv_name: str
3714 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3715 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3716 10c2650b Iustin Pop

3717 10c2650b Iustin Pop
    @rtype: None
3718 10c2650b Iustin Pop

3719 3f78eef2 Iustin Pop
    """
3720 cf5a8306 Iustin Pop
    if dev_path is None:
3721 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3722 cf5a8306 Iustin Pop
      return
3723 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3724 3f78eef2 Iustin Pop
    if on_primary:
3725 3f78eef2 Iustin Pop
      state = "primary"
3726 3f78eef2 Iustin Pop
    else:
3727 3f78eef2 Iustin Pop
      state = "secondary"
3728 3f78eef2 Iustin Pop
    if iv_name is None:
3729 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3730 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3731 3f78eef2 Iustin Pop
    try:
3732 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3733 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3734 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3735 3f78eef2 Iustin Pop
3736 3f78eef2 Iustin Pop
  @classmethod
3737 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3738 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3739 3f78eef2 Iustin Pop

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

3743 10c2650b Iustin Pop
    @type dev_path: str
3744 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3745 10c2650b Iustin Pop

3746 10c2650b Iustin Pop
    @rtype: None
3747 10c2650b Iustin Pop

3748 3f78eef2 Iustin Pop
    """
3749 cf5a8306 Iustin Pop
    if dev_path is None:
3750 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3751 cf5a8306 Iustin Pop
      return
3752 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3753 3f78eef2 Iustin Pop
    try:
3754 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3755 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3756 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)