Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 6b3f0d7e

History | View | Annotate | Download (123.9 kB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

605 098c0958 Michael Hanselmann
  """
606 78519c10 Michael Hanselmann
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
607 1a3c5d4e Bernardo Dal Seno
  vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
608 78519c10 Michael Hanselmann
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
609 78519c10 Michael Hanselmann
610 78519c10 Michael Hanselmann
  return (bootid, vg_info, hv_info)
611 a8083063 Iustin Pop
612 a8083063 Iustin Pop
613 d5a690cb Bernardo Dal Seno
def _CheckExclusivePvs(pvi_list):
614 d5a690cb Bernardo Dal Seno
  """Check that PVs are not shared among LVs
615 d5a690cb Bernardo Dal Seno

616 d5a690cb Bernardo Dal Seno
  @type pvi_list: list of L{objects.LvmPvInfo} objects
617 d5a690cb Bernardo Dal Seno
  @param pvi_list: information about the PVs
618 d5a690cb Bernardo Dal Seno

619 d5a690cb Bernardo Dal Seno
  @rtype: list of tuples (string, list of strings)
620 d5a690cb Bernardo Dal Seno
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
621 d5a690cb Bernardo Dal Seno

622 d5a690cb Bernardo Dal Seno
  """
623 d5a690cb Bernardo Dal Seno
  res = []
624 d5a690cb Bernardo Dal Seno
  for pvi in pvi_list:
625 d5a690cb Bernardo Dal Seno
    if len(pvi.lv_list) > 1:
626 d5a690cb Bernardo Dal Seno
      res.append((pvi.name, pvi.lv_list))
627 d5a690cb Bernardo Dal Seno
  return res
628 d5a690cb Bernardo Dal Seno
629 d5a690cb Bernardo Dal Seno
630 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
631 a8083063 Iustin Pop
  """Verify the status of the local node.
632 a8083063 Iustin Pop

633 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
634 e69d05fd Iustin Pop
  local node.
635 e69d05fd Iustin Pop

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

639 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
640 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
641 e69d05fd Iustin Pop
  report).
642 a8083063 Iustin Pop

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

647 e69d05fd Iustin Pop
  @type what: C{dict}
648 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
649 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
650 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
651 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
652 e69d05fd Iustin Pop
        connectivity with
653 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
654 10c2650b Iustin Pop
  @rtype: dict
655 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
656 10c2650b Iustin Pop
      values representing the result of the checks
657 a8083063 Iustin Pop

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

854 2be7273c Apollon Oikonomopoulos
  @type devices: list
855 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
856 2be7273c Apollon Oikonomopoulos
  @rtype: dict
857 2be7273c Apollon Oikonomopoulos
  @return:
858 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
859 2be7273c Apollon Oikonomopoulos
    size in MiB.
860 2be7273c Apollon Oikonomopoulos

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

863 2be7273c Apollon Oikonomopoulos
  """
864 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
865 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
866 2be7273c Apollon Oikonomopoulos
867 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
868 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
869 2be7273c Apollon Oikonomopoulos
      continue
870 2be7273c Apollon Oikonomopoulos
871 2be7273c Apollon Oikonomopoulos
    try:
872 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
873 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
874 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
875 2be7273c Apollon Oikonomopoulos
      continue
876 2be7273c Apollon Oikonomopoulos
877 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
878 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
879 2be7273c Apollon Oikonomopoulos
      if result.failed:
880 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
881 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
882 2be7273c Apollon Oikonomopoulos
        continue
883 2be7273c Apollon Oikonomopoulos
884 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
885 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
886 2be7273c Apollon Oikonomopoulos
  return blockdevs
887 2be7273c Apollon Oikonomopoulos
888 2be7273c Apollon Oikonomopoulos
889 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
890 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
891 a8083063 Iustin Pop

892 84d7e26b Dmitry Chernyak
  @type vg_names: list
893 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
894 397693d3 Iustin Pop
      empty for all volume groups
895 10c2650b Iustin Pop
  @rtype: dict
896 10c2650b Iustin Pop
  @return:
897 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
898 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
899 10c2650b Iustin Pop

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

902 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
903 10c2650b Iustin Pop
      details.
904 a8083063 Iustin Pop

905 a8083063 Iustin Pop
  """
906 cb2037a2 Iustin Pop
  lvs = {}
907 d0c8c01d Iustin Pop
  sep = "|"
908 397693d3 Iustin Pop
  if not vg_names:
909 397693d3 Iustin Pop
    vg_names = []
910 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
911 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
912 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
913 a8083063 Iustin Pop
  if result.failed:
914 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
915 cb2037a2 Iustin Pop
916 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
917 df4c2628 Iustin Pop
    line = line.strip()
918 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
919 df4c2628 Iustin Pop
    if not match:
920 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
921 df4c2628 Iustin Pop
      continue
922 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
923 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
924 d0c8c01d Iustin Pop
    online = attr[5] == "o"
925 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
926 33f2a81a Iustin Pop
    if virtual:
927 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
928 33f2a81a Iustin Pop
      # don't really hold data
929 33f2a81a Iustin Pop
      continue
930 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
931 cb2037a2 Iustin Pop
932 cb2037a2 Iustin Pop
  return lvs
933 a8083063 Iustin Pop
934 a8083063 Iustin Pop
935 a8083063 Iustin Pop
def ListVolumeGroups():
936 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
937 a8083063 Iustin Pop

938 10c2650b Iustin Pop
  @rtype: dict
939 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
940 10c2650b Iustin Pop
      size of the volume
941 a8083063 Iustin Pop

942 a8083063 Iustin Pop
  """
943 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
944 a8083063 Iustin Pop
945 a8083063 Iustin Pop
946 dcb93971 Michael Hanselmann
def NodeVolumes():
947 dcb93971 Michael Hanselmann
  """List all volumes on this node.
948 dcb93971 Michael Hanselmann

949 10c2650b Iustin Pop
  @rtype: list
950 10c2650b Iustin Pop
  @return:
951 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
952 10c2650b Iustin Pop
      - name: the logical volume name,
953 10c2650b Iustin Pop
      - size: the size of the logical volume
954 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
955 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
956 10c2650b Iustin Pop

957 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
958 10c2650b Iustin Pop
    error.
959 10c2650b Iustin Pop

960 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
961 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
962 10c2650b Iustin Pop
    multiple times.
963 10c2650b Iustin Pop

964 dcb93971 Michael Hanselmann
  """
965 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
966 dcb93971 Michael Hanselmann
                         "--separator=|",
967 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
968 dcb93971 Michael Hanselmann
  if result.failed:
969 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
970 10bfe6cb Iustin Pop
          result.output)
971 dcb93971 Michael Hanselmann
972 dcb93971 Michael Hanselmann
  def parse_dev(dev):
973 d0c8c01d Iustin Pop
    return dev.split("(")[0]
974 89e5ab02 Iustin Pop
975 89e5ab02 Iustin Pop
  def handle_dev(dev):
976 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
977 dcb93971 Michael Hanselmann
978 dcb93971 Michael Hanselmann
  def map_line(line):
979 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
980 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
981 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
982 89e5ab02 Iustin Pop
983 89e5ab02 Iustin Pop
  all_devs = []
984 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
985 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
986 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
987 89e5ab02 Iustin Pop
    else:
988 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
989 89e5ab02 Iustin Pop
  return all_devs
990 dcb93971 Michael Hanselmann
991 dcb93971 Michael Hanselmann
992 a8083063 Iustin Pop
def BridgesExist(bridges_list):
993 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
994 a8083063 Iustin Pop

995 b1206984 Iustin Pop
  @rtype: boolean
996 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
997 a8083063 Iustin Pop

998 a8083063 Iustin Pop
  """
999 35c0c8da Iustin Pop
  missing = []
1000 a8083063 Iustin Pop
  for bridge in bridges_list:
1001 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
1002 35c0c8da Iustin Pop
      missing.append(bridge)
1003 a8083063 Iustin Pop
1004 35c0c8da Iustin Pop
  if missing:
1005 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1006 35c0c8da Iustin Pop
1007 a8083063 Iustin Pop
1008 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
1009 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
1010 a8083063 Iustin Pop

1011 e69d05fd Iustin Pop
  @type hypervisor_list: list
1012 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
1013 e69d05fd Iustin Pop

1014 e69d05fd Iustin Pop
  @rtype: list
1015 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
1016 10c2650b Iustin Pop
    - instance1.example.com
1017 10c2650b Iustin Pop
    - instance2.example.com
1018 a8083063 Iustin Pop

1019 098c0958 Michael Hanselmann
  """
1020 e69d05fd Iustin Pop
  results = []
1021 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1022 e69d05fd Iustin Pop
    try:
1023 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
1024 e69d05fd Iustin Pop
      results.extend(names)
1025 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
1026 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
1027 aca13712 Iustin Pop
            hname, err, exc=True)
1028 a8083063 Iustin Pop
1029 e69d05fd Iustin Pop
  return results
1030 a8083063 Iustin Pop
1031 a8083063 Iustin Pop
1032 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
1033 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
1034 a8083063 Iustin Pop

1035 e69d05fd Iustin Pop
  @type instance: string
1036 e69d05fd Iustin Pop
  @param instance: the instance name
1037 e69d05fd Iustin Pop
  @type hname: string
1038 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1039 a8083063 Iustin Pop

1040 e69d05fd Iustin Pop
  @rtype: dict
1041 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1042 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1043 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1044 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1045 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1046 a8083063 Iustin Pop

1047 098c0958 Michael Hanselmann
  """
1048 a8083063 Iustin Pop
  output = {}
1049 a8083063 Iustin Pop
1050 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1051 a8083063 Iustin Pop
  if iinfo is not None:
1052 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1053 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1054 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1055 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1056 a8083063 Iustin Pop
1057 c26a6bd2 Iustin Pop
  return output
1058 a8083063 Iustin Pop
1059 a8083063 Iustin Pop
1060 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1061 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
1062 56e7640c Iustin Pop

1063 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1064 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1065 56e7640c Iustin Pop

1066 56e7640c Iustin Pop
  @rtype: tuple
1067 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1068 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1069 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1070 56e7640c Iustin Pop

1071 56e7640c Iustin Pop
  """
1072 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1073 afdc3985 Iustin Pop
  iname = instance.name
1074 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
1075 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1076 56e7640c Iustin Pop
1077 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1078 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1079 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1080 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1081 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1082 56e7640c Iustin Pop
1083 56e7640c Iustin Pop
1084 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
1085 a8083063 Iustin Pop
  """Gather data about all instances.
1086 a8083063 Iustin Pop

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

1091 e69d05fd Iustin Pop
  @type hypervisor_list: list
1092 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1093 e69d05fd Iustin Pop

1094 955db481 Guido Trotter
  @rtype: dict
1095 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1096 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1097 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1098 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1099 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1100 a8083063 Iustin Pop

1101 098c0958 Michael Hanselmann
  """
1102 a8083063 Iustin Pop
  output = {}
1103 a8083063 Iustin Pop
1104 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1105 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1106 e69d05fd Iustin Pop
    if iinfo:
1107 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1108 f23b5ae8 Iustin Pop
        value = {
1109 d0c8c01d Iustin Pop
          "memory": memory,
1110 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1111 d0c8c01d Iustin Pop
          "state": state,
1112 d0c8c01d Iustin Pop
          "time": times,
1113 e69d05fd Iustin Pop
          }
1114 b33b6f55 Iustin Pop
        if name in output:
1115 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1116 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1117 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1118 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1119 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1120 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1121 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1122 f23b5ae8 Iustin Pop
        output[name] = value
1123 a8083063 Iustin Pop
1124 c26a6bd2 Iustin Pop
  return output
1125 a8083063 Iustin Pop
1126 a8083063 Iustin Pop
1127 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1128 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1129 81a3406c Iustin Pop

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

1133 81a3406c Iustin Pop
  @type kind: string
1134 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1135 81a3406c Iustin Pop
  @type os_name: string
1136 81a3406c Iustin Pop
  @param os_name: the os name
1137 81a3406c Iustin Pop
  @type instance: string
1138 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1139 6aa7a354 Iustin Pop
  @type component: string or None
1140 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1141 6aa7a354 Iustin Pop
      transferred
1142 81a3406c Iustin Pop

1143 81a3406c Iustin Pop
  """
1144 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1145 6aa7a354 Iustin Pop
  if component:
1146 6aa7a354 Iustin Pop
    assert "/" not in component
1147 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1148 6aa7a354 Iustin Pop
  else:
1149 6aa7a354 Iustin Pop
    c_msg = ""
1150 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1151 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1152 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1153 81a3406c Iustin Pop
1154 81a3406c Iustin Pop
1155 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1156 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1157 a8083063 Iustin Pop

1158 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1159 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1160 e557bae9 Guido Trotter
  @type reinstall: boolean
1161 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1162 4a0e011f Iustin Pop
  @type debug: integer
1163 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1164 c26a6bd2 Iustin Pop
  @rtype: None
1165 a8083063 Iustin Pop

1166 a8083063 Iustin Pop
  """
1167 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1168 255dcebd Iustin Pop
1169 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1170 e557bae9 Guido Trotter
  if reinstall:
1171 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1172 a8083063 Iustin Pop
1173 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1174 decd5f45 Iustin Pop
1175 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1176 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1177 decd5f45 Iustin Pop
  if result.failed:
1178 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1179 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1180 18682bca Iustin Pop
                  result.output)
1181 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1182 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1183 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1184 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1185 decd5f45 Iustin Pop
1186 decd5f45 Iustin Pop
1187 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1188 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1189 decd5f45 Iustin Pop

1190 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1191 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1192 d15a9ad3 Guido Trotter
  @type old_name: string
1193 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1194 4a0e011f Iustin Pop
  @type debug: integer
1195 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1196 10c2650b Iustin Pop
  @rtype: boolean
1197 10c2650b Iustin Pop
  @return: the success of the operation
1198 decd5f45 Iustin Pop

1199 decd5f45 Iustin Pop
  """
