Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 72b35807

History | View | Annotate | Download (114.8 kB)

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

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

29 360b0dc2 Iustin Pop
"""
30 a8083063 Iustin Pop
31 b459a848 Andrea Spadaccini
# pylint: disable=E1103
32 6c881c52 Iustin Pop
33 6c881c52 Iustin Pop
# E1103: %s %r has no %r member (but some types could not be
34 6c881c52 Iustin Pop
# inferred), because the _TryOSFromDisk returns either (True, os_obj)
35 6c881c52 Iustin Pop
# or (False, "string") which confuses pylint
36 6c881c52 Iustin Pop
37 a8083063 Iustin Pop
38 a8083063 Iustin Pop
import os
39 a8083063 Iustin Pop
import os.path
40 a8083063 Iustin Pop
import shutil
41 a8083063 Iustin Pop
import time
42 a8083063 Iustin Pop
import stat
43 a8083063 Iustin Pop
import errno
44 a8083063 Iustin Pop
import re
45 b544cfe0 Iustin Pop
import random
46 18682bca Iustin Pop
import logging
47 3b9e6a30 Iustin Pop
import tempfile
48 12bce260 Michael Hanselmann
import zlib
49 12bce260 Michael Hanselmann
import base64
50 f81c4737 Michael Hanselmann
import signal
51 a8083063 Iustin Pop
52 a8083063 Iustin Pop
from ganeti import errors
53 a8083063 Iustin Pop
from ganeti import utils
54 a8083063 Iustin Pop
from ganeti import ssh
55 a8083063 Iustin Pop
from ganeti import hypervisor
56 a8083063 Iustin Pop
from ganeti import constants
57 a8083063 Iustin Pop
from ganeti import bdev
58 a8083063 Iustin Pop
from ganeti import objects
59 880478f8 Iustin Pop
from ganeti import ssconf
60 1651d116 Michael Hanselmann
from ganeti import serializer
61 a744b676 Manuel Franceschini
from ganeti import netutils
62 82b22e19 René Nussbaumer
from ganeti import runtime
63 0fa481f5 Andrea Spadaccini
from ganeti import mcpu
64 3ccd3243 Andrea Spadaccini
from ganeti import compat
65 710f30ec Michael Hanselmann
from ganeti import pathutils
66 cffbbae7 Michael Hanselmann
from ganeti import vcluster
67 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 ee045466 Michael Hanselmann
    pathutils.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 47130d50 Michael Hanselmann
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
651 47130d50 Michael Hanselmann
                                              what[constants.NV_FILELIST]))
652 47130d50 Michael Hanselmann
    result[constants.NV_FILELIST] = \
653 47130d50 Michael Hanselmann
      dict((vcluster.MakeVirtualPath(key), value)
654 47130d50 Michael Hanselmann
           for (key, value) in fingerprints.items())
655 25361b9a Iustin Pop
656 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
657 64c7b383 Michael Hanselmann
    (nodes, bynode) = what[constants.NV_NODELIST]
658 64c7b383 Michael Hanselmann
659 64c7b383 Michael Hanselmann
    # Add nodes from other groups (different for each node)
660 64c7b383 Michael Hanselmann
    try:
661 64c7b383 Michael Hanselmann
      nodes.extend(bynode[my_name])
662 64c7b383 Michael Hanselmann
    except KeyError:
663 64c7b383 Michael Hanselmann
      pass
664 64c7b383 Michael Hanselmann
665 64c7b383 Michael Hanselmann
    # Use a random order
666 64c7b383 Michael Hanselmann
    random.shuffle(nodes)
667 64c7b383 Michael Hanselmann
668 64c7b383 Michael Hanselmann
    # Try to contact all nodes
669 64c7b383 Michael Hanselmann
    val = {}
670 64c7b383 Michael Hanselmann
    for node in nodes:
671 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
672 a8083063 Iustin Pop
      if not success:
673 64c7b383 Michael Hanselmann
        val[node] = message
674 64c7b383 Michael Hanselmann
675 64c7b383 Michael Hanselmann
    result[constants.NV_NODELIST] = val
676 25361b9a Iustin Pop
677 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
678 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
679 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
680 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
681 9d4bfc96 Iustin Pop
      if name == my_name:
682 9d4bfc96 Iustin Pop
        my_pip = pip
683 9d4bfc96 Iustin Pop
        my_sip = sip
684 9d4bfc96 Iustin Pop
        break
685 9d4bfc96 Iustin Pop
    if not my_pip:
686 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
687 25361b9a Iustin Pop
                      " in the node list")
688 9d4bfc96 Iustin Pop
    else:
689 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
690 9d4bfc96 Iustin Pop
        fail = []
691 a744b676 Manuel Franceschini
        if not netutils.TcpPing(pip, port, source=my_pip):
692 9d4bfc96 Iustin Pop
          fail.append("primary")
693 9d4bfc96 Iustin Pop
        if sip != pip:
694 a744b676 Manuel Franceschini
          if not netutils.TcpPing(sip, port, source=my_sip):
695 9d4bfc96 Iustin Pop
            fail.append("secondary")
696 9d4bfc96 Iustin Pop
        if fail:
697 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
698 25361b9a Iustin Pop
                       " and ".join(fail))
699 25361b9a Iustin Pop
700 a3a5f850 Iustin Pop
  if constants.NV_MASTERIP in what:
701 a3a5f850 Iustin Pop
    # FIXME: add checks on incoming data structures (here and in the
702 a3a5f850 Iustin Pop
    # rest of the function)
703 a3a5f850 Iustin Pop
    master_name, master_ip = what[constants.NV_MASTERIP]
704 a3a5f850 Iustin Pop
    if master_name == my_name:
705 9769bb78 Manuel Franceschini
      source = constants.IP4_ADDRESS_LOCALHOST
706 a3a5f850 Iustin Pop
    else:
707 a3a5f850 Iustin Pop
      source = None
708 a744b676 Manuel Franceschini
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
709 5ae4945a Iustin Pop
                                                     source=source)
710 a3a5f850 Iustin Pop
711 17b0b812 Andrea Spadaccini
  if constants.NV_USERSCRIPTS in what:
712 17b0b812 Andrea Spadaccini
    result[constants.NV_USERSCRIPTS] = \
713 17b0b812 Andrea Spadaccini
      [script for script in what[constants.NV_USERSCRIPTS]
714 17b0b812 Andrea Spadaccini
       if not (os.path.exists(script) and os.access(script, os.X_OK))]
715 17b0b812 Andrea Spadaccini
716 16f41f24 René Nussbaumer
  if constants.NV_OOB_PATHS in what:
717 16f41f24 René Nussbaumer
    result[constants.NV_OOB_PATHS] = tmp = []
718 16f41f24 René Nussbaumer
    for path in what[constants.NV_OOB_PATHS]:
719 16f41f24 René Nussbaumer
      try:
720 16f41f24 René Nussbaumer
        st = os.stat(path)
721 16f41f24 René Nussbaumer
      except OSError, err:
722 16f41f24 René Nussbaumer
        tmp.append("error stating out of band helper: %s" % err)
723 16f41f24 René Nussbaumer
      else:
724 16f41f24 René Nussbaumer
        if stat.S_ISREG(st.st_mode):
725 16f41f24 René Nussbaumer
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
726 16f41f24 René Nussbaumer
            tmp.append(None)
727 16f41f24 René Nussbaumer
          else:
728 16f41f24 René Nussbaumer
            tmp.append("out of band helper %s is not executable" % path)
729 16f41f24 René Nussbaumer
        else:
730 16f41f24 René Nussbaumer
          tmp.append("out of band helper %s is not a file" % path)
731 16f41f24 René Nussbaumer
732 8964ee14 Iustin Pop
  if constants.NV_LVLIST in what and vm_capable:
733 ed904904 Iustin Pop
    try:
734 84d7e26b Dmitry Chernyak
      val = GetVolumeList(utils.ListVolumeGroups().keys())
735 ed904904 Iustin Pop
    except RPCFail, err:
736 ed904904 Iustin Pop
      val = str(err)
737 ed904904 Iustin Pop
    result[constants.NV_LVLIST] = val
738 25361b9a Iustin Pop
739 8964ee14 Iustin Pop
  if constants.NV_INSTANCELIST in what and vm_capable:
740 0cf5e7f5 Iustin Pop
    # GetInstanceList can fail
741 0cf5e7f5 Iustin Pop
    try:
742 0cf5e7f5 Iustin Pop
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
743 0cf5e7f5 Iustin Pop
    except RPCFail, err:
744 0cf5e7f5 Iustin Pop
      val = str(err)
745 0cf5e7f5 Iustin Pop
    result[constants.NV_INSTANCELIST] = val
746 25361b9a Iustin Pop
747 8964ee14 Iustin Pop
  if constants.NV_VGLIST in what and vm_capable:
748 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
749 25361b9a Iustin Pop
750 8964ee14 Iustin Pop
  if constants.NV_PVLIST in what and vm_capable:
751 d091393e Iustin Pop
    result[constants.NV_PVLIST] = \
752 d091393e Iustin Pop
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
753 d091393e Iustin Pop
                                   filter_allocatable=False)
754 d091393e Iustin Pop
755 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
756 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
757 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
758 25361b9a Iustin Pop
759 8964ee14 Iustin Pop
  if constants.NV_HVINFO in what and vm_capable:
760 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
761 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
762 9d4bfc96 Iustin Pop
763 8964ee14 Iustin Pop
  if constants.NV_DRBDLIST in what and vm_capable:
764 6d2e83d5 Iustin Pop
    try:
765 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
766 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
767 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
768 f6eaed12 Iustin Pop
      used_minors = str(err)
769 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
770 6d2e83d5 Iustin Pop
771 8964ee14 Iustin Pop
  if constants.NV_DRBDHELPER in what and vm_capable:
772 7ef40fbe Luca Bigliardi
    status = True
773 7ef40fbe Luca Bigliardi
    try:
774 7ef40fbe Luca Bigliardi
      payload = bdev.BaseDRBD.GetUsermodeHelper()
775 7ef40fbe Luca Bigliardi
    except errors.BlockDeviceError, err:
776 7ef40fbe Luca Bigliardi
      logging.error("Can't get DRBD usermode helper: %s", str(err))
777 7ef40fbe Luca Bigliardi
      status = False
778 7ef40fbe Luca Bigliardi
      payload = str(err)
779 7ef40fbe Luca Bigliardi
    result[constants.NV_DRBDHELPER] = (status, payload)
780 7ef40fbe Luca Bigliardi
781 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
782 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
783 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
784 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
785 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
786 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
787 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
788 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
789 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
790 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
791 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
792 313b2dd4 Michael Hanselmann
793 313b2dd4 Michael Hanselmann
  if constants.NV_TIME in what:
794 313b2dd4 Michael Hanselmann
    result[constants.NV_TIME] = utils.SplitTime(time.time())
795 313b2dd4 Michael Hanselmann
796 8964ee14 Iustin Pop
  if constants.NV_OSLIST in what and vm_capable:
797 b0d85178 Iustin Pop
    result[constants.NV_OSLIST] = DiagnoseOS()
798 b0d85178 Iustin Pop
799 20d317d4 Iustin Pop
  if constants.NV_BRIDGES in what and vm_capable:
800 20d317d4 Iustin Pop
    result[constants.NV_BRIDGES] = [bridge
801 20d317d4 Iustin Pop
                                    for bridge in what[constants.NV_BRIDGES]
802 20d317d4 Iustin Pop
                                    if not utils.BridgeExists(bridge)]
803 23e3c9b7 Michael Hanselmann
804 72b35807 Michael Hanselmann
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
805 72b35807 Michael Hanselmann
    result[constants.NV_FILE_STORAGE_PATHS] = \
806 72b35807 Michael Hanselmann
      bdev.ComputeWrongFileStoragePaths()
807 72b35807 Michael Hanselmann
808 c26a6bd2 Iustin Pop
  return result
809 a8083063 Iustin Pop
810 a8083063 Iustin Pop
811 2be7273c Apollon Oikonomopoulos
def GetBlockDevSizes(devices):
812 2be7273c Apollon Oikonomopoulos
  """Return the size of the given block devices