1200 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1201 decd5f45 Iustin Pop
1202 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1203 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1204 decd5f45 Iustin Pop
1205 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1206 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1207 a8083063 Iustin Pop
1208 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1209 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1210 a8083063 Iustin Pop
1211 a8083063 Iustin Pop
  if result.failed:
1212 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1213 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1214 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1215 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1216 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1217 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1218 a8083063 Iustin Pop
1219 a8083063 Iustin Pop
1220 3b721842 Michael Hanselmann
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1221 3b721842 Michael Hanselmann
  """Returns symlink path for block device.
1222 3b721842 Michael Hanselmann

1223 3b721842 Michael Hanselmann
  """
1224 3b721842 Michael Hanselmann
  if _dir is None:
1225 3b721842 Michael Hanselmann
    _dir = pathutils.DISK_LINKS_DIR
1226 3b721842 Michael Hanselmann
1227 3b721842 Michael Hanselmann
  return utils.PathJoin(_dir,
1228 3b721842 Michael Hanselmann
                        ("%s%s%s" %
1229 3b721842 Michael Hanselmann
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1230 5282084b Iustin Pop
1231 5282084b Iustin Pop
1232 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1233 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1234 9332fd8a Iustin Pop

1235 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1236 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1237 9332fd8a Iustin Pop

1238 9332fd8a Iustin Pop

1239 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1240 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1241 5282084b Iustin Pop
  @param idx: the disk index
1242 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1243 9332fd8a Iustin Pop

1244 9332fd8a Iustin Pop
  """
1245 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1246 9332fd8a Iustin Pop
  try:
1247 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1248 5282084b Iustin Pop
  except OSError, err:
1249 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1250 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1251 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1252 9332fd8a Iustin Pop
        os.remove(link_name)
1253 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1254 9332fd8a Iustin Pop
    else:
1255 9332fd8a Iustin Pop
      raise
1256 9332fd8a Iustin Pop
1257 9332fd8a Iustin Pop
  return link_name
1258 9332fd8a Iustin Pop
1259 9332fd8a Iustin Pop
1260 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1261 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1262 3c9c571d Iustin Pop

1263 3c9c571d Iustin Pop
  """
1264 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1265 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1266 5282084b Iustin Pop
    if os.path.islink(link_name):
1267 3c9c571d Iustin Pop
      try:
1268 03dfa658 Iustin Pop
        os.remove(link_name)
1269 03dfa658 Iustin Pop
      except OSError:
1270 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1271 3c9c571d Iustin Pop
1272 3c9c571d Iustin Pop
1273 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1274 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1275 a8083063 Iustin Pop

1276 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1277 a8083063 Iustin Pop
  devices must be already assembled.
1278 a8083063 Iustin Pop

1279 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1280 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1281 069cfbf1 Iustin Pop
  @rtype: list
1282 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1283 10c2650b Iustin Pop

1284 a8083063 Iustin Pop
  """
1285 a8083063 Iustin Pop
  block_devices = []
1286 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1287 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1288 a8083063 Iustin Pop
    if device is None:
1289 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1290 a8083063 Iustin Pop
                                    str(disk))
1291 a8083063 Iustin Pop
    device.Open()
1292 9332fd8a Iustin Pop
    try:
1293 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1294 9332fd8a Iustin Pop
    except OSError, e:
1295 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1296 9332fd8a Iustin Pop
                                    e.strerror)
1297 9332fd8a Iustin Pop
1298 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1299 9332fd8a Iustin Pop
1300 a8083063 Iustin Pop
  return block_devices
1301 a8083063 Iustin Pop
1302 a8083063 Iustin Pop
1303 323f9095 Stephen Shirley
def StartInstance(instance, startup_paused):
1304 a8083063 Iustin Pop
  """Start an instance.
1305 a8083063 Iustin Pop

1306 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1307 e69d05fd Iustin Pop
  @param instance: the instance object
1308 323f9095 Stephen Shirley
  @type startup_paused: bool
1309 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1310 c26a6bd2 Iustin Pop
  @rtype: None
1311 a8083063 Iustin Pop

1312 098c0958 Michael Hanselmann
  """
1313 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1314 a8083063 Iustin Pop
1315 a8083063 Iustin Pop
  if instance.name in running_instances:
1316 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1317 c26a6bd2 Iustin Pop
    return
1318 a8083063 Iustin Pop
1319 a8083063 Iustin Pop
  try:
1320 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1321 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1322 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1323 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1324 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1325 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1326 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1327 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1328 a8083063 Iustin Pop
1329 a8083063 Iustin Pop
1330 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1331 a8083063 Iustin Pop
  """Shut an instance down.
1332 a8083063 Iustin Pop

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

1335 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1336 e69d05fd Iustin Pop
  @param instance: the instance object
1337 6263189c Guido Trotter
  @type timeout: integer
1338 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1339 c26a6bd2 Iustin Pop
  @rtype: None
1340 a8083063 Iustin Pop

1341 098c0958 Michael Hanselmann
  """
1342 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1343 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1344 c26a6bd2 Iustin Pop
  iname = instance.name
1345 a8083063 Iustin Pop
1346 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1347 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1348 c26a6bd2 Iustin Pop
    return
1349 a8083063 Iustin Pop
1350 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1351 3c0cdc83 Michael Hanselmann
    def __init__(self):
1352 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1353 a8083063 Iustin Pop
1354 3c0cdc83 Michael Hanselmann
    def __call__(self):
1355 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1356 3c0cdc83 Michael Hanselmann
        return
1357 3c0cdc83 Michael Hanselmann
1358 3c0cdc83 Michael Hanselmann
      try:
1359 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1360 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1361 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1362 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1363 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1364 3c0cdc83 Michael Hanselmann
          return
1365 3c0cdc83 Michael Hanselmann
1366 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1367 3c0cdc83 Michael Hanselmann
1368 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1369 3c0cdc83 Michael Hanselmann
1370 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1371 3c0cdc83 Michael Hanselmann
1372 3c0cdc83 Michael Hanselmann
  try:
1373 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1374 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1375 a8083063 Iustin Pop
    # the shutdown did not succeed
1376 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1377 a8083063 Iustin Pop
1378 a8083063 Iustin Pop
    try:
1379 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1380 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1381 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1382 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1383 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1384 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1385 a8083063 Iustin Pop
1386 a8083063 Iustin Pop
    time.sleep(1)
1387 3c0cdc83 Michael Hanselmann
1388 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1389 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1390 3c9c571d Iustin Pop
1391 f28ec899 Guido Trotter
  try:
1392 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1393 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1394 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1395 f28ec899 Guido Trotter
1396 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1397 a8083063 Iustin Pop
1398 a8083063 Iustin Pop
1399 17c3f802 Guido Trotter
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1400 007a2f3e Alexander Schreiber
  """Reboot an instance.
1401 007a2f3e Alexander Schreiber

1402 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1403 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1404 10c2650b Iustin Pop
  @type reboot_type: str
1405 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1406 10c2650b Iustin Pop
    constants:
1407 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1408 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1409 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1410 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1411 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1412 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1413 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1414 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1415 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1416 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1417 c26a6bd2 Iustin Pop
  @rtype: None
1418 007a2f3e Alexander Schreiber

1419 007a2f3e Alexander Schreiber
  """
1420 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1421 007a2f3e Alexander Schreiber
1422 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1423 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1424 007a2f3e Alexander Schreiber
1425 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1426 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1427 007a2f3e Alexander Schreiber
    try:
1428 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1429 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1430 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1431 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1432 007a2f3e Alexander Schreiber
    try:
1433 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1434 82bc21e2 Stephen Shirley
      return StartInstance(instance, False)
1435 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1436 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1437 007a2f3e Alexander Schreiber
  else:
1438 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1439 007a2f3e Alexander Schreiber
1440 007a2f3e Alexander Schreiber
1441 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1442 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1443 ebe466d8 Guido Trotter

1444 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1445 ebe466d8 Guido Trotter
  @param instance: the instance object
1446 ebe466d8 Guido Trotter
  @type memory: int
1447 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1448 ebe466d8 Guido Trotter
  @rtype: None
1449 ebe466d8 Guido Trotter

1450 ebe466d8 Guido Trotter
  """
1451 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1452 ebe466d8 Guido Trotter
  running = hyper.ListInstances()
1453 ebe466d8 Guido Trotter
  if instance.name not in running:
1454 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1455 ebe466d8 Guido Trotter
    return
1456 ebe466d8 Guido Trotter
  try:
1457 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1458 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1459 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1460 ebe466d8 Guido Trotter
1461 ebe466d8 Guido Trotter
1462 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1463 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1464 6906a9d8 Guido Trotter

1465 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1466 6906a9d8 Guido Trotter
  @param instance: the instance definition
1467 6906a9d8 Guido Trotter

1468 6906a9d8 Guido Trotter
  """
1469 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1470 cd42d0ad Guido Trotter
  try:
1471 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1472 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1473 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1474 c26a6bd2 Iustin Pop
  return info
1475 6906a9d8 Guido Trotter
1476 6906a9d8 Guido Trotter
1477 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1478 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1479 6906a9d8 Guido Trotter

1480 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1481 6906a9d8 Guido Trotter
  @param instance: the instance definition
1482 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1483 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1484 6906a9d8 Guido Trotter
  @type target: string
1485 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1486 6906a9d8 Guido Trotter

1487 6906a9d8 Guido Trotter
  """
1488 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1489 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1490 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1491 77fcff4a Apollon Oikonomopoulos
    # in any way
1492 77fcff4a Apollon Oikonomopoulos
    try:
1493 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1494 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1495 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1496 77fcff4a Apollon Oikonomopoulos
1497 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1498 cd42d0ad Guido Trotter
  try:
1499 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1500 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1501 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1502 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1503 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1504 6906a9d8 Guido Trotter
1505 6906a9d8 Guido Trotter
1506 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1507 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1508 6906a9d8 Guido Trotter

1509 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1510 6906a9d8 Guido Trotter
  @param instance: the instance definition
1511 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1512 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1513 6906a9d8 Guido Trotter
  @type success: boolean
1514 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1515 6906a9d8 Guido Trotter

1516 6906a9d8 Guido Trotter
  """
1517 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1518 cd42d0ad Guido Trotter
  try:
1519 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1520 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1521 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1522 6906a9d8 Guido Trotter
1523 6906a9d8 Guido Trotter
1524 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1525 2a10865c Iustin Pop
  """Migrates an instance to another node.
1526 2a10865c Iustin Pop

1527 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1528 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1529 9f0e6b37 Iustin Pop
  @type target: string
1530 9f0e6b37 Iustin Pop
  @param target: the target node name
1531 9f0e6b37 Iustin Pop
  @type live: boolean
1532 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1533 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1534 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1535 9f0e6b37 Iustin Pop

1536 2a10865c Iustin Pop
  """
1537 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1538 2a10865c Iustin Pop
1539 2a10865c Iustin Pop
  try:
1540 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1541 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1542 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1543 2a10865c Iustin Pop
1544 2a10865c Iustin Pop
1545 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1546 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1547 6a1434d7 Andrea Spadaccini

1548 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1549 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1550 6a1434d7 Andrea Spadaccini
  @type success: bool
1551 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1552 6a1434d7 Andrea Spadaccini
  @type live: bool
1553 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1554 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1555 6a1434d7 Andrea Spadaccini

1556 6a1434d7 Andrea Spadaccini
  """
1557 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1558 6a1434d7 Andrea Spadaccini
1559 6a1434d7 Andrea Spadaccini
  try:
1560 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1561 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1562 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1563 6a1434d7 Andrea Spadaccini
          exc=True)
1564 6a1434d7 Andrea Spadaccini
1565 6a1434d7 Andrea Spadaccini
1566 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1567 6a1434d7 Andrea Spadaccini
  """Get the migration status
1568 6a1434d7 Andrea Spadaccini

1569 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1570 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1571 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1572 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1573 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1574 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1575 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1576 6a1434d7 Andrea Spadaccini

1577 6a1434d7 Andrea Spadaccini
  """
1578 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1579 6a1434d7 Andrea Spadaccini
  try:
1580 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1581 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1582 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1583 6a1434d7 Andrea Spadaccini
1584 6a1434d7 Andrea Spadaccini
1585 ee1478e5 Bernardo Dal Seno
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1586 a8083063 Iustin Pop
  """Creates a block device for an instance.
1587 a8083063 Iustin Pop

1588 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1589 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1590 b1206984 Iustin Pop
  @type size: int
1591 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1592 b1206984 Iustin Pop
  @type owner: str
1593 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1594 b1206984 Iustin Pop
      used for device cache data
1595 b1206984 Iustin Pop
  @type on_primary: boolean
1596 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1597 b1206984 Iustin Pop
  @type info: string
1598 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1599 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1600 ee1478e5 Bernardo Dal Seno
  @type excl_stor: boolean
1601 ee1478e5 Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
1602 b1206984 Iustin Pop

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

1607 a8083063 Iustin Pop
  """
1608 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
1609 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
1610 a8083063 Iustin Pop
  clist = []
1611 a8083063 Iustin Pop
  if disk.children:
1612 a8083063 Iustin Pop
    for child in disk.children:
1613 1063abd1 Iustin Pop
      try:
1614 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1615 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1616 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1617 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1618 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1619 a8083063 Iustin Pop
        # be assembled
1620 1063abd1 Iustin Pop
        try:
1621 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
1622 1063abd1 Iustin Pop
          crdev.Open()
1623 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1624 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1625 a8083063 Iustin Pop
      clist.append(crdev)
1626 a8083063 Iustin Pop
1627 dab69e97 Iustin Pop
  try:
1628 ee1478e5 Bernardo Dal Seno
    device = bdev.Create(disk, clist, excl_stor)
1629 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1630 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1631 6c626518 Iustin Pop
1632 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1633 1063abd1 Iustin Pop
    try:
1634 1063abd1 Iustin Pop
      device.Assemble()
1635 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1636 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1637 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1638 1063abd1 Iustin Pop
      try:
1639 1063abd1 Iustin Pop
        device.Open(force=True)
1640 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1641 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1642 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1643 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1644 a0c3fea1 Michael Hanselmann
1645 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1646 a0c3fea1 Michael Hanselmann
1647 c26a6bd2 Iustin Pop
  return device.unique_id
1648 a8083063 Iustin Pop
1649 a8083063 Iustin Pop
1650 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1651 69dd363f René Nussbaumer
  """This function actually wipes the device.
1652 69dd363f René Nussbaumer

1653 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1654 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1655 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1656 69dd363f René Nussbaumer

1657 69dd363f René Nussbaumer
  """
1658 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
1659 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
1660 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
1661 0188611b Michael Hanselmann
  block_size = 1024 * 1024
1662 0188611b Michael Hanselmann
1663 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1664 0188611b Michael Hanselmann
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1665 da63bb4e René Nussbaumer
         "count=%d" % size]
1666 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1667 69dd363f René Nussbaumer
1668 69dd363f René Nussbaumer
  if result.failed:
1669 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1670 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1671 69dd363f René Nussbaumer
1672 69dd363f René Nussbaumer
1673 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1674 69dd363f René Nussbaumer
  """Wipes a block device.
1675 69dd363f René Nussbaumer

1676 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1677 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1678 da63bb4e René Nussbaumer
  @type offset: int
1679 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1680 da63bb4e René Nussbaumer
  @type size: int
1681 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1682 69dd363f René Nussbaumer

1683 69dd363f René Nussbaumer
  """
1684 69dd363f René Nussbaumer
  try:
1685 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1686 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1687 da63bb4e René Nussbaumer
    rdev = None
1688 da63bb4e René Nussbaumer
1689 da63bb4e René Nussbaumer
  if not rdev:
1690 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1691 da63bb4e René Nussbaumer
1692 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1693 0188611b Michael Hanselmann
  if offset < 0:
1694 0188611b Michael Hanselmann
    _Fail("Negative offset")
1695 0188611b Michael Hanselmann
  if size < 0:
1696 0188611b Michael Hanselmann
    _Fail("Negative size")
1697 da63bb4e René Nussbaumer
  if offset > rdev.size:
1698 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1699 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1700 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1701 69dd363f René Nussbaumer
1702 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1703 69dd363f René Nussbaumer
1704 69dd363f René Nussbaumer
1705 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1706 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1707 5119c79e René Nussbaumer

1708 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1709 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1710 5119c79e René Nussbaumer
  @type pause: bool
1711 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1712 5119c79e René Nussbaumer

1713 5119c79e René Nussbaumer
  """
1714 5119c79e René Nussbaumer
  success = []
1715 5119c79e René Nussbaumer
  for disk in disks:
1716 5119c79e René Nussbaumer
    try:
1717 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1718 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1719 5119c79e René Nussbaumer
      rdev = None
1720 5119c79e René Nussbaumer
1721 5119c79e René Nussbaumer
    if not rdev:
1722 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1723 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1724 5119c79e René Nussbaumer
      continue
1725 5119c79e René Nussbaumer
1726 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1727 5119c79e René Nussbaumer
1728 5119c79e René Nussbaumer
    if result:
1729 5119c79e René Nussbaumer
      success.append((result, None))
1730 5119c79e René Nussbaumer
    else:
1731 5119c79e René Nussbaumer
      if pause:
1732 5119c79e René Nussbaumer
        msg = "Pause"
1733 5119c79e René Nussbaumer
      else:
1734 5119c79e René Nussbaumer
        msg = "Resume"
1735 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1736 5119c79e René Nussbaumer
1737 5119c79e René Nussbaumer
  return success
1738 5119c79e René Nussbaumer
1739 5119c79e René Nussbaumer
1740 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1741 a8083063 Iustin Pop
  """Remove a block device.
1742 a8083063 Iustin Pop

1743 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1744 10c2650b Iustin Pop

1745 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1746 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1747 10c2650b Iustin Pop
  @rtype: boolean
1748 10c2650b Iustin Pop
  @return: the success of the operation
1749 a8083063 Iustin Pop

1750 a8083063 Iustin Pop
  """
1751 e1bc0878 Iustin Pop
  msgs = []
1752 a8083063 Iustin Pop
  try:
1753 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1754 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1755 a8083063 Iustin Pop
    # probably can't attach
1756 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1757 a8083063 Iustin Pop
    rdev = None
1758 a8083063 Iustin Pop
  if rdev is not None:
1759 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1760 e1bc0878 Iustin Pop
    try:
1761 0c6c04ec Iustin Pop
      rdev.Remove()
1762 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1763 e1bc0878 Iustin Pop
      msgs.append(str(err))
1764 c26a6bd2 Iustin Pop
    if not msgs:
1765 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1766 e1bc0878 Iustin Pop
1767 a8083063 Iustin Pop
  if disk.children:
1768 a8083063 Iustin Pop
    for child in disk.children:
1769 c26a6bd2 Iustin Pop
      try:
1770 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1771 c26a6bd2 Iustin Pop
      except RPCFail, err:
1772 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1773 e1bc0878 Iustin Pop
1774 c26a6bd2 Iustin Pop
  if msgs:
1775 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1776 afdc3985 Iustin Pop
1777 a8083063 Iustin Pop
1778 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1779 a8083063 Iustin Pop
  """Activate a block device for an instance.
1780 a8083063 Iustin Pop

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

1783 10c2650b Iustin Pop
  @note: this function is called recursively.
1784 a8083063 Iustin Pop

1785 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1786 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1787 10c2650b Iustin Pop
  @type owner: str
1788 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1789 10c2650b Iustin Pop
  @type as_primary: boolean
1790 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1791 10c2650b Iustin Pop
      read/write
1792 a8083063 Iustin Pop

1793 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1794 10c2650b Iustin Pop
      was assembled)
1795 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1796 10c2650b Iustin Pop
      during the activation of the children or the device
1797 10c2650b Iustin Pop
      itself
1798 a8083063 Iustin Pop

1799 a8083063 Iustin Pop
  """
1800 a8083063 Iustin Pop
  children = []
1801 a8083063 Iustin Pop
  if disk.children:
1802 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1803 fc1dc9d7 Iustin Pop
    if mcn == -1:
1804 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1805 fc1dc9d7 Iustin Pop
    else:
1806 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1807 a8083063 Iustin Pop
    for chld_disk in disk.children:
1808 fc1dc9d7 Iustin Pop
      try:
1809 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1810 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1811 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1812 fc1dc9d7 Iustin Pop
          raise
1813 fc1dc9d7 Iustin Pop
        cdev = None
1814 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1815 1063abd1 Iustin Pop
                      str(err))
1816 fc1dc9d7 Iustin Pop
      children.append(cdev)
1817 a8083063 Iustin Pop
1818 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1819 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
1820 a8083063 Iustin Pop
    result = r_dev
1821 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1822 a8083063 Iustin Pop
      r_dev.Open()
1823 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1824 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1825 3f78eef2 Iustin Pop
1826 a8083063 Iustin Pop
  else:
1827 a8083063 Iustin Pop
    result = True
1828 a8083063 Iustin Pop
  return result
1829 a8083063 Iustin Pop
1830 a8083063 Iustin Pop
1831 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
1832 a8083063 Iustin Pop
  """Activate a block device for an instance.
1833 a8083063 Iustin Pop

1834 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1835 a8083063 Iustin Pop

1836 b1206984 Iustin Pop
  @rtype: str or boolean
1837 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1838 b1206984 Iustin Pop
      C{True} for secondary nodes
1839 a8083063 Iustin Pop

1840 a8083063 Iustin Pop
  """
1841 53c14ef1 Iustin Pop
  try:
1842 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1843 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1844 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
1845 53c14ef1 Iustin Pop
      result = result.dev_path
1846 c417e115 Iustin Pop
      if as_primary:
1847 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
1848 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1849 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1850 c417e115 Iustin Pop
  except OSError, err:
1851 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
1852 afdc3985 Iustin Pop
1853 c26a6bd2 Iustin Pop
  return result
1854 a8083063 Iustin Pop
1855 a8083063 Iustin Pop
1856 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1857 a8083063 Iustin Pop
  """Shut down a block device.
1858 a8083063 Iustin Pop

1859 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1860 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1861 c41eea6e Iustin Pop
  shutdown.
1862 a8083063 Iustin Pop

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

1867 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1868 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1869 10c2650b Iustin Pop
      shutdown
1870 c26a6bd2 Iustin Pop
  @rtype: None
1871 10c2650b Iustin Pop

1872 a8083063 Iustin Pop
  """
1873 cacfd1fd Iustin Pop
  msgs = []
1874 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1875 a8083063 Iustin Pop
  if r_dev is not None:
1876 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1877 cacfd1fd Iustin Pop
    try:
1878 746f7476 Iustin Pop
      r_dev.Shutdown()
1879 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1880 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1881 cacfd1fd Iustin Pop
      msgs.append(str(err))
1882 746f7476 Iustin Pop
1883 a8083063 Iustin Pop
  if disk.children:
1884 a8083063 Iustin Pop
    for child in disk.children:
1885 c26a6bd2 Iustin Pop
      try:
1886 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1887 c26a6bd2 Iustin Pop
      except RPCFail, err:
1888 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1889 746f7476 Iustin Pop
1890 c26a6bd2 Iustin Pop
  if msgs:
1891 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1892 a8083063 Iustin Pop
1893 a8083063 Iustin Pop
1894 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1895 153d9724 Iustin Pop
  """Extend a mirrored block device.
1896 a8083063 Iustin Pop

1897 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1898 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1899 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1900 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1901 c26a6bd2 Iustin Pop
  @rtype: None
1902 10c2650b Iustin Pop

1903 a8083063 Iustin Pop
  """
1904 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1905 153d9724 Iustin Pop
  if parent_bdev is None:
1906 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1907 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1908 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1909 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1910 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1911 a8083063 Iustin Pop
1912 a8083063 Iustin Pop
1913 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1914 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1915 a8083063 Iustin Pop

1916 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1917 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1918 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1919 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1920 c26a6bd2 Iustin Pop
  @rtype: None
1921 10c2650b Iustin Pop

1922 a8083063 Iustin Pop
  """
1923 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1924 153d9724 Iustin Pop
  if parent_bdev is None:
1925 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1926 e739bd57 Iustin Pop
  devs = []
1927 e739bd57 Iustin Pop
  for disk in new_cdevs:
1928 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1929 e739bd57 Iustin Pop
    if rpath is None:
1930 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1931 e739bd57 Iustin Pop
      if bd is None:
1932 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1933 e739bd57 Iustin Pop
      else:
1934 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1935 e739bd57 Iustin Pop
    else:
1936 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1937 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1938 e739bd57 Iustin Pop
      devs.append(rpath)
1939 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1940 a8083063 Iustin Pop
1941 a8083063 Iustin Pop
1942 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1943 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1944 a8083063 Iustin Pop

1945 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1946 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1947 10c2650b Iustin Pop
  @rtype: disk
1948 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1949 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1950 10c2650b Iustin Pop
      found
1951 a8083063 Iustin Pop

1952 a8083063 Iustin Pop
  """
1953 a8083063 Iustin Pop
  stats = []
1954 a8083063 Iustin Pop
  for dsk in disks:
1955 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1956 a8083063 Iustin Pop
    if rbd is None:
1957 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1958 96acbc09 Michael Hanselmann
1959 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1960 96acbc09 Michael Hanselmann
1961 c26a6bd2 Iustin Pop
  return stats
1962 a8083063 Iustin Pop
1963 a8083063 Iustin Pop
1964 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1965 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1966 c6a9dffa Michael Hanselmann

1967 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1968 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1969 c6a9dffa Michael Hanselmann
  @rtype: disk
1970 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1971 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
1972 c6a9dffa Michael Hanselmann
    otherwise
1973 c6a9dffa Michael Hanselmann

1974 c6a9dffa Michael Hanselmann
  """
1975 c6a9dffa Michael Hanselmann
  result = []
1976 c6a9dffa Michael Hanselmann
  for disk in disks:
1977 c6a9dffa Michael Hanselmann
    try:
1978 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
1979 c6a9dffa Michael Hanselmann
      if rbd is None:
1980 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
1981 c6a9dffa Michael Hanselmann
        continue
1982 c6a9dffa Michael Hanselmann
1983 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
1984 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
1985 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
1986 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
1987 c6a9dffa Michael Hanselmann
    else:
1988 c6a9dffa Michael Hanselmann
      result.append((True, status))