813 2be7273c Apollon Oikonomopoulos

814 2be7273c Apollon Oikonomopoulos
  @type devices: list
815 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
816 2be7273c Apollon Oikonomopoulos
  @rtype: dict
817 2be7273c Apollon Oikonomopoulos
  @return:
818 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
819 2be7273c Apollon Oikonomopoulos
    size in MiB.
820 2be7273c Apollon Oikonomopoulos

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

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

852 84d7e26b Dmitry Chernyak
  @type vg_names: list
853 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
854 397693d3 Iustin Pop
      empty for all volume groups
855 10c2650b Iustin Pop
  @rtype: dict
856 10c2650b Iustin Pop
  @return:
857 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
858 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
859 10c2650b Iustin Pop

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

862 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
863 10c2650b Iustin Pop
      details.
864 a8083063 Iustin Pop

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

898 10c2650b Iustin Pop
  @rtype: dict
899 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
900 10c2650b Iustin Pop
      size of the volume
901 a8083063 Iustin Pop

902 a8083063 Iustin Pop
  """
903 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
904 a8083063 Iustin Pop
905 a8083063 Iustin Pop
906 dcb93971 Michael Hanselmann
def NodeVolumes():
907 dcb93971 Michael Hanselmann
  """List all volumes on this node.
908 dcb93971 Michael Hanselmann

909 10c2650b Iustin Pop
  @rtype: list
910 10c2650b Iustin Pop
  @return:
911 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
912 10c2650b Iustin Pop
      - name: the logical volume name,
913 10c2650b Iustin Pop
      - size: the size of the logical volume
914 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
915 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
916 10c2650b Iustin Pop

917 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
918 10c2650b Iustin Pop
    error.
919 10c2650b Iustin Pop

920 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
921 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
922 10c2650b Iustin Pop
    multiple times.
923 10c2650b Iustin Pop

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

955 b1206984 Iustin Pop
  @rtype: boolean
956 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
957 a8083063 Iustin Pop

958 a8083063 Iustin Pop
  """
959 35c0c8da Iustin Pop
  missing = []
960 a8083063 Iustin Pop
  for bridge in bridges_list:
961 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
962 35c0c8da Iustin Pop
      missing.append(bridge)
963 a8083063 Iustin Pop
964 35c0c8da Iustin Pop
  if missing:
965 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
966 35c0c8da Iustin Pop
967 a8083063 Iustin Pop
968 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
969 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
970 a8083063 Iustin Pop

971 e69d05fd Iustin Pop
  @type hypervisor_list: list
972 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
973 e69d05fd Iustin Pop

974 e69d05fd Iustin Pop
  @rtype: list
975 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
976 10c2650b Iustin Pop
    - instance1.example.com
977 10c2650b Iustin Pop
    - instance2.example.com
978 a8083063 Iustin Pop

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

995 e69d05fd Iustin Pop
  @type instance: string
996 e69d05fd Iustin Pop
  @param instance: the instance name
997 e69d05fd Iustin Pop
  @type hname: string
998 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
999 a8083063 Iustin Pop

1000 e69d05fd Iustin Pop
  @rtype: dict
1001 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1002 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1003 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1004 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1005 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1006 a8083063 Iustin Pop

1007 098c0958 Michael Hanselmann
  """
1008 a8083063 Iustin Pop
  output = {}
1009 a8083063 Iustin Pop
1010 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1011 a8083063 Iustin Pop
  if iinfo is not None:
1012 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1013 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1014 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1015 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1016 a8083063 Iustin Pop
1017 c26a6bd2 Iustin Pop
  return output
1018 a8083063 Iustin Pop
1019 a8083063 Iustin Pop
1020 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1021 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
1022 56e7640c Iustin Pop

1023 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1024 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1025 56e7640c Iustin Pop

1026 56e7640c Iustin Pop
  @rtype: tuple