1989 c6a9dffa Michael Hanselmann
1990 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
1991 c6a9dffa Michael Hanselmann
1992 c6a9dffa Michael Hanselmann
  return result
1993 c6a9dffa Michael Hanselmann
1994 c6a9dffa Michael Hanselmann
1995 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1996 a8083063 Iustin Pop
  """Check if a device is activated.
1997 a8083063 Iustin Pop

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

2000 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2001 10c2650b Iustin Pop
  @param disk: the disk object we need to find
2002 a8083063 Iustin Pop

2003 10c2650b Iustin Pop
  @return: None if the device can't be found,
2004 10c2650b Iustin Pop
      otherwise the device instance
2005 a8083063 Iustin Pop

2006 a8083063 Iustin Pop
  """
2007 a8083063 Iustin Pop
  children = []
2008 a8083063 Iustin Pop
  if disk.children:
2009 a8083063 Iustin Pop
    for chdisk in disk.children:
2010 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
2011 a8083063 Iustin Pop
2012 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
2013 a8083063 Iustin Pop
2014 a8083063 Iustin Pop
2015 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
2016 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
2017 f2e07bb4 Michael Hanselmann

2018 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
2019 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
2020 f2e07bb4 Michael Hanselmann

2021 f2e07bb4 Michael Hanselmann
  """
2022 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
2023 f2e07bb4 Michael Hanselmann
  if real_disk is None:
2024 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
2025 f2e07bb4 Michael Hanselmann
2026 f2e07bb4 Michael Hanselmann
  real_disk.Open()
2027 f2e07bb4 Michael Hanselmann
2028 f2e07bb4 Michael Hanselmann
  return real_disk
2029 f2e07bb4 Michael Hanselmann
2030 f2e07bb4 Michael Hanselmann
2031 821d1bd1 Iustin Pop
def BlockdevFind(disk):
2032 a8083063 Iustin Pop
  """Check if a device is activated.
2033 a8083063 Iustin Pop

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

2036 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2037 10c2650b Iustin Pop
  @param disk: the disk to find
2038 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2039 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2040 96acbc09 Michael Hanselmann
           information
2041 a8083063 Iustin Pop

2042 a8083063 Iustin Pop
  """
2043 23829f6f Iustin Pop
  try:
2044 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
2045 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
2046 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
2047 96acbc09 Michael Hanselmann
2048 a8083063 Iustin Pop
  if rbd is None:
2049 c26a6bd2 Iustin Pop
    return None
2050 96acbc09 Michael Hanselmann
2051 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2052 a8083063 Iustin Pop
2053 a8083063 Iustin Pop
2054 968a7623 Iustin Pop
def BlockdevGetsize(disks):
2055 968a7623 Iustin Pop
  """Computes the size of the given disks.
2056 968a7623 Iustin Pop

2057 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2058 968a7623 Iustin Pop

2059 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2060 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2061 968a7623 Iustin Pop
  @rtype: list
2062 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2063 968a7623 Iustin Pop
      otherwise the size
2064 968a7623 Iustin Pop

2065 968a7623 Iustin Pop
  """
2066 968a7623 Iustin Pop
  result = []
2067 968a7623 Iustin Pop
  for cf in disks:
2068 968a7623 Iustin Pop
    try:
2069 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2070 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2071 968a7623 Iustin Pop
      result.append(None)
2072 968a7623 Iustin Pop
      continue
2073 968a7623 Iustin Pop
    if rbd is None:
2074 968a7623 Iustin Pop
      result.append(None)
2075 968a7623 Iustin Pop
    else:
2076 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
2077 968a7623 Iustin Pop
  return result
2078 968a7623 Iustin Pop
2079 968a7623 Iustin Pop
2080 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2081 858f3d18 Iustin Pop
  """Export a block device to a remote node.
2082 858f3d18 Iustin Pop

2083 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
2084 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
2085 858f3d18 Iustin Pop
  @type dest_node: str
2086 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
2087 858f3d18 Iustin Pop
  @type dest_path: str
2088 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
2089 858f3d18 Iustin Pop
  @type cluster_name: str
2090 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2091 858f3d18 Iustin Pop
  @rtype: None
2092 858f3d18 Iustin Pop

2093 858f3d18 Iustin Pop
  """
2094 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
2095 858f3d18 Iustin Pop
2096 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
2097 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2098 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
2099 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
2100 858f3d18 Iustin Pop
2101 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
2102 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
2103 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
2104 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2105 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
2106 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
2107 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2108 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
2109 858f3d18 Iustin Pop
2110 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2111 052783ff Michael Hanselmann
                                                   constants.SSH_LOGIN_USER,
2112 858f3d18 Iustin Pop
                                                   destcmd)
2113 858f3d18 Iustin Pop
2114 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
2115 d0c8c01d Iustin Pop
  command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2116 858f3d18 Iustin Pop
2117 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
2118 858f3d18 Iustin Pop
2119 858f3d18 Iustin Pop
  if result.failed:
2120 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
2121 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
2122 858f3d18 Iustin Pop
2123 858f3d18 Iustin Pop
2124 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2125 a8083063 Iustin Pop
  """Write a file to the filesystem.
2126 a8083063 Iustin Pop

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

2130 10c2650b Iustin Pop
  @type file_name: str
2131 10c2650b Iustin Pop
  @param file_name: the target file name
2132 10c2650b Iustin Pop
  @type data: str
2133 10c2650b Iustin Pop
  @param data: the new contents of the file
2134 10c2650b Iustin Pop
  @type mode: int
2135 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2136 9a914f7a René Nussbaumer
  @type uid: string
2137 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2138 9a914f7a René Nussbaumer
  @type gid: string
2139 9a914f7a René Nussbaumer
  @param gid: the group of the file
2140 10c2650b Iustin Pop
  @type atime: float
2141 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2142 10c2650b Iustin Pop
  @type mtime: float
2143 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2144 c26a6bd2 Iustin Pop
  @rtype: None
2145 10c2650b Iustin Pop

2146 a8083063 Iustin Pop
  """
2147 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2148 cffbbae7 Michael Hanselmann
2149 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2150 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2151 a8083063 Iustin Pop
2152 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2153 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2154 2cc6781a Iustin Pop
          file_name)
2155 a8083063 Iustin Pop
2156 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2157 12bce260 Michael Hanselmann
2158 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2159 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2160 9a914f7a René Nussbaumer
2161 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2162 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2163 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2164 9a914f7a René Nussbaumer
2165 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2166 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2167 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2168 a8083063 Iustin Pop
2169 386b57af Iustin Pop
2170 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2171 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2172 b2f29800 René Nussbaumer

2173 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2174 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2175 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2176 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2177 b2f29800 René Nussbaumer

2178 b2f29800 René Nussbaumer
  @return: stdout
2179 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2180 b2f29800 René Nussbaumer

2181 b2f29800 René Nussbaumer
  """
2182 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2183 b2f29800 René Nussbaumer
2184 b2f29800 René Nussbaumer
  if result.failed:
2185 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2186 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2187 b2f29800 René Nussbaumer
2188 b2f29800 René Nussbaumer
  return result.stdout
2189 b2f29800 René Nussbaumer
2190 b2f29800 René Nussbaumer
2191 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2192 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2193 a8083063 Iustin Pop

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

2197 10c2650b Iustin Pop
  @type os_dir: str
2198 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2199 8e70b181 Iustin Pop
  @rtype: tuple
2200 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2201 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2202 a8083063 Iustin Pop

2203 a8083063 Iustin Pop
  """
2204 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2205 a8083063 Iustin Pop
2206 a8083063 Iustin Pop
  try:
2207 a8083063 Iustin Pop
    st = os.stat(api_file)
2208 a8083063 Iustin Pop
  except EnvironmentError, err:
2209 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2210 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2211 a8083063 Iustin Pop
2212 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2213 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2214 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2215 a8083063 Iustin Pop
2216 a8083063 Iustin Pop
  try:
2217 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2218 a8083063 Iustin Pop
  except EnvironmentError, err:
2219 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2220 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2221 a8083063 Iustin Pop
2222 a8083063 Iustin Pop
  try:
2223 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2224 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2225 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2226 255dcebd Iustin Pop
                   str(err))
2227 a8083063 Iustin Pop
2228 255dcebd Iustin Pop
  return True, api_versions
2229 a8083063 Iustin Pop
2230 386b57af Iustin Pop
2231 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2232 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2233 a8083063 Iustin Pop

2234 10c2650b Iustin Pop
  @type top_dirs: list
2235 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2236 10c2650b Iustin Pop
      search (if not given defaults to
2237 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2238 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2239 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2240 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2241 bad78e66 Iustin Pop
      search paths, where:
2242 255dcebd Iustin Pop
          - name is the (potential) OS name
2243 255dcebd Iustin Pop
          - path is the full path to the OS
2244 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2245 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2246 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2247 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2248 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2249 a8083063 Iustin Pop

2250 a8083063 Iustin Pop
  """
2251 7c3d51d4 Guido Trotter
  if top_dirs is None:
2252 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2253 a8083063 Iustin Pop
2254 a8083063 Iustin Pop
  result = []
2255 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2256 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2257 7c3d51d4 Guido Trotter
      try:
2258 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2259 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2260 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2261 7c3d51d4 Guido Trotter
        break
2262 7c3d51d4 Guido Trotter
      for name in f_names:
2263 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2264 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2265 255dcebd Iustin Pop
        if status:
2266 255dcebd Iustin Pop
          diagnose = ""
2267 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2268 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2269 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2270 255dcebd Iustin Pop
        else:
2271 255dcebd Iustin Pop
          diagnose = os_inst
2272 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2273 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2274 bad78e66 Iustin Pop
                       parameters, api_versions))
2275 a8083063 Iustin Pop
2276 c26a6bd2 Iustin Pop
  return result
2277 a8083063 Iustin Pop
2278 a8083063 Iustin Pop
2279 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2280 a8083063 Iustin Pop
  """Create an OS instance from disk.
2281 a8083063 Iustin Pop

2282 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2283 8e70b181 Iustin Pop
  valid OS name.
2284 a8083063 Iustin Pop

2285 8ee4dc80 Guido Trotter
  @type base_dir: string
2286 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2287 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2288 255dcebd Iustin Pop
  @rtype: tuple
2289 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2290 255dcebd Iustin Pop
      or error message
2291 7c3d51d4 Guido Trotter

2292 a8083063 Iustin Pop
  """
2293 56bcd3f4 Guido Trotter
  if base_dir is None:
2294 710f30ec Michael Hanselmann
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2295 c34c0cfd Iustin Pop
  else:
2296 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2297 f95c81bf Iustin Pop
2298 f95c81bf Iustin Pop
  if os_dir is None:
2299 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
2300 a8083063 Iustin Pop
2301 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2302 255dcebd Iustin Pop
  if not status:
2303 255dcebd Iustin Pop
    # push the error up
2304 255dcebd Iustin Pop
    return status, api_versions
2305 a8083063 Iustin Pop
2306 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2307 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2308 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2309 a8083063 Iustin Pop
2310 35007011 Iustin Pop
  # OS Files dictionary, we will populate it with the absolute path
2311 35007011 Iustin Pop
  # names; if the value is True, then it is a required file, otherwise
2312 35007011 Iustin Pop
  # an optional one
2313 35007011 Iustin Pop
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2314 a8083063 Iustin Pop
2315 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
2316 35007011 Iustin Pop
    os_files[constants.OS_VARIANTS_FILE] = False
2317 95075fba Guido Trotter
2318 c7d04a6b Iustin Pop
  if max(api_versions) >= constants.OS_API_V20:
2319 35007011 Iustin Pop
    os_files[constants.OS_PARAMETERS_FILE] = True
2320 c7d04a6b Iustin Pop
  else:
2321 c7d04a6b Iustin Pop
    del os_files[constants.OS_SCRIPT_VERIFY]
2322 c7d04a6b Iustin Pop
2323 35007011 Iustin Pop
  for (filename, required) in os_files.items():
2324 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
2325 a8083063 Iustin Pop
2326 a8083063 Iustin Pop
    try:
2327 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
2328 a8083063 Iustin Pop
    except EnvironmentError, err:
2329 35007011 Iustin Pop
      if err.errno == errno.ENOENT and not required:
2330 35007011 Iustin Pop
        del os_files[filename]
2331 35007011 Iustin Pop
        continue
2332 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
2333 eb93b673 Guido Trotter
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2334 a8083063 Iustin Pop
2335 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2336 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
2337 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
2338 255dcebd Iustin Pop
2339 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
2340 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2341 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
2342 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
2343 0757c107 Guido Trotter
2344 845da3e8 Iustin Pop
  variants = []
2345 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
2346 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2347 95075fba Guido Trotter
    try:
2348 5a7cb9d3 Iustin Pop
      variants = \
2349 5a7cb9d3 Iustin Pop
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2350 95075fba Guido Trotter
    except EnvironmentError, err:
2351 35007011 Iustin Pop
      # we accept missing files, but not other errors
2352 35007011 Iustin Pop
      if err.errno != errno.ENOENT:
2353 35007011 Iustin Pop
        return False, ("Error while reading the OS variants file at %s: %s" %
2354 eb93b673 Guido Trotter
                       (variants_file, utils.ErrnoOrStr(err)))
2355 0757c107 Guido Trotter
2356 c7d04a6b Iustin Pop
  parameters = []
2357 c7d04a6b Iustin Pop
  if constants.OS_PARAMETERS_FILE in os_files:
2358 c7d04a6b Iustin Pop
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2359 c7d04a6b Iustin Pop
    try:
2360 c7d04a6b Iustin Pop
      parameters = utils.ReadFile(parameters_file).splitlines()
2361 c7d04a6b Iustin Pop
    except EnvironmentError, err:
2362 c7d04a6b Iustin Pop
      return False, ("Error while reading the OS parameters file at %s: %s" %
2363 eb93b673 Guido Trotter
                     (parameters_file, utils.ErrnoOrStr(err)))
2364 c7d04a6b Iustin Pop
    parameters = [v.split(None, 1) for v in parameters]
2365 c7d04a6b Iustin Pop
2366 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
2367 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2368 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2369 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2370 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2371 40684c3a Iustin Pop
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2372 40684c3a Iustin Pop
                                                 None),
2373 95075fba Guido Trotter
                      supported_variants=variants,
2374 c7d04a6b Iustin Pop
                      supported_parameters=parameters,
2375 255dcebd Iustin Pop
                      api_versions=api_versions)
2376 255dcebd Iustin Pop
  return True, os_obj
2377 255dcebd Iustin Pop
2378 255dcebd Iustin Pop
2379 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
2380 255dcebd Iustin Pop
  """Create an OS instance from disk.
2381 255dcebd Iustin Pop

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

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

2389 255dcebd Iustin Pop
  @type base_dir: string
2390 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2391 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2392 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2393 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2394 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2395 255dcebd Iustin Pop

2396 255dcebd Iustin Pop
  """
2397 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2398 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2399 255dcebd Iustin Pop
2400 255dcebd Iustin Pop
  if not status:
2401 255dcebd Iustin Pop
    _Fail(payload)
2402 a8083063 Iustin Pop
2403 255dcebd Iustin Pop
  return payload
2404 a8083063 Iustin Pop
2405 a8083063 Iustin Pop
2406 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2407 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2408 2266edb2 Guido Trotter

2409 a025e535 Vitaly Kuznetsov
  @type os_name: str
2410 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2411 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2412 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2413 1bdcbbab Iustin Pop
  @type os_params: dict
2414 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2415 2266edb2 Guido Trotter
  @type debug: integer
2416 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2417 2266edb2 Guido Trotter
  @rtype: dict
2418 2266edb2 Guido Trotter
  @return: dict of environment variables
2419 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2420 10c2650b Iustin Pop
      cannot be found
2421 2266edb2 Guido Trotter

2422 2266edb2 Guido Trotter
  """
2423 2266edb2 Guido Trotter
  result = {}
2424 099c52ad Iustin Pop
  api_version = \
2425 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2426 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2427 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2428 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2429 efaa9b06 Iustin Pop
2430 efaa9b06 Iustin Pop
  # OS variants
2431 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2432 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2433 870dc44c Iustin Pop
    if not variant:
2434 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2435 35007011 Iustin Pop
  else:
2436 35007011 Iustin Pop
    variant = ""
2437 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2438 efaa9b06 Iustin Pop
2439 1bdcbbab Iustin Pop
  # OS params
2440 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2441 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2442 1bdcbbab Iustin Pop
2443 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
2444 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
2445 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
2446 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
2447 9a6ade06 Iustin Pop
2448 efaa9b06 Iustin Pop
  return result
2449 efaa9b06 Iustin Pop
2450 efaa9b06 Iustin Pop
2451 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2452 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2453 efaa9b06 Iustin Pop

2454 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2455 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2456 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2457 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2458 efaa9b06 Iustin Pop
  @type debug: integer
2459 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2460 efaa9b06 Iustin Pop
  @rtype: dict
2461 efaa9b06 Iustin Pop
  @return: dict of environment variables
2462 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2463 efaa9b06 Iustin Pop
      cannot be found
2464 efaa9b06 Iustin Pop

2465 efaa9b06 Iustin Pop
  """
2466 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2467 efaa9b06 Iustin Pop
2468 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2469 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2470 f2165b8a Iustin Pop
2471 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2472 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2473 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2474 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2475 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2476 efaa9b06 Iustin Pop
2477 efaa9b06 Iustin Pop
  # Disks
2478 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2479 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2480 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2481 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2482 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2483 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2484 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2485 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2486 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2487 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2488 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2489 d0c8c01d Iustin Pop
        "file:%s" % disk.physical_id[0]
2490 efaa9b06 Iustin Pop
2491 efaa9b06 Iustin Pop
  # NICs
2492 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2493 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2494 2266edb2 Guido Trotter
    if nic.ip:
2495 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2496 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2497 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2498 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2499 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2500 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2501 d89168ff Guido Trotter
    if nic.netinfo:
2502 d89168ff Guido Trotter
      nobj = objects.Network.FromDict(nic.netinfo)
2503 d89168ff Guido Trotter
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2504 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2505 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2506 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2507 2266edb2 Guido Trotter
2508 efaa9b06 Iustin Pop
  # HV/BE params
2509 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2510 67fc3042 Iustin Pop
    for key, value in source.items():
2511 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2512 67fc3042 Iustin Pop
2513 2266edb2 Guido Trotter
  return result
2514 a8083063 Iustin Pop
2515 f2e07bb4 Michael Hanselmann
2516 b954f097 Constantinos Venetsanopoulos
def DiagnoseExtStorage(top_dirs=None):
2517 b954f097 Constantinos Venetsanopoulos
  """Compute the validity for all ExtStorage Providers.
2518 b954f097 Constantinos Venetsanopoulos

2519 b954f097 Constantinos Venetsanopoulos
  @type top_dirs: list
2520 b954f097 Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
2521 b954f097 Constantinos Venetsanopoulos
      search (if not given defaults to
2522 b954f097 Constantinos Venetsanopoulos
      L{pathutils.ES_SEARCH_PATH})
2523 b954f097 Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
2524 b954f097 Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
2525 b954f097 Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
2526 b954f097 Constantinos Venetsanopoulos
      search paths, where:
2527 b954f097 Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
2528 b954f097 Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
2529 b954f097 Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
2530 b954f097 Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
2531 b954f097 Constantinos Venetsanopoulos
            otherwise empty
2532 b954f097 Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
2533 b954f097 Constantinos Venetsanopoulos

2534 b954f097 Constantinos Venetsanopoulos
  """
2535 b954f097 Constantinos Venetsanopoulos
  if top_dirs is None:
2536 b954f097 Constantinos Venetsanopoulos
    top_dirs = pathutils.ES_SEARCH_PATH
2537 b954f097 Constantinos Venetsanopoulos
2538 b954f097 Constantinos Venetsanopoulos
  result = []
2539 b954f097 Constantinos Venetsanopoulos
  for dir_name in top_dirs:
2540 b954f097 Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
2541 b954f097 Constantinos Venetsanopoulos
      try:
2542 b954f097 Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
2543 b954f097 Constantinos Venetsanopoulos
      except EnvironmentError, err:
2544 b954f097 Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
2545 b954f097 Constantinos Venetsanopoulos
                          dir_name, err)
2546 b954f097 Constantinos Venetsanopoulos
        break
2547 b954f097 Constantinos Venetsanopoulos
      for name in f_names:
2548 b954f097 Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
2549 b954f097 Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2550 b954f097 Constantinos Venetsanopoulos
        if status:
2551 b954f097 Constantinos Venetsanopoulos
          diagnose = ""
2552 b954f097 Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
2553 b954f097 Constantinos Venetsanopoulos
        else:
2554 b954f097 Constantinos Venetsanopoulos
          diagnose = es_inst
2555 b954f097 Constantinos Venetsanopoulos
          parameters = []
2556 b954f097 Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
2557 b954f097 Constantinos Venetsanopoulos
2558 b954f097 Constantinos Venetsanopoulos
  return result
2559 b954f097 Constantinos Venetsanopoulos
2560 b954f097 Constantinos Venetsanopoulos
2561 cad0723b Iustin Pop
def BlockdevGrow(disk, amount, dryrun, backingstore):
2562 594609c0 Iustin Pop
  """Grow a stack of block devices.
2563 594609c0 Iustin Pop

2564 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2565 10c2650b Iustin Pop
  first ones to resize.
2566 594609c0 Iustin Pop

2567 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2568 10c2650b Iustin Pop
  @param disk: the disk to be grown
2569 a59faf4b Iustin Pop
  @type amount: integer
2570 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2571 a59faf4b Iustin Pop
  @type dryrun: boolean
2572 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2573 a59faf4b Iustin Pop
      only, without actually increasing the size
2574 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
2575 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2576 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
2577 10c2650b Iustin Pop
  @rtype: (status, result)
2578 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2579 a59faf4b Iustin Pop
      the errors message if status is False
2580 594609c0 Iustin Pop

2581 594609c0 Iustin Pop
  """
2582 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2583 594609c0 Iustin Pop
  if r_dev is None:
2584 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2585 594609c0 Iustin Pop
2586 594609c0 Iustin Pop
  try:
2587 cad0723b Iustin Pop
    r_dev.Grow(amount, dryrun, backingstore)
2588 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2589 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2590 594609c0 Iustin Pop
2591 594609c0 Iustin Pop
2592 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2593 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2594 a8083063 Iustin Pop

2595 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2596 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2597 a8083063 Iustin Pop

2598 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2599 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2600 e9e9263d Guido Trotter
  @rtype: string
2601 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2602 a8083063 Iustin Pop

2603 098c0958 Michael Hanselmann
  """
2604 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2605 433c63aa Iustin Pop
    if not disk.children:
2606 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2607 433c63aa Iustin Pop
            disk.unique_id)
2608 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2609 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2610 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2611 a8083063 Iustin Pop
    if r_dev is not None:
2612 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2613 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2614 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2615 a8083063 Iustin Pop
    else:
2616 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2617 a8083063 Iustin Pop
  else:
2618 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2619 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2620 a8083063 Iustin Pop
2621 a8083063 Iustin Pop
2622 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
2623 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
2624 48e175a2 Iustin Pop

2625 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
2626 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
2627 48e175a2 Iustin Pop
  for example after renames.
2628 48e175a2 Iustin Pop

2629 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
2630 48e175a2 Iustin Pop
  @param disk: the disk to be grown
2631 48e175a2 Iustin Pop
  @type info: string
2632 48e175a2 Iustin Pop
  @param info: new 'info' metadata
2633 48e175a2 Iustin Pop
  @rtype: (status, result)
2634 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2635 48e175a2 Iustin Pop
      the errors message if status is False
2636 48e175a2 Iustin Pop

2637 48e175a2 Iustin Pop
  """
2638 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2639 48e175a2 Iustin Pop
  if r_dev is None:
2640 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2641 48e175a2 Iustin Pop
2642 48e175a2 Iustin Pop
  try:
2643 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
2644 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
2645 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
2646 48e175a2 Iustin Pop
2647 48e175a2 Iustin Pop
2648 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2649 a8083063 Iustin Pop
  """Write out the export configuration information.
2650 a8083063 Iustin Pop

2651 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2652 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2653 10c2650b Iustin Pop
      saving configuration
2654 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2655 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2656 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2657 a8083063 Iustin Pop

2658 c26a6bd2 Iustin Pop
  @rtype: None
2659 a8083063 Iustin Pop

2660 098c0958 Michael Hanselmann
  """
2661 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2662 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2663 a8083063 Iustin Pop
2664 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2665 a8083063 Iustin Pop
2666 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2667 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
2668 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2669 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2670 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
2671 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2672 a8083063 Iustin Pop
2673 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2674 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
2675 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2676 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2677 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
2678 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
2679 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2680 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
2681 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2682 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2683 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2684 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2685 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2686 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2687 66f93869 Manuel Franceschini
2688 95268cc3 Iustin Pop
  nic_total = 0
2689 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2690 95268cc3 Iustin Pop
    nic_total += 1
2691 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
2692 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
2693 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2694 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2695 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
2696 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2697 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2698 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
2699 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2700 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2701 a8083063 Iustin Pop
2702 726d7d68 Iustin Pop
  disk_total = 0
2703 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2704 19d7f90a Guido Trotter
    if disk:
2705 726d7d68 Iustin Pop
      disk_total += 1
2706 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2707 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
2708 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2709 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
2710 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2711 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
2712 d0c8c01d Iustin Pop
2713 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2714 a8083063 Iustin Pop
2715 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2716 3c8954ad Iustin Pop
2717 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2718 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2719 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2720 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2721 3c8954ad Iustin Pop
2722 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2723 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2724 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2725 3c8954ad Iustin Pop
2726 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2727 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2728 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2729 535b49cb Iustin Pop
2730 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2731 726d7d68 Iustin Pop
                  data=config.Dumps())
2732 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2733 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2734 a8083063 Iustin Pop
2735 a8083063 Iustin Pop
2736 a8083063 Iustin Pop
def ExportInfo(dest):
2737 a8083063 Iustin Pop
  """Get export configuration information.
2738 a8083063 Iustin Pop

2739 10c2650b Iustin Pop
  @type dest: str
2740 10c2650b Iustin Pop
  @param dest: directory containing the export
2741 a8083063 Iustin Pop

2742 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2743 10c2650b Iustin Pop
  @return: a serializable config file containing the
2744 10c2650b Iustin Pop
      export info
2745 a8083063 Iustin Pop

2746 a8083063 Iustin Pop
  """
2747 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2748 a8083063 Iustin Pop
2749 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2750 a8083063 Iustin Pop
  config.read(cff)
2751 a8083063 Iustin Pop
2752 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2753 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2754 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2755 a8083063 Iustin Pop
2756 c26a6bd2 Iustin Pop
  return config.Dumps()