1027 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1028 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1029 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1030 56e7640c Iustin Pop

1031 56e7640c Iustin Pop
  """
1032 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1033 afdc3985 Iustin Pop
  iname = instance.name
1034 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
1035 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1036 56e7640c Iustin Pop
1037 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1038 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1039 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1040 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1041 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1042 56e7640c Iustin Pop
1043 56e7640c Iustin Pop
1044 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
1045 a8083063 Iustin Pop
  """Gather data about all instances.
1046 a8083063 Iustin Pop

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

1051 e69d05fd Iustin Pop
  @type hypervisor_list: list
1052 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1053 e69d05fd Iustin Pop

1054 955db481 Guido Trotter
  @rtype: dict
1055 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1056 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1057 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1058 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1059 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1060 a8083063 Iustin Pop

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

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

1093 81a3406c Iustin Pop
  @type kind: string
1094 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1095 81a3406c Iustin Pop
  @type os_name: string
1096 81a3406c Iustin Pop
  @param os_name: the os name
1097 81a3406c Iustin Pop
  @type instance: string
1098 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1099 6aa7a354 Iustin Pop
  @type component: string or None
1100 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1101 6aa7a354 Iustin Pop
      transferred
1102 81a3406c Iustin Pop

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

1118 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1119 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1120 e557bae9 Guido Trotter
  @type reinstall: boolean
1121 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1122 4a0e011f Iustin Pop
  @type debug: integer
1123 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1124 c26a6bd2 Iustin Pop
  @rtype: None
1125 a8083063 Iustin Pop

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

1150 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1151 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1152 d15a9ad3 Guido Trotter
  @type old_name: string
1153 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1154 4a0e011f Iustin Pop
  @type debug: integer
1155 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1156 10c2650b Iustin Pop
  @rtype: boolean
1157 10c2650b Iustin Pop
  @return: the success of the operation
1158 decd5f45 Iustin Pop

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

1188 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1189 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1190 9332fd8a Iustin Pop

1191 9332fd8a Iustin Pop

1192 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1193 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1194 5282084b Iustin Pop
  @param idx: the disk index
1195 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1196 9332fd8a Iustin Pop

1197 9332fd8a Iustin Pop
  """
1198 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1199 9332fd8a Iustin Pop
  try:
1200 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1201 5282084b Iustin Pop
  except OSError, err:
1202 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1203 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1204 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1205 9332fd8a Iustin Pop
        os.remove(link_name)
1206 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1207 9332fd8a Iustin Pop
    else:
1208 9332fd8a Iustin Pop
      raise
1209 9332fd8a Iustin Pop
1210 9332fd8a Iustin Pop
  return link_name
1211 9332fd8a Iustin Pop
1212 9332fd8a Iustin Pop
1213 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1214 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1215 3c9c571d Iustin Pop

1216 3c9c571d Iustin Pop
  """
1217 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1218 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1219 5282084b Iustin Pop
    if os.path.islink(link_name):
1220 3c9c571d Iustin Pop
      try:
1221 03dfa658 Iustin Pop
        os.remove(link_name)
1222 03dfa658 Iustin Pop
      except OSError:
1223 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1224 3c9c571d Iustin Pop
1225 3c9c571d Iustin Pop
1226 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1227 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1228 a8083063 Iustin Pop

1229 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1230 a8083063 Iustin Pop
  devices must be already assembled.
1231 a8083063 Iustin Pop

1232 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1233 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1234 069cfbf1 Iustin Pop
  @rtype: list
1235 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1236 10c2650b Iustin Pop

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

1259 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1260 e69d05fd Iustin Pop
  @param instance: the instance object
1261 323f9095 Stephen Shirley
  @type startup_paused: bool
1262 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1263 c26a6bd2 Iustin Pop
  @rtype: None
1264 a8083063 Iustin Pop

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

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

1288 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1289 e69d05fd Iustin Pop
  @param instance: the instance object
1290 6263189c Guido Trotter
  @type timeout: integer
1291 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1292 c26a6bd2 Iustin Pop
  @rtype: None
1293 a8083063 Iustin Pop

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

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

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

1397 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1398 ebe466d8 Guido Trotter
  @param instance: the instance object
1399 ebe466d8 Guido Trotter
  @type memory: int
1400 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1401 ebe466d8 Guido Trotter
  @rtype: None
1402 ebe466d8 Guido Trotter

1403 ebe466d8 Guido Trotter
  """
1404 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1405 ebe466d8 Guido Trotter
  running = hyper.ListInstances()
1406 ebe466d8 Guido Trotter
  if instance.name not in running:
1407 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1408 ebe466d8 Guido Trotter
    return
1409 ebe466d8 Guido Trotter
  try:
1410 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1411 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1412 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1413 ebe466d8 Guido Trotter
1414 ebe466d8 Guido Trotter
1415 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1416 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1417 6906a9d8 Guido Trotter

1418 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1419 6906a9d8 Guido Trotter
  @param instance: the instance definition
1420 6906a9d8 Guido Trotter

1421 6906a9d8 Guido Trotter
  """
1422 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1423 cd42d0ad Guido Trotter
  try:
1424 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1425 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1426 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1427 c26a6bd2 Iustin Pop
  return info
1428 6906a9d8 Guido Trotter
1429 6906a9d8 Guido Trotter
1430 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1431 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1432 6906a9d8 Guido Trotter

1433 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1434 6906a9d8 Guido Trotter
  @param instance: the instance definition
1435 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1436 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1437 6906a9d8 Guido Trotter
  @type target: string
1438 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1439 6906a9d8 Guido Trotter

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

1462 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1463 6906a9d8 Guido Trotter
  @param instance: the instance definition
1464 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1465 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1466 6906a9d8 Guido Trotter
  @type success: boolean
1467 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1468 6906a9d8 Guido Trotter

1469 6906a9d8 Guido Trotter
  """
1470 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1471 cd42d0ad Guido Trotter
  try:
1472 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1473 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1474 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1475 6906a9d8 Guido Trotter
1476 6906a9d8 Guido Trotter
1477 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1478 2a10865c Iustin Pop
  """Migrates an instance to another node.
1479 2a10865c Iustin Pop

1480 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1481 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1482 9f0e6b37 Iustin Pop
  @type target: string
1483 9f0e6b37 Iustin Pop
  @param target: the target node name
1484 9f0e6b37 Iustin Pop
  @type live: boolean
1485 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1486 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1487 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1488 9f0e6b37 Iustin Pop

1489 2a10865c Iustin Pop
  """
1490 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1491 2a10865c Iustin Pop
1492 2a10865c Iustin Pop
  try:
1493 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1494 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1495 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1496 2a10865c Iustin Pop
1497 2a10865c Iustin Pop
1498 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1499 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1500 6a1434d7 Andrea Spadaccini

1501 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1502 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1503 6a1434d7 Andrea Spadaccini
  @type success: bool
1504 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1505 6a1434d7 Andrea Spadaccini
  @type live: bool
1506 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1507 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1508 6a1434d7 Andrea Spadaccini

1509 6a1434d7 Andrea Spadaccini
  """
1510 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1511 6a1434d7 Andrea Spadaccini
1512 6a1434d7 Andrea Spadaccini
  try:
1513 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1514 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1515 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1516 6a1434d7 Andrea Spadaccini
          exc=True)
1517 6a1434d7 Andrea Spadaccini
1518 6a1434d7 Andrea Spadaccini
1519 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1520 6a1434d7 Andrea Spadaccini
  """Get the migration status
1521 6a1434d7 Andrea Spadaccini

1522 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1523 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1524 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1525 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1526 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1527 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1528 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1529 6a1434d7 Andrea Spadaccini

1530 6a1434d7 Andrea Spadaccini
  """
1531 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1532 6a1434d7 Andrea Spadaccini
  try:
1533 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1534 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1535 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1536 6a1434d7 Andrea Spadaccini
1537 6a1434d7 Andrea Spadaccini
1538 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1539 a8083063 Iustin Pop
  """Creates a block device for an instance.
1540 a8083063 Iustin Pop

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

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

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

1604 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1605 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1606 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1607 69dd363f René Nussbaumer

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

1627 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1628 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1629 da63bb4e René Nussbaumer
  @type offset: int
1630 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1631 da63bb4e René Nussbaumer
  @type size: int
1632 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1633 69dd363f René Nussbaumer

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

1659 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1660 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1661 5119c79e René Nussbaumer
  @type pause: bool
1662 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1663 5119c79e René Nussbaumer

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

1694 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1695 10c2650b Iustin Pop

1696 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1697 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1698 10c2650b Iustin Pop
  @rtype: boolean
1699 10c2650b Iustin Pop
  @return: the success of the operation
1700 a8083063 Iustin Pop

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

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

1734 10c2650b Iustin Pop
  @note: this function is called recursively.
1735 a8083063 Iustin Pop

1736 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1737 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1738 10c2650b Iustin Pop
  @type owner: str
1739 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1740 10c2650b Iustin Pop
  @type as_primary: boolean
1741 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1742 10c2650b Iustin Pop
      read/write
1743 a8083063 Iustin Pop

1744 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1745 10c2650b Iustin Pop
      was assembled)
1746 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1747 10c2650b Iustin Pop
      during the activation of the children or the device
1748 10c2650b Iustin Pop
      itself
1749 a8083063 Iustin Pop

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

1785 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1786 a8083063 Iustin Pop

1787 b1206984 Iustin Pop
  @rtype: str or boolean
1788 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1789 b1206984 Iustin Pop
      C{True} for secondary nodes
1790 a8083063 Iustin Pop

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

1810 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1811 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1812 c41eea6e Iustin Pop
  shutdown.
1813 a8083063 Iustin Pop

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

1818 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1819 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1820 10c2650b Iustin Pop
      shutdown
1821 c26a6bd2 Iustin Pop
  @rtype: None
1822 10c2650b Iustin Pop

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

1848 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1849 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1850 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1851 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1852 c26a6bd2 Iustin Pop
  @rtype: None
1853 10c2650b Iustin Pop

1854 a8083063 Iustin Pop
  """
1855 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1856 153d9724 Iustin Pop
  if parent_bdev is None:
1857 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1858 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1859 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1860 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1861 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1862 a8083063 Iustin Pop
1863 a8083063 Iustin Pop
1864 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1865 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1866 a8083063 Iustin Pop

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

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

1896 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1897 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1898 10c2650b Iustin Pop
  @rtype: disk
1899 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1900 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1901 10c2650b Iustin Pop
      found
1902 a8083063 Iustin Pop

1903 a8083063 Iustin Pop
  """
1904 a8083063 Iustin Pop
  stats = []
1905 a8083063 Iustin Pop
  for dsk in disks:
1906 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1907 a8083063 Iustin Pop
    if rbd is None:
1908 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1909 96acbc09 Michael Hanselmann
1910 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1911 96acbc09 Michael Hanselmann
1912 c26a6bd2 Iustin Pop
  return stats
1913 a8083063 Iustin Pop
1914 a8083063 Iustin Pop
1915 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1916 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1917 c6a9dffa Michael Hanselmann

1918 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1919 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1920 c6a9dffa Michael Hanselmann
  @rtype: disk
1921 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1922 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
1923 c6a9dffa Michael Hanselmann
    otherwise
1924 c6a9dffa Michael Hanselmann

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

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

1951 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1952 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1953 a8083063 Iustin Pop

1954 10c2650b Iustin Pop
  @return: None if the device can't be found,
1955 10c2650b Iustin Pop
      otherwise the device instance
1956 a8083063 Iustin Pop

1957 a8083063 Iustin Pop
  """
1958 a8083063 Iustin Pop
  children = []
1959 a8083063 Iustin Pop
  if disk.children:
1960 a8083063 Iustin Pop
    for chdisk in disk.children:
1961 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1962 a8083063 Iustin Pop
1963 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
1964 a8083063 Iustin Pop
1965 a8083063 Iustin Pop
1966 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1967 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1968 f2e07bb4 Michael Hanselmann

1969 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1970 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1971 f2e07bb4 Michael Hanselmann

1972 f2e07bb4 Michael Hanselmann
  """
1973 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1974 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1975 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1976 f2e07bb4 Michael Hanselmann
1977 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1978 f2e07bb4 Michael Hanselmann
1979 f2e07bb4 Michael Hanselmann
  return real_disk
1980 f2e07bb4 Michael Hanselmann
1981 f2e07bb4 Michael Hanselmann
1982 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1983 a8083063 Iustin Pop
  """Check if a device is activated.
1984 a8083063 Iustin Pop

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

1987 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1988 10c2650b Iustin Pop
  @param disk: the disk to find
1989 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1990 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1991 96acbc09 Michael Hanselmann
           information
1992 a8083063 Iustin Pop

1993 a8083063 Iustin Pop
  """
1994 23829f6f Iustin Pop
  try:
1995 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1996 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1997 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1998 96acbc09 Michael Hanselmann
1999 a8083063 Iustin Pop
  if rbd is None:
2000 c26a6bd2 Iustin Pop
    return None
2001 96acbc09 Michael Hanselmann
2002 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2003 a8083063 Iustin Pop
2004 a8083063 Iustin Pop
2005 968a7623 Iustin Pop
def BlockdevGetsize(disks):
2006 968a7623 Iustin Pop
  """Computes the size of the given disks.
2007 968a7623 Iustin Pop

2008 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2009 968a7623 Iustin Pop

2010 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2011 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2012 968a7623 Iustin Pop
  @rtype: list
2013 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2014 968a7623 Iustin Pop
      otherwise the size
2015 968a7623 Iustin Pop

2016 968a7623 Iustin Pop
  """
2017 968a7623 Iustin Pop
  result = []
2018 968a7623 Iustin Pop
  for cf in disks:
2019 968a7623 Iustin Pop
    try:
2020 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2021 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2022 968a7623 Iustin Pop
      result.append(None)
2023 968a7623 Iustin Pop
      continue
2024 968a7623 Iustin Pop
    if rbd is None:
2025 968a7623 Iustin Pop
      result.append(None)
2026 968a7623 Iustin Pop
    else:
2027 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
2028 968a7623 Iustin Pop
  return result
2029 968a7623 Iustin Pop
2030 968a7623 Iustin Pop
2031 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2032 858f3d18 Iustin Pop
  """Export a block device to a remote node.
2033 858f3d18 Iustin Pop

2034 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
2035 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
2036 858f3d18 Iustin Pop
  @type dest_node: str
2037 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
2038 858f3d18 Iustin Pop
  @type dest_path: str
2039 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
2040 858f3d18 Iustin Pop
  @type cluster_name: str
2041 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2042 858f3d18 Iustin Pop
  @rtype: None
2043 858f3d18 Iustin Pop

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

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

2081 10c2650b Iustin Pop
  @type file_name: str
2082 10c2650b Iustin Pop
  @param file_name: the target file name
2083 10c2650b Iustin Pop
  @type data: str
2084 10c2650b Iustin Pop
  @param data: the new contents of the file
2085 10c2650b Iustin Pop
  @type mode: int
2086 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2087 9a914f7a René Nussbaumer
  @type uid: string
2088 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2089 9a914f7a René Nussbaumer
  @type gid: string
2090 9a914f7a René Nussbaumer
  @param gid: the group of the file
2091 10c2650b Iustin Pop
  @type atime: float
2092 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2093 10c2650b Iustin Pop
  @type mtime: float
2094 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2095 c26a6bd2 Iustin Pop
  @rtype: None
2096 10c2650b Iustin Pop

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

2124 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2125 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2126 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2127 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2128 b2f29800 René Nussbaumer

2129 b2f29800 René Nussbaumer
  @return: stdout
2130 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2131 b2f29800 René Nussbaumer