2757 a8083063 Iustin Pop
2758 a8083063 Iustin Pop
2759 a8083063 Iustin Pop
def ListExports():
2760 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2761 098c0958 Michael Hanselmann

2762 10c2650b Iustin Pop
  @rtype: list
2763 10c2650b Iustin Pop
  @return: list of the exports
2764 10c2650b Iustin Pop

2765 a8083063 Iustin Pop
  """
2766 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
2767 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2768 a8083063 Iustin Pop
  else:
2769 afdc3985 Iustin Pop
    _Fail("No exports directory")
2770 a8083063 Iustin Pop
2771 a8083063 Iustin Pop
2772 a8083063 Iustin Pop
def RemoveExport(export):
2773 a8083063 Iustin Pop
  """Remove an existing export from the node.
2774 a8083063 Iustin Pop

2775 10c2650b Iustin Pop
  @type export: str
2776 10c2650b Iustin Pop
  @param export: the name of the export to remove
2777 c26a6bd2 Iustin Pop
  @rtype: None
2778 a8083063 Iustin Pop

2779 098c0958 Michael Hanselmann
  """
2780 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2781 a8083063 Iustin Pop
2782 35fbcd11 Iustin Pop
  try:
2783 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2784 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2785 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2786 a8083063 Iustin Pop
2787 a8083063 Iustin Pop
2788 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2789 f3e513ad Iustin Pop
  """Rename a list of block devices.
2790 f3e513ad Iustin Pop

2791 10c2650b Iustin Pop
  @type devlist: list of tuples
2792 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2793 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2794 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2795 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2796 10c2650b Iustin Pop
      rename it to
2797 10c2650b Iustin Pop
  @rtype: boolean
2798 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2799 f3e513ad Iustin Pop

2800 f3e513ad Iustin Pop
  """
2801 6b5e3f70 Iustin Pop
  msgs = []
2802 f3e513ad Iustin Pop
  result = True
2803 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2804 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2805 f3e513ad Iustin Pop
    if dev is None:
2806 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2807 f3e513ad Iustin Pop
      result = False
2808 f3e513ad Iustin Pop
      continue
2809 f3e513ad Iustin Pop
    try:
2810 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2811 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2812 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2813 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2814 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2815 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2816 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2817 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2818 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2819 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2820 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2821 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2822 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2823 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2824 f3e513ad Iustin Pop
      result = False
2825 afdc3985 Iustin Pop
  if not result:
2826 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2827 f3e513ad Iustin Pop
2828 f3e513ad Iustin Pop
2829 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2830 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2831 778b75bb Manuel Franceschini

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

2836 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2837 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2838 d61cbe76 Iustin Pop

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

2841 778b75bb Manuel Franceschini
  """
2842 63a3d8f7 Michael Hanselmann
  if not (constants.ENABLE_FILE_STORAGE or
2843 63a3d8f7 Michael Hanselmann
          constants.ENABLE_SHARED_FILE_STORAGE):
2844 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2845 5e09a309 Michael Hanselmann
2846 5e09a309 Michael Hanselmann
  bdev.CheckFileStoragePath(fs_dir)
2847 5e09a309 Michael Hanselmann
2848 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
2849 778b75bb Manuel Franceschini
2850 778b75bb Manuel Franceschini
2851 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2852 778b75bb Manuel Franceschini
  """Create file storage directory.
2853 778b75bb Manuel Franceschini

2854 b1206984 Iustin Pop
  @type file_storage_dir: str
2855 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2856 778b75bb Manuel Franceschini

2857 b1206984 Iustin Pop
  @rtype: tuple
2858 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2859 b1206984 Iustin Pop
      creation was successful or not
2860 778b75bb Manuel Franceschini

2861 778b75bb Manuel Franceschini
  """
2862 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2863 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2864 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2865 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2866 b2b8bcce Iustin Pop
            file_storage_dir)
2867 778b75bb Manuel Franceschini
  else:
2868 b2b8bcce Iustin Pop
    try:
2869 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2870 b2b8bcce Iustin Pop
    except OSError, err:
2871 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2872 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2873 778b75bb Manuel Franceschini
2874 778b75bb Manuel Franceschini
2875 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2876 778b75bb Manuel Franceschini
  """Remove file storage directory.
2877 778b75bb Manuel Franceschini

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

2880 10c2650b Iustin Pop
  @type file_storage_dir: str
2881 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2882 10c2650b Iustin Pop
  @rtype: tuple (success,)
2883 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2884 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2885 778b75bb Manuel Franceschini

2886 778b75bb Manuel Franceschini
  """
2887 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2888 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2889 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2890 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2891 b2b8bcce Iustin Pop
            file_storage_dir)
2892 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2893 b2b8bcce Iustin Pop
    try:
2894 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2895 b2b8bcce Iustin Pop
    except OSError, err:
2896 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2897 b2b8bcce Iustin Pop
            file_storage_dir, err)
2898 b2b8bcce Iustin Pop
2899 778b75bb Manuel Franceschini
2900 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2901 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2902 778b75bb Manuel Franceschini

2903 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2904 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2905 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2906 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2907 10c2650b Iustin Pop
  @rtype: tuple (success,)
2908 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2909 10c2650b Iustin Pop
      whether the operation was successful
2910 778b75bb Manuel Franceschini

2911 778b75bb Manuel Franceschini
  """
2912 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2913 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2914 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2915 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2916 b2b8bcce Iustin Pop
      try:
2917 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2918 b2b8bcce Iustin Pop
      except OSError, err:
2919 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2920 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2921 778b75bb Manuel Franceschini
    else:
2922 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2923 b2b8bcce Iustin Pop
            old_file_storage_dir)
2924 b2b8bcce Iustin Pop
  else:
2925 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2926 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2927 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2928 778b75bb Manuel Franceschini
2929 778b75bb Manuel Franceschini
2930 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2931 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2932 ca52cdeb Michael Hanselmann

2933 10c2650b Iustin Pop
  @type file_name: str
2934 10c2650b Iustin Pop
  @param file_name: the file name we should check
2935 c8457ce7 Iustin Pop
  @rtype: None
2936 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2937 10c2650b Iustin Pop

2938 ca52cdeb Michael Hanselmann
  """
2939 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2940 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2941 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2942 dc31eae3 Michael Hanselmann
2943 dc31eae3 Michael Hanselmann
2944 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2945 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2946 dc31eae3 Michael Hanselmann

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

2950 10c2650b Iustin Pop
  @type file_name: str
2951 10c2650b Iustin Pop
  @param file_name: the job file name
2952 10c2650b Iustin Pop
  @type content: str
2953 10c2650b Iustin Pop
  @param content: the new job contents
2954 10c2650b Iustin Pop
  @rtype: boolean
2955 10c2650b Iustin Pop
  @return: the success of the operation
2956 10c2650b Iustin Pop

2957 dc31eae3 Michael Hanselmann
  """
2958 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2959 cffbbae7 Michael Hanselmann
2960 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2961 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2962 ca52cdeb Michael Hanselmann
2963 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2964 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2965 fe05a931 Michele Tartara
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
2966 ca52cdeb Michael Hanselmann
2967 ca52cdeb Michael Hanselmann
2968 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2969 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2970 af5ebcb1 Michael Hanselmann

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

2973 10c2650b Iustin Pop
  @type old: str
2974 10c2650b Iustin Pop
  @param old: the old (actual) file name
2975 10c2650b Iustin Pop
  @type new: str
2976 10c2650b Iustin Pop
  @param new: the desired file name
2977 c8457ce7 Iustin Pop
  @rtype: tuple
2978 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2979 10c2650b Iustin Pop

2980 af5ebcb1 Michael Hanselmann
  """
2981 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
2982 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
2983 cffbbae7 Michael Hanselmann
2984 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2985 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2986 af5ebcb1 Michael Hanselmann
2987 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
2988 8e5a705d René Nussbaumer
2989 fe05a931 Michele Tartara
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
2990 fe05a931 Michele Tartara
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
2991 af5ebcb1 Michael Hanselmann
2992 af5ebcb1 Michael Hanselmann
2993 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2994 d61cbe76 Iustin Pop
  """Closes the given block devices.
2995 d61cbe76 Iustin Pop

2996 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2997 10c2650b Iustin Pop
  DRBD).
2998 10c2650b Iustin Pop

2999 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
3000 b2e7666a Iustin Pop
      of this instance will be removed
3001 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
3002 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
3003 10c2650b Iustin Pop
  @rtype: tuple (success, message)
3004 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
3005 10c2650b Iustin Pop
      indicates the succes of the operation, and message
3006 10c2650b Iustin Pop
      which will contain the error details in case we
3007 10c2650b Iustin Pop
      failed
3008 d61cbe76 Iustin Pop

3009 d61cbe76 Iustin Pop
  """
3010 d61cbe76 Iustin Pop
  bdevs = []
3011 d61cbe76 Iustin Pop
  for cf in disks:
3012 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
3013 d61cbe76 Iustin Pop
    if rd is None:
3014 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
3015 d61cbe76 Iustin Pop
    bdevs.append(rd)
3016 d61cbe76 Iustin Pop
3017 d61cbe76 Iustin Pop
  msg = []
3018 d61cbe76 Iustin Pop
  for rd in bdevs:
3019 d61cbe76 Iustin Pop
    try:
3020 d61cbe76 Iustin Pop
      rd.Close()
3021 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
3022 d61cbe76 Iustin Pop
      msg.append(str(err))
3023 d61cbe76 Iustin Pop
  if msg:
3024 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3025 d61cbe76 Iustin Pop
  else:
3026 b2e7666a Iustin Pop
    if instance_name:
3027 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
3028 d61cbe76 Iustin Pop
3029 d61cbe76 Iustin Pop
3030 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
3031 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
3032 6217e295 Iustin Pop

3033 6217e295 Iustin Pop
  @type hvname: string
3034 6217e295 Iustin Pop
  @param hvname: the hypervisor name
3035 6217e295 Iustin Pop
  @type hvparams: dict
3036 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
3037 c26a6bd2 Iustin Pop
  @rtype: None
3038 6217e295 Iustin Pop

3039 6217e295 Iustin Pop
  """
3040 6217e295 Iustin Pop
  try:
3041 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
3042 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
3043 6217e295 Iustin Pop
  except errors.HypervisorError, err:
3044 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
3045 6217e295 Iustin Pop
3046 6217e295 Iustin Pop
3047 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
3048 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
3049 acd9ff9e Iustin Pop

3050 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
3051 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
3052 acd9ff9e Iustin Pop
  @type parameters: list
3053 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
3054 acd9ff9e Iustin Pop

3055 acd9ff9e Iustin Pop
  """
3056 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
3057 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
3058 acd9ff9e Iustin Pop
  if delta:
3059 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
3060 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3061 acd9ff9e Iustin Pop
3062 acd9ff9e Iustin Pop
3063 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
3064 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
3065 acd9ff9e Iustin Pop

3066 acd9ff9e Iustin Pop
  @type required: boolean
3067 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3068 acd9ff9e Iustin Pop
      failure or not
3069 acd9ff9e Iustin Pop
  @type osname: string
3070 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3071 acd9ff9e Iustin Pop
  @type checks: list
3072 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3073 acd9ff9e Iustin Pop
  @type osparams: dict
3074 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
3075 acd9ff9e Iustin Pop
  @rtype: boolean
3076 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3077 acd9ff9e Iustin Pop
      found and L{required} was false
3078 acd9ff9e Iustin Pop

3079 acd9ff9e Iustin Pop
  """
3080 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3081 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3082 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3083 acd9ff9e Iustin Pop
3084 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3085 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3086 acd9ff9e Iustin Pop
3087 acd9ff9e Iustin Pop
  if not status:
3088 acd9ff9e Iustin Pop
    if required:
3089 acd9ff9e Iustin Pop
      _Fail(tbv)
3090 acd9ff9e Iustin Pop
    else:
3091 acd9ff9e Iustin Pop
      return False
3092 acd9ff9e Iustin Pop
3093 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3094 72db3fd7 Iustin Pop
    return True
3095 72db3fd7 Iustin Pop
3096 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3097 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3098 acd9ff9e Iustin Pop
3099 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3100 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3101 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3102 acd9ff9e Iustin Pop
  if result.failed:
3103 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3104 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3105 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3106 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3107 acd9ff9e Iustin Pop
3108 acd9ff9e Iustin Pop
  return True
3109 acd9ff9e Iustin Pop
3110 acd9ff9e Iustin Pop
3111 56aa9fd5 Iustin Pop
def DemoteFromMC():
3112 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3113 56aa9fd5 Iustin Pop

3114 56aa9fd5 Iustin Pop
  """
3115 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3116 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3117 56aa9fd5 Iustin Pop
  if master == myself:
3118 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3119 f154a7a3 Michael Hanselmann
3120 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3121 f154a7a3 Michael Hanselmann
  if not result.failed:
3122 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3123 f154a7a3 Michael Hanselmann
3124 56aa9fd5 Iustin Pop
  try:
3125 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3126 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3127 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3128 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3129 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3130 f154a7a3 Michael Hanselmann
3131 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3132 56aa9fd5 Iustin Pop
3133 56aa9fd5 Iustin Pop
3134 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3135 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3136 f942a838 Michael Hanselmann

3137 f942a838 Michael Hanselmann
  """
3138 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3139 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3140 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3141 f942a838 Michael Hanselmann
3142 f942a838 Michael Hanselmann
3143 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3144 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3145 f942a838 Michael Hanselmann

3146 f942a838 Michael Hanselmann
  @type validity: int
3147 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3148 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3149 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3150 f942a838 Michael Hanselmann

3151 f942a838 Michael Hanselmann
  """
3152 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3153 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3154 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3155 f942a838 Michael Hanselmann
3156 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3157 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3158 f942a838 Michael Hanselmann
  try:
3159 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3160 f942a838 Michael Hanselmann
    assert len(name) > 5
3161 f942a838 Michael Hanselmann
3162 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3163 f942a838 Michael Hanselmann
3164 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3165 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3166 f942a838 Michael Hanselmann
3167 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3168 f942a838 Michael Hanselmann
    return (name, cert_pem)
3169 f942a838 Michael Hanselmann
  except Exception:
3170 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3171 f942a838 Michael Hanselmann
    raise
3172 f942a838 Michael Hanselmann
3173 f942a838 Michael Hanselmann
3174 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3175 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3176 f942a838 Michael Hanselmann

3177 f942a838 Michael Hanselmann
  @type name: string
3178 f942a838 Michael Hanselmann
  @param name: Certificate name
3179 f942a838 Michael Hanselmann

3180 f942a838 Michael Hanselmann
  """
3181 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3182 f942a838 Michael Hanselmann
3183 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3184 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3185 f942a838 Michael Hanselmann
3186 f942a838 Michael Hanselmann
  try:
3187 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3188 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3189 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3190 f942a838 Michael Hanselmann
          cert_dir, err)
3191 f942a838 Michael Hanselmann
3192 f942a838 Michael Hanselmann
3193 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3194 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3195 1651d116 Michael Hanselmann

3196 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3197 1651d116 Michael Hanselmann
  @param instance: The instance object
3198 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3199 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3200 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3201 1651d116 Michael Hanselmann

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

3307 1651d116 Michael Hanselmann
  """
3308 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3309 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3310 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3311 1651d116 Michael Hanselmann
3312 1651d116 Michael Hanselmann
3313 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3314 6613661a Iustin Pop
                            ieio, ieioargs):
3315 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3316 1651d116 Michael Hanselmann

3317 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3318 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3319 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3320 1651d116 Michael Hanselmann
  @type host: string
3321 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3322 1651d116 Michael Hanselmann
  @type port: int
3323 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3324 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3325 1651d116 Michael Hanselmann
  @param instance: Instance object
3326 6613661a Iustin Pop
  @type component: string
3327 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3328 6613661a Iustin Pop
      e.g. 'disk/0'
3329 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3330 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3331 1651d116 Michael Hanselmann

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

3444 1651d116 Michael Hanselmann
  @type names: sequence
3445 1651d116 Michael Hanselmann
  @param names: List of names
3446 1651d116 Michael Hanselmann
  @rtype: List of dicts
3447 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3448 1651d116 Michael Hanselmann
           status couldn't be read
3449 1651d116 Michael Hanselmann

3450 1651d116 Michael Hanselmann
  """
3451 1651d116 Michael Hanselmann
  result = []
3452 1651d116 Michael Hanselmann
3453 1651d116 Michael Hanselmann
  for name in names:
3454 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3455 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3456 1651d116 Michael Hanselmann
3457 1651d116 Michael Hanselmann
    try:
3458 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3459 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3460 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3461 1651d116 Michael Hanselmann
        raise
3462 1651d116 Michael Hanselmann
      data = None
3463 1651d116 Michael Hanselmann
3464 1651d116 Michael Hanselmann
    if not data:
3465 1651d116 Michael Hanselmann
      result.append(None)
3466 1651d116 Michael Hanselmann
      continue
3467 1651d116 Michael Hanselmann
3468 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3469 1651d116 Michael Hanselmann
3470 1651d116 Michael Hanselmann
  return result
3471 1651d116 Michael Hanselmann
3472 1651d116 Michael Hanselmann
3473 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3474 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3475 f81c4737 Michael Hanselmann

3476 f81c4737 Michael Hanselmann
  """
3477 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3478 f81c4737 Michael Hanselmann
3479 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3480 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3481 f81c4737 Michael Hanselmann
3482 f81c4737 Michael Hanselmann
  if pid:
3483 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3484 f81c4737 Michael Hanselmann
                 name, pid)
3485 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3486 f81c4737 Michael Hanselmann
3487 f81c4737 Michael Hanselmann
3488 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3489 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3490 1651d116 Michael Hanselmann

3491 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3492 1651d116 Michael Hanselmann
  whole status directory is removed.
3493 1651d116 Michael Hanselmann

3494 1651d116 Michael Hanselmann
  """
3495 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3496 1651d116 Michael Hanselmann
3497 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3498 1651d116 Michael Hanselmann
3499 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3500 1651d116 Michael Hanselmann
3501 1651d116 Michael Hanselmann
  if pid:
3502 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3503 1651d116 Michael Hanselmann
                 name, pid)
3504 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3505 1651d116 Michael Hanselmann
3506 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3507 1651d116 Michael Hanselmann
3508 1651d116 Michael Hanselmann
3509 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3510 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3511 6b93ec9d Iustin Pop

3512 6b93ec9d Iustin Pop
  """
3513 6b93ec9d Iustin Pop
  # set the correct physical ID
3514 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3515 6b93ec9d Iustin Pop
  for cf in disks:
3516 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3517 6b93ec9d Iustin Pop
3518 6b93ec9d Iustin Pop
  bdevs = []
3519 6b93ec9d Iustin Pop
3520 6b93ec9d Iustin Pop
  for cf in disks:
3521 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3522 6b93ec9d Iustin Pop
    if rd is None:
3523 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3524 6b93ec9d Iustin Pop
    bdevs.append(rd)
3525 5a533f8a Iustin Pop
  return bdevs
3526 6b93ec9d Iustin Pop
3527 6b93ec9d Iustin Pop
3528 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3529 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3530 6b93ec9d Iustin Pop

3531 6b93ec9d Iustin Pop
  """
3532 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3533 6b93ec9d Iustin Pop
3534 6b93ec9d Iustin Pop
  # disconnect disks
3535 6b93ec9d Iustin Pop
  for rd in bdevs:
3536 6b93ec9d Iustin Pop
    try:
3537 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3538 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3539 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3540 2cc6781a Iustin Pop
            err, exc=True)
3541 6b93ec9d Iustin Pop
3542 6b93ec9d Iustin Pop
3543 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3544 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3545 6b93ec9d Iustin Pop

3546 6b93ec9d Iustin Pop
  """
3547 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3548 6b93ec9d Iustin Pop
3549 6b93ec9d Iustin Pop
  if multimaster:
3550 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3551 6b93ec9d Iustin Pop
      try:
3552 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3553 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3554 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3555 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3556 6b93ec9d Iustin Pop
  # needed primary mode
3557 6b93ec9d Iustin Pop
  for rd in bdevs:
3558 6b93ec9d Iustin Pop
    try:
3559 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3560 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3561 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3562 3c0cdc83 Michael Hanselmann
3563 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3564 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3565 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3566 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3567 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3568 3c0cdc83 Michael Hanselmann
3569 3c0cdc83 Michael Hanselmann
  def _Attach():
3570 6b93ec9d Iustin Pop
    all_connected = True
3571 3c0cdc83 Michael Hanselmann
3572 6b93ec9d Iustin Pop
    for rd in bdevs:
3573 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3574 3c0cdc83 Michael Hanselmann
3575 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3576 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3577 3c0cdc83 Michael Hanselmann
3578 6b93ec9d Iustin Pop
      if stats.is_standalone:
3579 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3580 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3581 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3582 6b93ec9d Iustin Pop
        try:
3583 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3584 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3585 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3586 3c0cdc83 Michael Hanselmann
3587 3c0cdc83 Michael Hanselmann
    if not all_connected:
3588 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3589 3c0cdc83 Michael Hanselmann
3590 3c0cdc83 Michael Hanselmann
  try:
3591 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3592 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3593 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3594 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3595 3c0cdc83 Michael Hanselmann
3596 6b93ec9d Iustin Pop
  if multimaster:
3597 6b93ec9d Iustin Pop
    # change to primary mode
3598 6b93ec9d Iustin Pop
    for rd in bdevs:
3599 d3da87b8 Iustin Pop
      try:
3600 d3da87b8 Iustin Pop
        rd.Open()
3601 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3602 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3603 6b93ec9d Iustin Pop
3604 6b93ec9d Iustin Pop
3605 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3606 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3607 6b93ec9d Iustin Pop

3608 6b93ec9d Iustin Pop
  """
3609 db8667b7 Iustin Pop
  def _helper(rd):
3610 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3611 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3612 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3613 db8667b7 Iustin Pop
    return stats
3614 db8667b7 Iustin Pop
3615 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3616 6b93ec9d Iustin Pop
3617 6b93ec9d Iustin Pop
  min_resync = 100
3618 6b93ec9d Iustin Pop
  alldone = True
3619 6b93ec9d Iustin Pop
  for rd in bdevs:
3620 db8667b7 Iustin Pop
    try:
3621 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3622 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3623 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3624 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3625 db8667b7 Iustin Pop
      # last check
3626 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3627 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3628 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3629 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3630 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3631 afdc3985 Iustin Pop
3632 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3633 6b93ec9d Iustin Pop
3634 6b93ec9d Iustin Pop
3635 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3636 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3637 c46b9782 Luca Bigliardi

3638 c46b9782 Luca Bigliardi
  """
3639 c46b9782 Luca Bigliardi
  try:
3640 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3641 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3642 c46b9782 Luca Bigliardi
    _Fail(str(err))
3643 c46b9782 Luca Bigliardi
3644 c46b9782 Luca Bigliardi
3645 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3646 f5118ade Iustin Pop
  """Hard-powercycle the node.
3647 f5118ade Iustin Pop

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

3651 f5118ade Iustin Pop
  """
3652 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3653 f5118ade Iustin Pop
  try:
3654 f5118ade Iustin Pop
    pid = os.fork()
3655 29921401 Iustin Pop
  except OSError:
3656 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3657 f5118ade Iustin Pop
    pid = 0
3658 f5118ade Iustin Pop
  if pid > 0:
3659 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3660 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3661 1af6ac0f Luca Bigliardi
  try:
3662 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3663 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3664 1af6ac0f Luca Bigliardi
    pass
3665 f5118ade Iustin Pop
  time.sleep(5)
3666 f5118ade Iustin Pop
  hyper.PowercycleNode()
3667 f5118ade Iustin Pop
3668 f5118ade Iustin Pop
3669 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
3670 45bc4635 Iustin Pop
  """Verifies a restricted command name.
3671 1a2eb2dc Michael Hanselmann

3672 1a2eb2dc Michael Hanselmann
  @type cmd: string
3673 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3674 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3675 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3676 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3677 1a2eb2dc Michael Hanselmann

3678 1a2eb2dc Michael Hanselmann
  """
3679 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
3680 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
3681 1a2eb2dc Michael Hanselmann
3682 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
3683 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
3684 1a2eb2dc Michael Hanselmann
3685 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3686 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
3687 1a2eb2dc Michael Hanselmann
3688 1a2eb2dc Michael Hanselmann
  return (True, None)
3689 1a2eb2dc Michael Hanselmann
3690 1a2eb2dc Michael Hanselmann
3691 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
3692 45bc4635 Iustin Pop
  """Common checks for restricted command file system directories and files.
3693 1a2eb2dc Michael Hanselmann

3694 1a2eb2dc Michael Hanselmann
  @type path: string
3695 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3696 1a2eb2dc Michael Hanselmann
  @param owner: C{None} or tuple containing UID and GID
3697 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or C{os.stat} result)
3698 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3699 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's the result of C{os.stat}
3700 1a2eb2dc Michael Hanselmann

3701 1a2eb2dc Michael Hanselmann
  """
3702 1a2eb2dc Michael Hanselmann
  if owner is None:
3703 1a2eb2dc Michael Hanselmann
    # Default to root as owner
3704 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
3705 1a2eb2dc Michael Hanselmann
3706 1a2eb2dc Michael Hanselmann
  try:
3707 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
3708 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
3709 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3710 1a2eb2dc Michael Hanselmann
3711 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3712 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
3713 1a2eb2dc Michael Hanselmann
3714 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
3715 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
3716 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3717 1a2eb2dc Michael Hanselmann
3718 1a2eb2dc Michael Hanselmann
  return (True, st)
3719 1a2eb2dc Michael Hanselmann
3720 1a2eb2dc Michael Hanselmann
3721 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3722 45bc4635 Iustin Pop
  """Verifies restricted command directory.
3723 1a2eb2dc Michael Hanselmann

3724 1a2eb2dc Michael Hanselmann
  @type path: string
3725 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3726 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3727 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3728 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3729 1a2eb2dc Michael Hanselmann

3730 1a2eb2dc Michael Hanselmann
  """
3731 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3732 1a2eb2dc Michael Hanselmann
3733 1a2eb2dc Michael Hanselmann
  if not status:
3734 1a2eb2dc Michael Hanselmann
    return (False, value)
3735 1a2eb2dc Michael Hanselmann
3736 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
3737 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
3738 1a2eb2dc Michael Hanselmann
3739 1a2eb2dc Michael Hanselmann
  return (True, None)
3740 1a2eb2dc Michael Hanselmann
3741 1a2eb2dc Michael Hanselmann
3742 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3743 45bc4635 Iustin Pop
  """Verifies a whole restricted command and returns its executable filename.
3744 1a2eb2dc Michael Hanselmann

3745 1a2eb2dc Michael Hanselmann
  @type path: string
3746 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
3747 1a2eb2dc Michael Hanselmann
  @type cmd: string
3748 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3749 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
3750 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3751 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
3752 1a2eb2dc Michael Hanselmann
    absolute path to the executable
3753 1a2eb2dc Michael Hanselmann

3754 1a2eb2dc Michael Hanselmann
  """