2132 b2f29800 René Nussbaumer
  """
2133 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2134 b2f29800 René Nussbaumer
2135 b2f29800 René Nussbaumer
  if result.failed:
2136 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2137 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2138 b2f29800 René Nussbaumer
2139 b2f29800 René Nussbaumer
  return result.stdout
2140 b2f29800 René Nussbaumer
2141 b2f29800 René Nussbaumer
2142 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2143 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2144 a8083063 Iustin Pop

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

2148 10c2650b Iustin Pop
  @type os_dir: str
2149 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2150 8e70b181 Iustin Pop
  @rtype: tuple
2151 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2152 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2153 a8083063 Iustin Pop

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

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

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

2233 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2234 8e70b181 Iustin Pop
  valid OS name.
2235 a8083063 Iustin Pop

2236 8ee4dc80 Guido Trotter
  @type base_dir: string
2237 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2238 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2239 255dcebd Iustin Pop
  @rtype: tuple
2240 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2241 255dcebd Iustin Pop
      or error message
2242 7c3d51d4 Guido Trotter

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

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

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

2340 255dcebd Iustin Pop
  @type base_dir: string
2341 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2342 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2343 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2344 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2345 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2346 255dcebd Iustin Pop

2347 255dcebd Iustin Pop
  """
2348 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2349 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2350 255dcebd Iustin Pop
2351 255dcebd Iustin Pop
  if not status:
2352 255dcebd Iustin Pop
    _Fail(payload)
2353 a8083063 Iustin Pop
2354 255dcebd Iustin Pop
  return payload
2355 a8083063 Iustin Pop
2356 a8083063 Iustin Pop
2357 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2358 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2359 2266edb2 Guido Trotter

2360 a025e535 Vitaly Kuznetsov
  @type os_name: str
2361 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2362 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2363 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2364 1bdcbbab Iustin Pop
  @type os_params: dict
2365 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2366 2266edb2 Guido Trotter
  @type debug: integer
2367 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2368 2266edb2 Guido Trotter
  @rtype: dict
2369 2266edb2 Guido Trotter
  @return: dict of environment variables
2370 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2371 10c2650b Iustin Pop
      cannot be found
2372 2266edb2 Guido Trotter

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

2405 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2406 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2407 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2408 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2409 efaa9b06 Iustin Pop
  @type debug: integer
2410 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2411 efaa9b06 Iustin Pop
  @rtype: dict
2412 efaa9b06 Iustin Pop
  @return: dict of environment variables
2413 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2414 efaa9b06 Iustin Pop
      cannot be found
2415 efaa9b06 Iustin Pop

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

2467 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2468 10c2650b Iustin Pop
  first ones to resize.
2469 594609c0 Iustin Pop

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

2484 594609c0 Iustin Pop
  """
2485 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2486 594609c0 Iustin Pop
  if r_dev is None:
2487 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2488 594609c0 Iustin Pop
2489 594609c0 Iustin Pop
  try:
2490 cad0723b Iustin Pop
    r_dev.Grow(amount, dryrun, backingstore)
2491 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2492 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2493 594609c0 Iustin Pop
2494 594609c0 Iustin Pop
2495 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2496 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2497 a8083063 Iustin Pop

2498 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2499 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2500 a8083063 Iustin Pop

2501 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2502 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2503 e9e9263d Guido Trotter
  @rtype: string
2504 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2505 a8083063 Iustin Pop

2506 098c0958 Michael Hanselmann
  """
2507 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2508 433c63aa Iustin Pop
    if not disk.children:
2509 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2510 433c63aa Iustin Pop
            disk.unique_id)
2511 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2512 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2513 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2514 a8083063 Iustin Pop
    if r_dev is not None:
2515 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2516 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2517 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2518 a8083063 Iustin Pop
    else:
2519 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2520 a8083063 Iustin Pop
  else:
2521 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2522 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2523 a8083063 Iustin Pop
2524 a8083063 Iustin Pop
2525 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
2526 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
2527 48e175a2 Iustin Pop

2528 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
2529 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
2530 48e175a2 Iustin Pop
  for example after renames.
2531 48e175a2 Iustin Pop

2532 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
2533 48e175a2 Iustin Pop
  @param disk: the disk to be grown
2534 48e175a2 Iustin Pop
  @type info: string
2535 48e175a2 Iustin Pop
  @param info: new 'info' metadata
2536 48e175a2 Iustin Pop
  @rtype: (status, result)
2537 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2538 48e175a2 Iustin Pop
      the errors message if status is False
2539 48e175a2 Iustin Pop

2540 48e175a2 Iustin Pop
  """
2541 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2542 48e175a2 Iustin Pop
  if r_dev is None:
2543 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2544 48e175a2 Iustin Pop
2545 48e175a2 Iustin Pop
  try:
2546 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
2547 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
2548 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
2549 48e175a2 Iustin Pop
2550 48e175a2 Iustin Pop
2551 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2552 a8083063 Iustin Pop
  """Write out the export configuration information.
2553 a8083063 Iustin Pop

2554 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2555 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2556 10c2650b Iustin Pop
      saving configuration
2557 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2558 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2559 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2560 a8083063 Iustin Pop

2561 c26a6bd2 Iustin Pop
  @rtype: None
2562 a8083063 Iustin Pop

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

2640 10c2650b Iustin Pop
  @type dest: str
2641 10c2650b Iustin Pop
  @param dest: directory containing the export
2642 a8083063 Iustin Pop

2643 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2644 10c2650b Iustin Pop
  @return: a serializable config file containing the
2645 10c2650b Iustin Pop
      export info
2646 a8083063 Iustin Pop

2647 a8083063 Iustin Pop
  """
2648 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2649 a8083063 Iustin Pop
2650 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2651 a8083063 Iustin Pop
  config.read(cff)
2652 a8083063 Iustin Pop
2653 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2654 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2655 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2656 a8083063 Iustin Pop
2657 c26a6bd2 Iustin Pop
  return config.Dumps()
2658 a8083063 Iustin Pop
2659 a8083063 Iustin Pop
2660 a8083063 Iustin Pop
def ListExports():
2661 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2662 098c0958 Michael Hanselmann

2663 10c2650b Iustin Pop
  @rtype: list
2664 10c2650b Iustin Pop
  @return: list of the exports
2665 10c2650b Iustin Pop

2666 a8083063 Iustin Pop
  """
2667 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
2668 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2669 a8083063 Iustin Pop
  else:
2670 afdc3985 Iustin Pop
    _Fail("No exports directory")
2671 a8083063 Iustin Pop
2672 a8083063 Iustin Pop
2673 a8083063 Iustin Pop
def RemoveExport(export):
2674 a8083063 Iustin Pop
  """Remove an existing export from the node.
2675 a8083063 Iustin Pop

2676 10c2650b Iustin Pop
  @type export: str
2677 10c2650b Iustin Pop
  @param export: the name of the export to remove
2678 c26a6bd2 Iustin Pop
  @rtype: None
2679 a8083063 Iustin Pop

2680 098c0958 Michael Hanselmann
  """
2681 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2682 a8083063 Iustin Pop
2683 35fbcd11 Iustin Pop
  try:
2684 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2685 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2686 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2687 a8083063 Iustin Pop
2688 a8083063 Iustin Pop
2689 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2690 f3e513ad Iustin Pop
  """Rename a list of block devices.
2691 f3e513ad Iustin Pop

2692 10c2650b Iustin Pop
  @type devlist: list of tuples
2693 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2694 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2695 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2696 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2697 10c2650b Iustin Pop
      rename it to
2698 10c2650b Iustin Pop
  @rtype: boolean
2699 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2700 f3e513ad Iustin Pop

2701 f3e513ad Iustin Pop
  """
2702 6b5e3f70 Iustin Pop
  msgs = []
2703 f3e513ad Iustin Pop
  result = True
2704 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2705 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2706 f3e513ad Iustin Pop
    if dev is None:
2707 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2708 f3e513ad Iustin Pop
      result = False
2709 f3e513ad Iustin Pop
      continue
2710 f3e513ad Iustin Pop
    try:
2711 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2712 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2713 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2714 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2715 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2716 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2717 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2718 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2719 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2720 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2721 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2722 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2723 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2724 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2725 f3e513ad Iustin Pop
      result = False
2726 afdc3985 Iustin Pop
  if not result:
2727 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2728 f3e513ad Iustin Pop
2729 f3e513ad Iustin Pop
2730 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2731 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2732 778b75bb Manuel Franceschini

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

2737 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2738 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2739 d61cbe76 Iustin Pop

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

2742 778b75bb Manuel Franceschini
  """
2743 63a3d8f7 Michael Hanselmann
  if not (constants.ENABLE_FILE_STORAGE or
2744 63a3d8f7 Michael Hanselmann
          constants.ENABLE_SHARED_FILE_STORAGE):
2745 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2746 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2747 4b97f902 Apollon Oikonomopoulos
  fs_dir = os.path.normpath(fs_dir)
2748 4b97f902 Apollon Oikonomopoulos
  base_fstore = cfg.GetFileStorageDir()
2749 4b97f902 Apollon Oikonomopoulos
  base_shared = cfg.GetSharedFileStorageDir()
2750 cf00dba0 René Nussbaumer
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2751 cf00dba0 René Nussbaumer
          utils.IsBelowDir(base_shared, fs_dir)):
2752 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2753 4b97f902 Apollon Oikonomopoulos
          " storage directory '%s' or shared storage directory '%s'",
2754 4b97f902 Apollon Oikonomopoulos
          fs_dir, base_fstore, base_shared)
2755 4b97f902 Apollon Oikonomopoulos
  return fs_dir
2756 778b75bb Manuel Franceschini
2757 778b75bb Manuel Franceschini
2758 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2759 778b75bb Manuel Franceschini
  """Create file storage directory.
2760 778b75bb Manuel Franceschini

2761 b1206984 Iustin Pop
  @type file_storage_dir: str
2762 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2763 778b75bb Manuel Franceschini

2764 b1206984 Iustin Pop
  @rtype: tuple
2765 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2766 b1206984 Iustin Pop
      creation was successful or not
2767 778b75bb Manuel Franceschini

2768 778b75bb Manuel Franceschini
  """
2769 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2770 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2771 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2772 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2773 b2b8bcce Iustin Pop
            file_storage_dir)
2774 778b75bb Manuel Franceschini
  else:
2775 b2b8bcce Iustin Pop
    try:
2776 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2777 b2b8bcce Iustin Pop
    except OSError, err:
2778 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2779 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2780 778b75bb Manuel Franceschini
2781 778b75bb Manuel Franceschini
2782 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2783 778b75bb Manuel Franceschini
  """Remove file storage directory.
2784 778b75bb Manuel Franceschini

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

2787 10c2650b Iustin Pop
  @type file_storage_dir: str
2788 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2789 10c2650b Iustin Pop
  @rtype: tuple (success,)
2790 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2791 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2792 778b75bb Manuel Franceschini

2793 778b75bb Manuel Franceschini
  """
2794 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2795 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2796 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2797 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2798 b2b8bcce Iustin Pop
            file_storage_dir)
2799 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2800 b2b8bcce Iustin Pop
    try:
2801 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2802 b2b8bcce Iustin Pop
    except OSError, err:
2803 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2804 b2b8bcce Iustin Pop
            file_storage_dir, err)
2805 b2b8bcce Iustin Pop
2806 778b75bb Manuel Franceschini
2807 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2808 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2809 778b75bb Manuel Franceschini

2810 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2811 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2812 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2813 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2814 10c2650b Iustin Pop
  @rtype: tuple (success,)
2815 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2816 10c2650b Iustin Pop
      whether the operation was successful
2817 778b75bb Manuel Franceschini

2818 778b75bb Manuel Franceschini
  """
2819 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2820 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2821 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2822 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2823 b2b8bcce Iustin Pop
      try:
2824 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2825 b2b8bcce Iustin Pop
      except OSError, err:
2826 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2827 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2828 778b75bb Manuel Franceschini
    else:
2829 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2830 b2b8bcce Iustin Pop
            old_file_storage_dir)
2831 b2b8bcce Iustin Pop
  else:
2832 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2833 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2834 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2835 778b75bb Manuel Franceschini
2836 778b75bb Manuel Franceschini
2837 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2838 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2839 ca52cdeb Michael Hanselmann

2840 10c2650b Iustin Pop
  @type file_name: str
2841 10c2650b Iustin Pop
  @param file_name: the file name we should check
2842 c8457ce7 Iustin Pop
  @rtype: None
2843 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2844 10c2650b Iustin Pop

2845 ca52cdeb Michael Hanselmann
  """
2846 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2847 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2848 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2849 dc31eae3 Michael Hanselmann
2850 dc31eae3 Michael Hanselmann
2851 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2852 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2853 dc31eae3 Michael Hanselmann

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

2857 10c2650b Iustin Pop
  @type file_name: str
2858 10c2650b Iustin Pop
  @param file_name: the job file name
2859 10c2650b Iustin Pop
  @type content: str
2860 10c2650b Iustin Pop
  @param content: the new job contents
2861 10c2650b Iustin Pop
  @rtype: boolean
2862 10c2650b Iustin Pop
  @return: the success of the operation
2863 10c2650b Iustin Pop

2864 dc31eae3 Michael Hanselmann
  """
2865 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2866 cffbbae7 Michael Hanselmann
2867 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2868 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2869 ca52cdeb Michael Hanselmann
2870 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2871 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2872 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2873 ca52cdeb Michael Hanselmann
2874 ca52cdeb Michael Hanselmann
2875 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2876 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2877 af5ebcb1 Michael Hanselmann

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

2880 10c2650b Iustin Pop
  @type old: str
2881 10c2650b Iustin Pop
  @param old: the old (actual) file name
2882 10c2650b Iustin Pop
  @type new: str
2883 10c2650b Iustin Pop
  @param new: the desired file name
2884 c8457ce7 Iustin Pop
  @rtype: tuple
2885 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2886 10c2650b Iustin Pop

2887 af5ebcb1 Michael Hanselmann
  """
2888 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
2889 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
2890 cffbbae7 Michael Hanselmann
2891 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2892 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2893 af5ebcb1 Michael Hanselmann
2894 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
2895 8e5a705d René Nussbaumer
2896 8e5a705d René Nussbaumer
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2897 8e5a705d René Nussbaumer
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2898 af5ebcb1 Michael Hanselmann
2899 af5ebcb1 Michael Hanselmann
2900 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2901 d61cbe76 Iustin Pop
  """Closes the given block devices.
2902 d61cbe76 Iustin Pop

2903 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2904 10c2650b Iustin Pop
  DRBD).
2905 10c2650b Iustin Pop

2906 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2907 b2e7666a Iustin Pop
      of this instance will be removed
2908 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2909 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2910 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2911 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2912 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2913 10c2650b Iustin Pop
      which will contain the error details in case we
2914 10c2650b Iustin Pop
      failed
2915 d61cbe76 Iustin Pop

2916 d61cbe76 Iustin Pop
  """
2917 d61cbe76 Iustin Pop
  bdevs = []
2918 d61cbe76 Iustin Pop
  for cf in disks:
2919 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2920 d61cbe76 Iustin Pop
    if rd is None:
2921 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2922 d61cbe76 Iustin Pop
    bdevs.append(rd)
2923 d61cbe76 Iustin Pop
2924 d61cbe76 Iustin Pop
  msg = []
2925 d61cbe76 Iustin Pop
  for rd in bdevs:
2926 d61cbe76 Iustin Pop
    try:
2927 d61cbe76 Iustin Pop
      rd.Close()
2928 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2929 d61cbe76 Iustin Pop
      msg.append(str(err))
2930 d61cbe76 Iustin Pop
  if msg:
2931 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2932 d61cbe76 Iustin Pop
  else:
2933 b2e7666a Iustin Pop
    if instance_name:
2934 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2935 d61cbe76 Iustin Pop
2936 d61cbe76 Iustin Pop
2937 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2938 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2939 6217e295 Iustin Pop

2940 6217e295 Iustin Pop
  @type hvname: string
2941 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2942 6217e295 Iustin Pop
  @type hvparams: dict
2943 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2944 c26a6bd2 Iustin Pop
  @rtype: None
2945 6217e295 Iustin Pop

2946 6217e295 Iustin Pop
  """