3755 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
3756 1a2eb2dc Michael Hanselmann
3757 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3758 1a2eb2dc Michael Hanselmann
3759 1a2eb2dc Michael Hanselmann
  if not status:
3760 1a2eb2dc Michael Hanselmann
    return (False, msg)
3761 1a2eb2dc Michael Hanselmann
3762 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
3763 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3764 1a2eb2dc Michael Hanselmann
3765 1a2eb2dc Michael Hanselmann
  return (True, executable)
3766 1a2eb2dc Michael Hanselmann
3767 1a2eb2dc Michael Hanselmann
3768 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
3769 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3770 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
3771 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
3772 45bc4635 Iustin Pop
  """Performs a number of tests on a restricted command.
3773 1a2eb2dc Michael Hanselmann

3774 1a2eb2dc Michael Hanselmann
  @type path: string
3775 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
3776 1a2eb2dc Michael Hanselmann
  @type cmd: string
3777 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3778 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
3779 1a2eb2dc Michael Hanselmann

3780 1a2eb2dc Michael Hanselmann
  """
3781 1a2eb2dc Michael Hanselmann
  # Verify the directory first
3782 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
3783 1a2eb2dc Michael Hanselmann
  if status:
3784 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
3785 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
3786 1a2eb2dc Michael Hanselmann
3787 1a2eb2dc Michael Hanselmann
  if not status:
3788 1a2eb2dc Michael Hanselmann
    return (False, msg)
3789 1a2eb2dc Michael Hanselmann
3790 1a2eb2dc Michael Hanselmann
  # Check actual executable
3791 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
3792 1a2eb2dc Michael Hanselmann
3793 1a2eb2dc Michael Hanselmann
3794 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
3795 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3796 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3797 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3798 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
3799 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
3800 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
3801 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3802 45bc4635 Iustin Pop
  """Executes a restricted command after performing strict tests.
3803 1a2eb2dc Michael Hanselmann

3804 1a2eb2dc Michael Hanselmann
  @type cmd: string
3805 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3806 1a2eb2dc Michael Hanselmann
  @rtype: string
3807 1a2eb2dc Michael Hanselmann
  @return: Command output
3808 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
3809 1a2eb2dc Michael Hanselmann

3810 1a2eb2dc Michael Hanselmann
  """
3811 45bc4635 Iustin Pop
  logging.info("Preparing to run restricted command '%s'", cmd)
3812 1a2eb2dc Michael Hanselmann
3813 1a2eb2dc Michael Hanselmann
  if not _enabled:
3814 45bc4635 Iustin Pop
    _Fail("Restricted commands disabled at configure time")
3815 1a2eb2dc Michael Hanselmann
3816 1a2eb2dc Michael Hanselmann
  lock = None
3817 1a2eb2dc Michael Hanselmann
  try:
3818 1a2eb2dc Michael Hanselmann
    cmdresult = None
3819 1a2eb2dc Michael Hanselmann
    try:
3820 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
3821 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3822 1a2eb2dc Michael Hanselmann
3823 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
3824 1a2eb2dc Michael Hanselmann
3825 1a2eb2dc Michael Hanselmann
      if status:
3826 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3827 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
3828 1a2eb2dc Michael Hanselmann
      else:
3829 1a2eb2dc Michael Hanselmann
        logging.error(value)
3830 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
3831 1a2eb2dc Michael Hanselmann
      # Keep original error in log
3832 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
3833 1a2eb2dc Michael Hanselmann
3834 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
3835 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
3836 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
3837 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
3838 1a2eb2dc Michael Hanselmann
3839 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
3840 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
3841 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
3842 45bc4635 Iustin Pop
      _Fail("Restricted command '%s' failed: %s; output: %s",
3843 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
3844 1a2eb2dc Michael Hanselmann
    else:
3845 1a2eb2dc Michael Hanselmann
      return cmdresult.output
3846 1a2eb2dc Michael Hanselmann
  finally:
3847 1a2eb2dc Michael Hanselmann
    if lock is not None:
3848 1a2eb2dc Michael Hanselmann
      # Release lock at last
3849 1a2eb2dc Michael Hanselmann
      lock.Close()
3850 1a2eb2dc Michael Hanselmann
      lock = None
3851 1a2eb2dc Michael Hanselmann
3852 1a2eb2dc Michael Hanselmann
3853 99e222b1 Michael Hanselmann
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3854 99e222b1 Michael Hanselmann
  """Creates or removes the watcher pause file.
3855 99e222b1 Michael Hanselmann

3856 99e222b1 Michael Hanselmann
  @type until: None or number
3857 99e222b1 Michael Hanselmann
  @param until: Unix timestamp saying until when the watcher shouldn't run
3858 99e222b1 Michael Hanselmann

3859 99e222b1 Michael Hanselmann
  """
3860 99e222b1 Michael Hanselmann
  if until is None:
3861 99e222b1 Michael Hanselmann
    logging.info("Received request to no longer pause watcher")
3862 99e222b1 Michael Hanselmann
    utils.RemoveFile(_filename)
3863 99e222b1 Michael Hanselmann
  else:
3864 99e222b1 Michael Hanselmann
    logging.info("Received request to pause watcher until %s", until)
3865 99e222b1 Michael Hanselmann
3866 99e222b1 Michael Hanselmann
    if not ht.TNumber(until):
3867 99e222b1 Michael Hanselmann
      _Fail("Duration must be numeric")
3868 99e222b1 Michael Hanselmann
3869 99e222b1 Michael Hanselmann
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
3870 99e222b1 Michael Hanselmann
3871 99e222b1 Michael Hanselmann
3872 a8083063 Iustin Pop
class HooksRunner(object):
3873 a8083063 Iustin Pop
  """Hook runner.
3874 a8083063 Iustin Pop

3875 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3876 10c2650b Iustin Pop
  on the master side.
3877 a8083063 Iustin Pop

3878 a8083063 Iustin Pop
  """
3879 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3880 a8083063 Iustin Pop
    """Constructor for hooks runner.
3881 a8083063 Iustin Pop

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

3886 a8083063 Iustin Pop
    """
3887 a8083063 Iustin Pop
    if hooks_base_dir is None:
3888 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3889 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3890 fe267188 Iustin Pop
    # constant
3891 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3892 a8083063 Iustin Pop
3893 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3894 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3895 0fa481f5 Andrea Spadaccini

3896 0fa481f5 Andrea Spadaccini
    """
3897 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3898 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3899 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3900 0fa481f5 Andrea Spadaccini
    assert node == myself
3901 0fa481f5 Andrea Spadaccini
3902 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3903 0fa481f5 Andrea Spadaccini
3904 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3905 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3906 0fa481f5 Andrea Spadaccini
3907 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3908 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3909 a8083063 Iustin Pop

3910 10c2650b Iustin Pop
    @type hpath: str
3911 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3912 10c2650b Iustin Pop
        holds the scripts
3913 10c2650b Iustin Pop
    @type phase: str
3914 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3915 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3916 10c2650b Iustin Pop
    @type env: dict
3917 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3918 10c2650b Iustin Pop
    @rtype: list
3919 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3920 10c2650b Iustin Pop
      - script path
3921 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3922 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3923 10c2650b Iustin Pop
      - output of the script
3924 10c2650b Iustin Pop

3925 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3926 10c2650b Iustin Pop
        parameters
3927 a8083063 Iustin Pop

3928 a8083063 Iustin Pop
    """
3929 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3930 a8083063 Iustin Pop
      suffix = "pre"
3931 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3932 a8083063 Iustin Pop
      suffix = "post"
3933 a8083063 Iustin Pop
    else:
3934 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3935 3fb4f740 Iustin Pop
3936 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3937 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3938 6bb65e3a Guido Trotter
3939 6bb65e3a Guido Trotter
    results = []
3940 a9b7e346 Iustin Pop
3941 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3942 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3943 a9b7e346 Iustin Pop
      # warning at every operation
3944 a9b7e346 Iustin Pop
      return results
3945 a9b7e346 Iustin Pop
3946 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3947 a9b7e346 Iustin Pop
3948 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
3949 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3950 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3951 a8083063 Iustin Pop
        output = ""
3952 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3953 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3954 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3955 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3956 6bb65e3a Guido Trotter
        if runresult.failed:
3957 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3958 a8083063 Iustin Pop
        else:
3959 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3960 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3961 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3962 6bb65e3a Guido Trotter
3963 6bb65e3a Guido Trotter
    return results
3964 3f78eef2 Iustin Pop
3965 3f78eef2 Iustin Pop
3966 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3967 8d528b7c Iustin Pop
  """IAllocator runner.
3968 8d528b7c Iustin Pop

3969 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3970 8d528b7c Iustin Pop
  the master side.
3971 8d528b7c Iustin Pop

3972 8d528b7c Iustin Pop
  """
3973 7e950d31 Iustin Pop
  @staticmethod
3974 7e950d31 Iustin Pop
  def Run(name, idata):
3975 8d528b7c Iustin Pop
    """Run an iallocator script.
3976 8d528b7c Iustin Pop

3977 10c2650b Iustin Pop
    @type name: str
3978 10c2650b Iustin Pop
    @param name: the iallocator script name
3979 10c2650b Iustin Pop
    @type idata: str
3980 10c2650b Iustin Pop
    @param idata: the allocator input data
3981 10c2650b Iustin Pop

3982 10c2650b Iustin Pop
    @rtype: tuple
3983 87f5c298 Iustin Pop
    @return: two element tuple of:
3984 87f5c298 Iustin Pop
       - status
3985 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3986 8d528b7c Iustin Pop

3987 8d528b7c Iustin Pop
    """
3988 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3989 8d528b7c Iustin Pop
                                  os.path.isfile)
3990 8d528b7c Iustin Pop
    if alloc_script is None:
3991 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3992 8d528b7c Iustin Pop
3993 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3994 8d528b7c Iustin Pop
    try:
3995 8d528b7c Iustin Pop
      os.write(fd, idata)
3996 8d528b7c Iustin Pop
      os.close(fd)
3997 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3998 8d528b7c Iustin Pop
      if result.failed:
3999 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4000 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
4001 8d528b7c Iustin Pop
    finally:
4002 8d528b7c Iustin Pop
      os.unlink(fin_name)
4003 8d528b7c Iustin Pop
4004 c26a6bd2 Iustin Pop
    return result.stdout
4005 8d528b7c Iustin Pop
4006 8d528b7c Iustin Pop
4007 3f78eef2 Iustin Pop
class DevCacheManager(object):
4008 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
4009 3f78eef2 Iustin Pop

4010 3f78eef2 Iustin Pop
  """
4011 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
4012 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4013 3f78eef2 Iustin Pop
4014 3f78eef2 Iustin Pop
  @classmethod
4015 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
4016 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
4017 3f78eef2 Iustin Pop

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

4021 10c2650b Iustin Pop
    @type dev_path: str
4022 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
4023 10c2650b Iustin Pop
    @rtype: str
4024 10c2650b Iustin Pop
    @return: the converted path name
4025 3f78eef2 Iustin Pop

4026 3f78eef2 Iustin Pop
    """
4027 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
4028 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4029 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
4030 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4031 3f78eef2 Iustin Pop
    return fpath
4032 3f78eef2 Iustin Pop
4033 3f78eef2 Iustin Pop
  @classmethod
4034 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4035 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
4036 3f78eef2 Iustin Pop

4037 10c2650b Iustin Pop
    @type dev_path: str
4038 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4039 10c2650b Iustin Pop
    @type owner: str
4040 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
4041 10c2650b Iustin Pop
    @type on_primary: bool
4042 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
4043 10c2650b Iustin Pop
        node nor not
4044 10c2650b Iustin Pop
    @type iv_name: str
4045 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
4046 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
4047 10c2650b Iustin Pop

4048 10c2650b Iustin Pop
    @rtype: None
4049 10c2650b Iustin Pop

4050 3f78eef2 Iustin Pop
    """
4051 cf5a8306 Iustin Pop
    if dev_path is None:
4052 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4053 cf5a8306 Iustin Pop
      return
4054 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4055 3f78eef2 Iustin Pop
    if on_primary:
4056 3f78eef2 Iustin Pop
      state = "primary"
4057 3f78eef2 Iustin Pop
    else:
4058 3f78eef2 Iustin Pop
      state = "secondary"
4059 3f78eef2 Iustin Pop
    if iv_name is None:
4060 3f78eef2 Iustin Pop
      iv_name = "not_visible"
4061 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4062 3f78eef2 Iustin Pop
    try:
4063 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
4064 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4065 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4066 3f78eef2 Iustin Pop
4067 3f78eef2 Iustin Pop
  @classmethod
4068 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
4069 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
4070 3f78eef2 Iustin Pop

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

4074 10c2650b Iustin Pop
    @type dev_path: str
4075 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4076 10c2650b Iustin Pop

4077 10c2650b Iustin Pop
    @rtype: None
4078 10c2650b Iustin Pop

4079 3f78eef2 Iustin Pop
    """
4080 cf5a8306 Iustin Pop
    if dev_path is None:
4081 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4082 cf5a8306 Iustin Pop
      return
4083 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4084 3f78eef2 Iustin Pop
    try:
4085 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
4086 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4087 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)