2947 6217e295 Iustin Pop
  try:
2948 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2949 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2950 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2951 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2952 6217e295 Iustin Pop
2953 6217e295 Iustin Pop
2954 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
2955 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
2956 acd9ff9e Iustin Pop

2957 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
2958 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
2959 acd9ff9e Iustin Pop
  @type parameters: list
2960 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
2961 acd9ff9e Iustin Pop

2962 acd9ff9e Iustin Pop
  """
2963 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
2964 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
2965 acd9ff9e Iustin Pop
  if delta:
2966 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
2967 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2968 acd9ff9e Iustin Pop
2969 acd9ff9e Iustin Pop
2970 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
2971 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
2972 acd9ff9e Iustin Pop

2973 acd9ff9e Iustin Pop
  @type required: boolean
2974 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
2975 acd9ff9e Iustin Pop
      failure or not
2976 acd9ff9e Iustin Pop
  @type osname: string
2977 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
2978 acd9ff9e Iustin Pop
  @type checks: list
2979 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
2980 acd9ff9e Iustin Pop
  @type osparams: dict
2981 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
2982 acd9ff9e Iustin Pop
  @rtype: boolean
2983 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
2984 acd9ff9e Iustin Pop
      found and L{required} was false
2985 acd9ff9e Iustin Pop

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

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

3044 f942a838 Michael Hanselmann
  """
3045 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3046 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3047 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3048 f942a838 Michael Hanselmann
3049 f942a838 Michael Hanselmann
3050 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3051 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3052 f942a838 Michael Hanselmann

3053 f942a838 Michael Hanselmann
  @type validity: int
3054 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3055 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3056 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3057 f942a838 Michael Hanselmann

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

3084 f942a838 Michael Hanselmann
  @type name: string
3085 f942a838 Michael Hanselmann
  @param name: Certificate name
3086 f942a838 Michael Hanselmann

3087 f942a838 Michael Hanselmann
  """
3088 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3089 f942a838 Michael Hanselmann
3090 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3091 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3092 f942a838 Michael Hanselmann
3093 f942a838 Michael Hanselmann
  try:
3094 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3095 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3096 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3097 f942a838 Michael Hanselmann
          cert_dir, err)
3098 f942a838 Michael Hanselmann
3099 f942a838 Michael Hanselmann
3100 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3101 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3102 1651d116 Michael Hanselmann

3103 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3104 1651d116 Michael Hanselmann
  @param instance: The instance object
3105 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3106 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3107 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3108 1651d116 Michael Hanselmann

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

3214 1651d116 Michael Hanselmann
  """
3215 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3216 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3217 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3218 1651d116 Michael Hanselmann
3219 1651d116 Michael Hanselmann
3220 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3221 6613661a Iustin Pop
                            ieio, ieioargs):
3222 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3223 1651d116 Michael Hanselmann

3224 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3225 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3226 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3227 1651d116 Michael Hanselmann
  @type host: string
3228 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3229 1651d116 Michael Hanselmann
  @type port: int
3230 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3231 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3232 1651d116 Michael Hanselmann
  @param instance: Instance object
3233 6613661a Iustin Pop
  @type component: string
3234 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3235 6613661a Iustin Pop
      e.g. 'disk/0'
3236 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3237 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3238 1651d116 Michael Hanselmann

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

3351 1651d116 Michael Hanselmann
  @type names: sequence
3352 1651d116 Michael Hanselmann
  @param names: List of names
3353 1651d116 Michael Hanselmann
  @rtype: List of dicts
3354 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3355 1651d116 Michael Hanselmann
           status couldn't be read
3356 1651d116 Michael Hanselmann

3357 1651d116 Michael Hanselmann
  """
3358 1651d116 Michael Hanselmann
  result = []
3359 1651d116 Michael Hanselmann
3360 1651d116 Michael Hanselmann
  for name in names:
3361 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3362 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3363 1651d116 Michael Hanselmann
3364 1651d116 Michael Hanselmann
    try:
3365 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3366 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3367 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3368 1651d116 Michael Hanselmann
        raise
3369 1651d116 Michael Hanselmann
      data = None
3370 1651d116 Michael Hanselmann
3371 1651d116 Michael Hanselmann
    if not data:
3372 1651d116 Michael Hanselmann
      result.append(None)
3373 1651d116 Michael Hanselmann
      continue
3374 1651d116 Michael Hanselmann
3375 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3376 1651d116 Michael Hanselmann
3377 1651d116 Michael Hanselmann
  return result
3378 1651d116 Michael Hanselmann
3379 1651d116 Michael Hanselmann
3380 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3381 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3382 f81c4737 Michael Hanselmann

3383 f81c4737 Michael Hanselmann
  """
3384 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3385 f81c4737 Michael Hanselmann
3386 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3387 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3388 f81c4737 Michael Hanselmann
3389 f81c4737 Michael Hanselmann
  if pid:
3390 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3391 f81c4737 Michael Hanselmann
                 name, pid)
3392 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3393 f81c4737 Michael Hanselmann
3394 f81c4737 Michael Hanselmann
3395 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3396 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3397 1651d116 Michael Hanselmann

3398 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3399 1651d116 Michael Hanselmann
  whole status directory is removed.
3400 1651d116 Michael Hanselmann

3401 1651d116 Michael Hanselmann
  """
3402 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3403 1651d116 Michael Hanselmann
3404 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3405 1651d116 Michael Hanselmann
3406 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3407 1651d116 Michael Hanselmann
3408 1651d116 Michael Hanselmann
  if pid:
3409 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3410 1651d116 Michael Hanselmann
                 name, pid)
3411 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3412 1651d116 Michael Hanselmann
3413 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3414 1651d116 Michael Hanselmann
3415 1651d116 Michael Hanselmann
3416 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3417 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3418 6b93ec9d Iustin Pop

3419 6b93ec9d Iustin Pop
  """
3420 6b93ec9d Iustin Pop
  # set the correct physical ID
3421 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3422 6b93ec9d Iustin Pop
  for cf in disks:
3423 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3424 6b93ec9d Iustin Pop
3425 6b93ec9d Iustin Pop
  bdevs = []
3426 6b93ec9d Iustin Pop
3427 6b93ec9d Iustin Pop
  for cf in disks:
3428 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3429 6b93ec9d Iustin Pop
    if rd is None:
3430 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3431 6b93ec9d Iustin Pop
    bdevs.append(rd)
3432 5a533f8a Iustin Pop
  return bdevs
3433 6b93ec9d Iustin Pop
3434 6b93ec9d Iustin Pop
3435 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3436 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3437 6b93ec9d Iustin Pop

3438 6b93ec9d Iustin Pop
  """
3439 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3440 6b93ec9d Iustin Pop
3441 6b93ec9d Iustin Pop
  # disconnect disks
3442 6b93ec9d Iustin Pop
  for rd in bdevs:
3443 6b93ec9d Iustin Pop
    try:
3444 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3445 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3446 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3447 2cc6781a Iustin Pop
            err, exc=True)
3448 6b93ec9d Iustin Pop
3449 6b93ec9d Iustin Pop
3450 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3451 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3452 6b93ec9d Iustin Pop

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

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

3545 c46b9782 Luca Bigliardi
  """
3546 c46b9782 Luca Bigliardi
  try:
3547 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3548 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3549 c46b9782 Luca Bigliardi
    _Fail(str(err))
3550 c46b9782 Luca Bigliardi
3551 c46b9782 Luca Bigliardi
3552 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3553 f5118ade Iustin Pop
  """Hard-powercycle the node.
3554 f5118ade Iustin Pop

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

3558 f5118ade Iustin Pop
  """
3559 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3560 f5118ade Iustin Pop
  try:
3561 f5118ade Iustin Pop
    pid = os.fork()
3562 29921401 Iustin Pop
  except OSError:
3563 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3564 f5118ade Iustin Pop
    pid = 0
3565 f5118ade Iustin Pop
  if pid > 0:
3566 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3567 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3568 1af6ac0f Luca Bigliardi
  try:
3569 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3570 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3571 1af6ac0f Luca Bigliardi
    pass
3572 f5118ade Iustin Pop
  time.sleep(5)
3573 f5118ade Iustin Pop
  hyper.PowercycleNode()
3574 f5118ade Iustin Pop
3575 f5118ade Iustin Pop
3576 a8083063 Iustin Pop
class HooksRunner(object):
3577 a8083063 Iustin Pop
  """Hook runner.
3578 a8083063 Iustin Pop

3579 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3580 10c2650b Iustin Pop
  on the master side.
3581 a8083063 Iustin Pop

3582 a8083063 Iustin Pop
  """
3583 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3584 a8083063 Iustin Pop
    """Constructor for hooks runner.
3585 a8083063 Iustin Pop

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

3590 a8083063 Iustin Pop
    """
3591 a8083063 Iustin Pop
    if hooks_base_dir is None:
3592 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3593 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3594 fe267188 Iustin Pop
    # constant
3595 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3596 a8083063 Iustin Pop
3597 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3598 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3599 0fa481f5 Andrea Spadaccini

3600 0fa481f5 Andrea Spadaccini
    """
3601 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3602 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3603 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3604 0fa481f5 Andrea Spadaccini
    assert node == myself
3605 0fa481f5 Andrea Spadaccini
3606 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3607 0fa481f5 Andrea Spadaccini
3608 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3609 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3610 0fa481f5 Andrea Spadaccini
3611 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3612 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3613 a8083063 Iustin Pop

3614 10c2650b Iustin Pop
    @type hpath: str
3615 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3616 10c2650b Iustin Pop
        holds the scripts
3617 10c2650b Iustin Pop
    @type phase: str
3618 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3619 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3620 10c2650b Iustin Pop
    @type env: dict
3621 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3622 10c2650b Iustin Pop
    @rtype: list
3623 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3624 10c2650b Iustin Pop
      - script path
3625 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3626 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3627 10c2650b Iustin Pop
      - output of the script
3628 10c2650b Iustin Pop

3629 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3630 10c2650b Iustin Pop
        parameters
3631 a8083063 Iustin Pop

3632 a8083063 Iustin Pop
    """
3633 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3634 a8083063 Iustin Pop
      suffix = "pre"
3635 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3636 a8083063 Iustin Pop
      suffix = "post"
3637 a8083063 Iustin Pop
    else:
3638 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3639 3fb4f740 Iustin Pop
3640 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3641 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3642 6bb65e3a Guido Trotter
3643 6bb65e3a Guido Trotter
    results = []
3644 a9b7e346 Iustin Pop
3645 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3646 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3647 a9b7e346 Iustin Pop
      # warning at every operation
3648 a9b7e346 Iustin Pop
      return results
3649 a9b7e346 Iustin Pop
3650 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3651 a9b7e346 Iustin Pop
3652 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
3653 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3654 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3655 a8083063 Iustin Pop
        output = ""
3656 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3657 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3658 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3659 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3660 6bb65e3a Guido Trotter
        if runresult.failed:
3661 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3662 a8083063 Iustin Pop
        else:
3663 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3664 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3665 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3666 6bb65e3a Guido Trotter
3667 6bb65e3a Guido Trotter
    return results
3668 3f78eef2 Iustin Pop
3669 3f78eef2 Iustin Pop
3670 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3671 8d528b7c Iustin Pop
  """IAllocator runner.
3672 8d528b7c Iustin Pop

3673 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3674 8d528b7c Iustin Pop
  the master side.
3675 8d528b7c Iustin Pop

3676 8d528b7c Iustin Pop
  """
3677 7e950d31 Iustin Pop
  @staticmethod
3678 7e950d31 Iustin Pop
  def Run(name, idata):
3679 8d528b7c Iustin Pop
    """Run an iallocator script.
3680 8d528b7c Iustin Pop

3681 10c2650b Iustin Pop
    @type name: str
3682 10c2650b Iustin Pop
    @param name: the iallocator script name
3683 10c2650b Iustin Pop
    @type idata: str
3684 10c2650b Iustin Pop
    @param idata: the allocator input data
3685 10c2650b Iustin Pop

3686 10c2650b Iustin Pop
    @rtype: tuple
3687 87f5c298 Iustin Pop
    @return: two element tuple of:
3688 87f5c298 Iustin Pop
       - status
3689 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3690 8d528b7c Iustin Pop

3691 8d528b7c Iustin Pop
    """
3692 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3693 8d528b7c Iustin Pop
                                  os.path.isfile)
3694 8d528b7c Iustin Pop
    if alloc_script is None:
3695 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3696 8d528b7c Iustin Pop
3697 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3698 8d528b7c Iustin Pop
    try:
3699 8d528b7c Iustin Pop
      os.write(fd, idata)
3700 8d528b7c Iustin Pop
      os.close(fd)
3701 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3702 8d528b7c Iustin Pop
      if result.failed:
3703 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3704 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3705 8d528b7c Iustin Pop
    finally:
3706 8d528b7c Iustin Pop
      os.unlink(fin_name)
3707 8d528b7c Iustin Pop
3708 c26a6bd2 Iustin Pop
    return result.stdout
3709 8d528b7c Iustin Pop
3710 8d528b7c Iustin Pop
3711 3f78eef2 Iustin Pop
class DevCacheManager(object):
3712 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3713 3f78eef2 Iustin Pop

3714 3f78eef2 Iustin Pop
  """
3715 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3716 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
3717 3f78eef2 Iustin Pop
3718 3f78eef2 Iustin Pop
  @classmethod
3719 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3720 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3721 3f78eef2 Iustin Pop

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

3725 10c2650b Iustin Pop
    @type dev_path: str
3726 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3727 10c2650b Iustin Pop
    @rtype: str
3728 10c2650b Iustin Pop
    @return: the converted path name
3729 3f78eef2 Iustin Pop

3730 3f78eef2 Iustin Pop
    """
3731 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3732 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3733 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3734 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3735 3f78eef2 Iustin Pop
    return fpath
3736 3f78eef2 Iustin Pop
3737 3f78eef2 Iustin Pop
  @classmethod
3738 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3739 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3740 3f78eef2 Iustin Pop

3741 10c2650b Iustin Pop
    @type dev_path: str
3742 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3743 10c2650b Iustin Pop
    @type owner: str
3744 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3745 10c2650b Iustin Pop
    @type on_primary: bool
3746 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3747 10c2650b Iustin Pop
        node nor not
3748 10c2650b Iustin Pop
    @type iv_name: str
3749 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3750 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3751 10c2650b Iustin Pop

3752 10c2650b Iustin Pop
    @rtype: None
3753 10c2650b Iustin Pop

3754 3f78eef2 Iustin Pop
    """
3755 cf5a8306 Iustin Pop
    if dev_path is None:
3756 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3757 cf5a8306 Iustin Pop
      return
3758 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3759 3f78eef2 Iustin Pop
    if on_primary:
3760 3f78eef2 Iustin Pop
      state = "primary"
3761 3f78eef2 Iustin Pop
    else:
3762 3f78eef2 Iustin Pop
      state = "secondary"
3763 3f78eef2 Iustin Pop
    if iv_name is None:
3764 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3765 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3766 3f78eef2 Iustin Pop
    try:
3767 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3768 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3769 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3770 3f78eef2 Iustin Pop
3771 3f78eef2 Iustin Pop
  @classmethod
3772 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3773 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3774 3f78eef2 Iustin Pop

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

3778 10c2650b Iustin Pop
    @type dev_path: str
3779 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3780 10c2650b Iustin Pop

3781 10c2650b Iustin Pop
    @rtype: None
3782 10c2650b Iustin Pop

3783 3f78eef2 Iustin Pop
    """
3784 cf5a8306 Iustin Pop
    if dev_path is None:
3785 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3786 cf5a8306 Iustin Pop
      return
3787 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3788 3f78eef2 Iustin Pop
    try:
3789 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3790 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3791 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)