Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 6ece11be

History | View | Annotate | Download (115.2 kB)

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

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

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

92 2cc6781a Iustin Pop
  Its argument is the error message.
93 2cc6781a Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

198 360b0dc2 Iustin Pop
  """
199 b397a7d2 Iustin Pop
  allowed_files = set([
200 b397a7d2 Iustin Pop
    constants.CLUSTER_CONF_FILE,
201 b397a7d2 Iustin Pop
    constants.ETC_HOSTS,
202 b397a7d2 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
203 b397a7d2 Iustin Pop
    constants.VNC_PASSWORD_FILE,
204 b397a7d2 Iustin Pop
    constants.RAPI_CERT_FILE,
205 bfe86c76 Andrea Spadaccini
    constants.SPICE_CERT_FILE,
206 bfe86c76 Andrea Spadaccini
    constants.SPICE_CACERT_FILE,
207 b397a7d2 Iustin Pop
    constants.RAPI_USERS_FILE,
208 6b7d5878 Michael Hanselmann
    constants.CONFD_HMAC_KEY,
209 ff89a747 Michael Hanselmann
    constants.CLUSTER_DOMAIN_SECRET_FILE,
210 b397a7d2 Iustin Pop
    ])
211 b397a7d2 Iustin Pop
212 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
213 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
214 69ab2e12 Guido Trotter
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
215 b397a7d2 Iustin Pop
216 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
217 360b0dc2 Iustin Pop
218 360b0dc2 Iustin Pop
219 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
220 360b0dc2 Iustin Pop
221 360b0dc2 Iustin Pop
222 1bc59f76 Michael Hanselmann
def JobQueuePurge():
223 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
224 10c2650b Iustin Pop

225 c8457ce7 Iustin Pop
  @rtype: tuple
226 c8457ce7 Iustin Pop
  @return: True, None
227 24fc781f Michael Hanselmann

228 24fc781f Michael Hanselmann
  """
229 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
230 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
231 24fc781f Michael Hanselmann
232 24fc781f Michael Hanselmann
233 bd1e4562 Iustin Pop
def GetMasterInfo():
234 bd1e4562 Iustin Pop
  """Returns master information.
235 bd1e4562 Iustin Pop

236 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
237 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
238 bd1e4562 Iustin Pop

239 bd1e4562 Iustin Pop
  @rtype: tuple
240 909b3a0e Andrea Spadaccini
  @return: master_netdev, master_ip, master_name, primary_ip_family,
241 909b3a0e Andrea Spadaccini
    master_netmask
242 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
243 b1b6ea87 Iustin Pop

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

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

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

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

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

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

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

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

358 fb460cf7 Andrea Spadaccini
  """
359 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_START,
360 702eff21 Andrea Spadaccini
                        use_external_mip_script)
361 fb460cf7 Andrea Spadaccini
362 fb460cf7 Andrea Spadaccini
363 fb460cf7 Andrea Spadaccini
def StartMasterDaemons(no_voting):
364 a8083063 Iustin Pop
  """Activate local node as master node.
365 a8083063 Iustin Pop

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

368 3583908a Guido Trotter
  @type no_voting: boolean
369 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
370 fb460cf7 Andrea Spadaccini
      but still non-interactively
371 10c2650b Iustin Pop
  @rtype: None
372 a8083063 Iustin Pop

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

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

403 a8083063 Iustin Pop
  """
404 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_STOP,
405 702eff21 Andrea Spadaccini
                        use_external_mip_script)
406 b1b6ea87 Iustin Pop
407 fb460cf7 Andrea Spadaccini
408 fb460cf7 Andrea Spadaccini
def StopMasterDaemons():
409 fb460cf7 Andrea Spadaccini
  """Stop the master daemons on this node.
410 fb460cf7 Andrea Spadaccini

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

413 fb460cf7 Andrea Spadaccini
  @rtype: None
414 fb460cf7 Andrea Spadaccini

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

429 41e079ce Andrea Spadaccini
  @param old_netmask: the old value of the netmask
430 41e079ce Andrea Spadaccini
  @param netmask: the new value of the netmask
431 41e079ce Andrea Spadaccini
  @param master_ip: the master IP
432 41e079ce Andrea Spadaccini
  @param master_netdev: the master network device
433 41e079ce Andrea Spadaccini

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

460 19ddc57a René Nussbaumer
  @param mode: The mode to operate. Either add or remove entry
461 19ddc57a René Nussbaumer
  @param host: The host to operate on
462 19ddc57a René Nussbaumer
  @param ip: The ip associated with the entry
463 19ddc57a René Nussbaumer

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

482 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
483 10c2650b Iustin Pop
  from the cluster.
484 10c2650b Iustin Pop

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

489 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
490 b989b9d9 Ken Wehr

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

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

548 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
549 78519c10 Michael Hanselmann

550 78519c10 Michael Hanselmann
    - vg_size is the size of the configured volume group in MiB
551 78519c10 Michael Hanselmann
    - vg_free is the free size of the volume group in MiB
552 78519c10 Michael Hanselmann
    - memory_dom0 is the memory allocated for domain0 in MiB
553 78519c10 Michael Hanselmann
    - memory_free is the currently available (free) ram in MiB
554 78519c10 Michael Hanselmann
    - memory_total is the total number of ram in MiB
555 78519c10 Michael Hanselmann
    - hv_version: the hypervisor version, if available
556 78519c10 Michael Hanselmann

557 78519c10 Michael Hanselmann
  """
558 78519c10 Michael Hanselmann
  return hypervisor.GetHypervisor(name).GetNodeInfo()
559 78519c10 Michael Hanselmann
560 78519c10 Michael Hanselmann
561 78519c10 Michael Hanselmann
def _GetNamedNodeInfo(names, fn):
562 78519c10 Michael Hanselmann
  """Calls C{fn} for all names in C{names} and returns a dictionary.
563 78519c10 Michael Hanselmann

564 78519c10 Michael Hanselmann
  @rtype: None or dict
565 78519c10 Michael Hanselmann

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

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

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

595 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
596 e69d05fd Iustin Pop
  local node.
597 e69d05fd Iustin Pop

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

601 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
602 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
603 e69d05fd Iustin Pop
  report).
604 a8083063 Iustin Pop

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

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

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

801 2be7273c Apollon Oikonomopoulos
  @type devices: list
802 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
803 2be7273c Apollon Oikonomopoulos
  @rtype: dict
804 2be7273c Apollon Oikonomopoulos
  @return:
805 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
806 2be7273c Apollon Oikonomopoulos
    size in MiB.
807 2be7273c Apollon Oikonomopoulos

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

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

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

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

849 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
850 10c2650b Iustin Pop
      details.
851 a8083063 Iustin Pop

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

885 10c2650b Iustin Pop
  @rtype: dict
886 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
887 10c2650b Iustin Pop
      size of the volume
888 a8083063 Iustin Pop

889 a8083063 Iustin Pop
  """
890 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
891 a8083063 Iustin Pop
892 a8083063 Iustin Pop
893 dcb93971 Michael Hanselmann
def NodeVolumes():
894 dcb93971 Michael Hanselmann
  """List all volumes on this node.
895 dcb93971 Michael Hanselmann

896 10c2650b Iustin Pop
  @rtype: list
897 10c2650b Iustin Pop
  @return:
898 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
899 10c2650b Iustin Pop
      - name: the logical volume name,
900 10c2650b Iustin Pop
      - size: the size of the logical volume
901 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
902 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
903 10c2650b Iustin Pop

904 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
905 10c2650b Iustin Pop
    error.
906 10c2650b Iustin Pop

907 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
908 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
909 10c2650b Iustin Pop
    multiple times.
910 10c2650b Iustin Pop

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

942 b1206984 Iustin Pop
  @rtype: boolean
943 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
944 a8083063 Iustin Pop

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

958 e69d05fd Iustin Pop
  @type hypervisor_list: list
959 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
960 e69d05fd Iustin Pop

961 e69d05fd Iustin Pop
  @rtype: list
962 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
963 10c2650b Iustin Pop
    - instance1.example.com
964 10c2650b Iustin Pop
    - instance2.example.com
965 a8083063 Iustin Pop

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

982 e69d05fd Iustin Pop
  @type instance: string
983 e69d05fd Iustin Pop
  @param instance: the instance name
984 e69d05fd Iustin Pop
  @type hname: string
985 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
986 a8083063 Iustin Pop

987 e69d05fd Iustin Pop
  @rtype: dict
988 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
989 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
990 e69d05fd Iustin Pop
      - state: xen state of instance (string)
991 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
992 a8083063 Iustin Pop

993 098c0958 Michael Hanselmann
  """
994 a8083063 Iustin Pop
  output = {}
995 a8083063 Iustin Pop
996 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
997 a8083063 Iustin Pop
  if iinfo is not None:
998 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
999 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1000 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1001 a8083063 Iustin Pop
1002 c26a6bd2 Iustin Pop
  return output
1003 a8083063 Iustin Pop
1004 a8083063 Iustin Pop
1005 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1006 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
1007 56e7640c Iustin Pop

1008 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1009 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1010 56e7640c Iustin Pop

1011 56e7640c Iustin Pop
  @rtype: tuple
1012 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1013 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1014 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1015 56e7640c Iustin Pop

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

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

1036 e69d05fd Iustin Pop
  @type hypervisor_list: list
1037 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1038 e69d05fd Iustin Pop

1039 955db481 Guido Trotter
  @rtype: dict
1040 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1041 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1042 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1043 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1044 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1045 a8083063 Iustin Pop

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

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

1078 81a3406c Iustin Pop
  @type kind: string
1079 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1080 81a3406c Iustin Pop
  @type os_name: string
1081 81a3406c Iustin Pop
  @param os_name: the os name
1082 81a3406c Iustin Pop
  @type instance: string
1083 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1084 6aa7a354 Iustin Pop
  @type component: string or None
1085 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1086 6aa7a354 Iustin Pop
      transferred
1087 81a3406c Iustin Pop

1088 81a3406c Iustin Pop
  """
1089 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1090 6aa7a354 Iustin Pop
  if component:
1091 6aa7a354 Iustin Pop
    assert "/" not in component
1092 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1093 6aa7a354 Iustin Pop
  else:
1094 6aa7a354 Iustin Pop
    c_msg = ""
1095 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1096 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1097 81a3406c Iustin Pop
  return utils.PathJoin(constants.LOG_OS_DIR, base)
1098 81a3406c Iustin Pop
1099 81a3406c Iustin Pop
1100 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1101 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1102 a8083063 Iustin Pop

1103 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1104 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1105 e557bae9 Guido Trotter
  @type reinstall: boolean
1106 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1107 4a0e011f Iustin Pop
  @type debug: integer
1108 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1109 c26a6bd2 Iustin Pop
  @rtype: None
1110 a8083063 Iustin Pop

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

1135 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1136 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1137 d15a9ad3 Guido Trotter
  @type old_name: string
1138 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1139 4a0e011f Iustin Pop
  @type debug: integer
1140 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1141 10c2650b Iustin Pop
  @rtype: boolean
1142 10c2650b Iustin Pop
  @return: the success of the operation
1143 decd5f45 Iustin Pop

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

1173 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1174 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1175 9332fd8a Iustin Pop

1176 9332fd8a Iustin Pop

1177 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1178 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1179 5282084b Iustin Pop
  @param idx: the disk index
1180 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1181 9332fd8a Iustin Pop

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

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

1214 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1215 a8083063 Iustin Pop
  devices must be already assembled.
1216 a8083063 Iustin Pop

1217 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1218 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1219 069cfbf1 Iustin Pop
  @rtype: list
1220 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1221 10c2650b Iustin Pop

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

1244 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1245 e69d05fd Iustin Pop
  @param instance: the instance object
1246 323f9095 Stephen Shirley
  @type startup_paused: bool
1247 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1248 c26a6bd2 Iustin Pop
  @rtype: None
1249 a8083063 Iustin Pop

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

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

1273 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1274 e69d05fd Iustin Pop
  @param instance: the instance object
1275 6263189c Guido Trotter
  @type timeout: integer
1276 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1277 c26a6bd2 Iustin Pop
  @rtype: None
1278 a8083063 Iustin Pop

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

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

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

1382 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1383 ebe466d8 Guido Trotter
  @param instance: the instance object
1384 ebe466d8 Guido Trotter
  @type memory: int
1385 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1386 ebe466d8 Guido Trotter
  @rtype: None
1387 ebe466d8 Guido Trotter

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

1403 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1404 6906a9d8 Guido Trotter
  @param instance: the instance definition
1405 6906a9d8 Guido Trotter

1406 6906a9d8 Guido Trotter
  """
1407 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1408 cd42d0ad Guido Trotter
  try:
1409 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1410 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1411 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1412 c26a6bd2 Iustin Pop
  return info
1413 6906a9d8 Guido Trotter
1414 6906a9d8 Guido Trotter
1415 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1416 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1417 6906a9d8 Guido Trotter

1418 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1419 6906a9d8 Guido Trotter
  @param instance: the instance definition
1420 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1421 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1422 6906a9d8 Guido Trotter
  @type target: string
1423 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1424 6906a9d8 Guido Trotter

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

1447 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1448 6906a9d8 Guido Trotter
  @param instance: the instance definition
1449 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1450 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1451 6906a9d8 Guido Trotter
  @type success: boolean
1452 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1453 6906a9d8 Guido Trotter

1454 6906a9d8 Guido Trotter
  """
1455 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1456 cd42d0ad Guido Trotter
  try:
1457 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1458 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1459 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1460 6906a9d8 Guido Trotter
1461 6906a9d8 Guido Trotter
1462 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1463 2a10865c Iustin Pop
  """Migrates an instance to another node.
1464 2a10865c Iustin Pop

1465 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1466 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1467 9f0e6b37 Iustin Pop
  @type target: string
1468 9f0e6b37 Iustin Pop
  @param target: the target node name
1469 9f0e6b37 Iustin Pop
  @type live: boolean
1470 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1471 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1472 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1473 9f0e6b37 Iustin Pop

1474 2a10865c Iustin Pop
  """
1475 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1476 2a10865c Iustin Pop
1477 2a10865c Iustin Pop
  try:
1478 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1479 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1480 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1481 2a10865c Iustin Pop
1482 2a10865c Iustin Pop
1483 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1484 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1485 6a1434d7 Andrea Spadaccini

1486 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1487 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1488 6a1434d7 Andrea Spadaccini
  @type success: bool
1489 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1490 6a1434d7 Andrea Spadaccini
  @type live: bool
1491 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1492 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1493 6a1434d7 Andrea Spadaccini

1494 6a1434d7 Andrea Spadaccini
  """
1495 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1496 6a1434d7 Andrea Spadaccini
1497 6a1434d7 Andrea Spadaccini
  try:
1498 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1499 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1500 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1501 6a1434d7 Andrea Spadaccini
          exc=True)
1502 6a1434d7 Andrea Spadaccini
1503 6a1434d7 Andrea Spadaccini
1504 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1505 6a1434d7 Andrea Spadaccini
  """Get the migration status
1506 6a1434d7 Andrea Spadaccini

1507 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1508 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1509 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1510 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1511 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1512 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1513 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1514 6a1434d7 Andrea Spadaccini

1515 6a1434d7 Andrea Spadaccini
  """
1516 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1517 6a1434d7 Andrea Spadaccini
  try:
1518 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1519 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1520 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1521 6a1434d7 Andrea Spadaccini
1522 5ed75b63 Dimitris Aragiorgis
def HotAddDisk(instance, disk, dev_path, seq):
1523 5ed75b63 Dimitris Aragiorgis
  """Hot add a nic
1524 5ed75b63 Dimitris Aragiorgis

1525 5ed75b63 Dimitris Aragiorgis
  """
1526 5ed75b63 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1527 5ed75b63 Dimitris Aragiorgis
  return hyper.HotAddDisk(instance, disk, dev_path, seq)
1528 5ed75b63 Dimitris Aragiorgis
1529 5ed75b63 Dimitris Aragiorgis
def HotDelDisk(instance, disk, seq):
1530 5ed75b63 Dimitris Aragiorgis
  """Hot add a nic
1531 5ed75b63 Dimitris Aragiorgis

1532 5ed75b63 Dimitris Aragiorgis
  """
1533 5ed75b63 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1534 5ed75b63 Dimitris Aragiorgis
  return hyper.HotDelDisk(instance, disk, seq)
1535 5ed75b63 Dimitris Aragiorgis
1536 5ed75b63 Dimitris Aragiorgis
def HotAddNic(instance, nic, seq):
1537 5ed75b63 Dimitris Aragiorgis
  """Hot add a nic
1538 5ed75b63 Dimitris Aragiorgis

1539 5ed75b63 Dimitris Aragiorgis
  """
1540 5ed75b63 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1541 5ed75b63 Dimitris Aragiorgis
  return hyper.HotAddNic(instance, nic, seq)
1542 5ed75b63 Dimitris Aragiorgis
1543 5ed75b63 Dimitris Aragiorgis
def HotDelNic(instance, nic, seq):
1544 5ed75b63 Dimitris Aragiorgis
  """Hot add a nic
1545 5ed75b63 Dimitris Aragiorgis

1546 5ed75b63 Dimitris Aragiorgis
  """
1547 5ed75b63 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1548 5ed75b63 Dimitris Aragiorgis
  return hyper.HotDelNic(instance, nic, seq)
1549 5ed75b63 Dimitris Aragiorgis
1550 6a1434d7 Andrea Spadaccini
1551 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1552 a8083063 Iustin Pop
  """Creates a block device for an instance.
1553 a8083063 Iustin Pop

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

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

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

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

1621 69dd363f René Nussbaumer
  """
1622 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1623 da63bb4e René Nussbaumer
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1624 da63bb4e René Nussbaumer
         "count=%d" % size]
1625 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1626 69dd363f René Nussbaumer
1627 69dd363f René Nussbaumer
  if result.failed:
1628 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1629 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1630 69dd363f René Nussbaumer
1631 69dd363f René Nussbaumer
1632 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1633 69dd363f René Nussbaumer
  """Wipes a block device.
1634 69dd363f René Nussbaumer

1635 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1636 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1637 da63bb4e René Nussbaumer
  @type offset: int
1638 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1639 da63bb4e René Nussbaumer
  @type size: int
1640 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1641 69dd363f René Nussbaumer

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

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

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

1698 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1699 10c2650b Iustin Pop

1700 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1701 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1702 10c2650b Iustin Pop
  @rtype: boolean
1703 10c2650b Iustin Pop
  @return: the success of the operation
1704 a8083063 Iustin Pop

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

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

1738 10c2650b Iustin Pop
  @note: this function is called recursively.
1739 a8083063 Iustin Pop

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

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

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

1789 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1790 a8083063 Iustin Pop

1791 b1206984 Iustin Pop
  @rtype: str or boolean
1792 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1793 b1206984 Iustin Pop
      C{True} for secondary nodes
1794 a8083063 Iustin Pop

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

1814 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1815 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1816 c41eea6e Iustin Pop
  shutdown.
1817 a8083063 Iustin Pop

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

1822 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1823 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1824 10c2650b Iustin Pop
      shutdown
1825 c26a6bd2 Iustin Pop
  @rtype: None
1826 10c2650b Iustin Pop

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

1852 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1853 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1854 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1855 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1856 c26a6bd2 Iustin Pop
  @rtype: None
1857 10c2650b Iustin Pop

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

1871 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1872 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1873 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1874 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1875 c26a6bd2 Iustin Pop
  @rtype: None
1876 10c2650b Iustin Pop

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

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

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

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

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

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

1955 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1956 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1957 a8083063 Iustin Pop

1958 10c2650b Iustin Pop
  @return: None if the device can't be found,
1959 10c2650b Iustin Pop
      otherwise the device instance
1960 a8083063 Iustin Pop

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

1973 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1974 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1975 f2e07bb4 Michael Hanselmann

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

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

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

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

2012 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2013 968a7623 Iustin Pop

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

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

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

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

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

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

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

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

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

2134 b2f29800 René Nussbaumer
  """
2135 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2136 b2f29800 René Nussbaumer
2137 b2f29800 René Nussbaumer
  if result.failed:
2138 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2139 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2140 b2f29800 René Nussbaumer
2141 b2f29800 René Nussbaumer
  return result.stdout
2142 b2f29800 René Nussbaumer
2143 b2f29800 René Nussbaumer
2144 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
2145 89b14f05 Iustin Pop
  """Update all ssconf files.
2146 89b14f05 Iustin Pop

2147 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
2148 89b14f05 Iustin Pop

2149 89b14f05 Iustin Pop
  """
2150 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
2151 6ddc95ec Michael Hanselmann
2152 6ddc95ec Michael Hanselmann
2153 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2154 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2155 a8083063 Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2479 9bcef16f Constantinos Venetsanopoulos
  @type top_dirs: list
2480 9bcef16f Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
2481 9bcef16f Constantinos Venetsanopoulos
      search (if not given defaults to
2482 9bcef16f Constantinos Venetsanopoulos
      L{constants.ES_SEARCH_PATH})
2483 9bcef16f Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
2484 9bcef16f Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
2485 9bcef16f Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
2486 9bcef16f Constantinos Venetsanopoulos
      search paths, where:
2487 9bcef16f Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
2488 9bcef16f Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
2489 9bcef16f Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
2490 9bcef16f Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
2491 9bcef16f Constantinos Venetsanopoulos
            otherwise empty
2492 9bcef16f Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
2493 9bcef16f Constantinos Venetsanopoulos

2494 9bcef16f Constantinos Venetsanopoulos
  """
2495 9bcef16f Constantinos Venetsanopoulos
  if top_dirs is None:
2496 9bcef16f Constantinos Venetsanopoulos
    top_dirs = constants.ES_SEARCH_PATH
2497 9bcef16f Constantinos Venetsanopoulos
2498 9bcef16f Constantinos Venetsanopoulos
  result = []
2499 9bcef16f Constantinos Venetsanopoulos
  for dir_name in top_dirs:
2500 9bcef16f Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
2501 9bcef16f Constantinos Venetsanopoulos
      try:
2502 9bcef16f Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
2503 9bcef16f Constantinos Venetsanopoulos
      except EnvironmentError, err:
2504 9bcef16f Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
2505 9bcef16f Constantinos Venetsanopoulos
                          dir_name, err)
2506 9bcef16f Constantinos Venetsanopoulos
        break
2507 9bcef16f Constantinos Venetsanopoulos
      for name in f_names:
2508 9bcef16f Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
2509 9bcef16f Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2510 9bcef16f Constantinos Venetsanopoulos
        if status:
2511 9bcef16f Constantinos Venetsanopoulos
          diagnose = ""
2512 9bcef16f Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
2513 9bcef16f Constantinos Venetsanopoulos
        else:
2514 9bcef16f Constantinos Venetsanopoulos
          diagnose = es_inst
2515 9bcef16f Constantinos Venetsanopoulos
          parameters = []
2516 9bcef16f Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
2517 9bcef16f Constantinos Venetsanopoulos
2518 9bcef16f Constantinos Venetsanopoulos
  return result
2519 9bcef16f Constantinos Venetsanopoulos
2520 9bcef16f Constantinos Venetsanopoulos
2521 a59faf4b Iustin Pop
def BlockdevGrow(disk, amount, dryrun):
2522 594609c0 Iustin Pop
  """Grow a stack of block devices.
2523 594609c0 Iustin Pop

2524 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2525 10c2650b Iustin Pop
  first ones to resize.
2526 594609c0 Iustin Pop

2527 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2528 10c2650b Iustin Pop
  @param disk: the disk to be grown
2529 a59faf4b Iustin Pop
  @type amount: integer
2530 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2531 a59faf4b Iustin Pop
  @type dryrun: boolean
2532 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2533 a59faf4b Iustin Pop
      only, without actually increasing the size
2534 10c2650b Iustin Pop
  @rtype: (status, result)
2535 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2536 a59faf4b Iustin Pop
      the errors message if status is False
2537 594609c0 Iustin Pop

2538 594609c0 Iustin Pop
  """
2539 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2540 594609c0 Iustin Pop
  if r_dev is None:
2541 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2542 594609c0 Iustin Pop
2543 594609c0 Iustin Pop
  try:
2544 a59faf4b Iustin Pop
    r_dev.Grow(amount, dryrun)
2545 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2546 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2547 594609c0 Iustin Pop
2548 594609c0 Iustin Pop
2549 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2550 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2551 a8083063 Iustin Pop

2552 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2553 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2554 a8083063 Iustin Pop

2555 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2556 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2557 e9e9263d Guido Trotter
  @rtype: string
2558 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2559 a8083063 Iustin Pop

2560 098c0958 Michael Hanselmann
  """
2561 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2562 433c63aa Iustin Pop
    if not disk.children:
2563 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2564 433c63aa Iustin Pop
            disk.unique_id)
2565 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2566 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2567 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2568 a8083063 Iustin Pop
    if r_dev is not None:
2569 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2570 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2571 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2572 a8083063 Iustin Pop
    else:
2573 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2574 a8083063 Iustin Pop
  else:
2575 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2576 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2577 a8083063 Iustin Pop
2578 a8083063 Iustin Pop
2579 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2580 a8083063 Iustin Pop
  """Write out the export configuration information.
2581 a8083063 Iustin Pop

2582 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2583 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2584 10c2650b Iustin Pop
      saving configuration
2585 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2586 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2587 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2588 a8083063 Iustin Pop

2589 c26a6bd2 Iustin Pop
  @rtype: None
2590 a8083063 Iustin Pop

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

2670 10c2650b Iustin Pop
  @type dest: str
2671 10c2650b Iustin Pop
  @param dest: directory containing the export
2672 a8083063 Iustin Pop

2673 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2674 10c2650b Iustin Pop
  @return: a serializable config file containing the
2675 10c2650b Iustin Pop
      export info
2676 a8083063 Iustin Pop

2677 a8083063 Iustin Pop
  """
2678 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2679 a8083063 Iustin Pop
2680 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2681 a8083063 Iustin Pop
  config.read(cff)
2682 a8083063 Iustin Pop
2683 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2684 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2685 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2686 a8083063 Iustin Pop
2687 c26a6bd2 Iustin Pop
  return config.Dumps()
2688 a8083063 Iustin Pop
2689 a8083063 Iustin Pop
2690 a8083063 Iustin Pop
def ListExports():
2691 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2692 098c0958 Michael Hanselmann

2693 10c2650b Iustin Pop
  @rtype: list
2694 10c2650b Iustin Pop
  @return: list of the exports
2695 10c2650b Iustin Pop

2696 a8083063 Iustin Pop
  """
2697 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
2698 b5b8309d Guido Trotter
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2699 a8083063 Iustin Pop
  else:
2700 afdc3985 Iustin Pop
    _Fail("No exports directory")
2701 a8083063 Iustin Pop
2702 a8083063 Iustin Pop
2703 a8083063 Iustin Pop
def RemoveExport(export):
2704 a8083063 Iustin Pop
  """Remove an existing export from the node.
2705 a8083063 Iustin Pop

2706 10c2650b Iustin Pop
  @type export: str
2707 10c2650b Iustin Pop
  @param export: the name of the export to remove
2708 c26a6bd2 Iustin Pop
  @rtype: None
2709 a8083063 Iustin Pop

2710 098c0958 Michael Hanselmann
  """
2711 c4feafe8 Iustin Pop
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2712 a8083063 Iustin Pop
2713 35fbcd11 Iustin Pop
  try:
2714 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2715 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2716 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2717 a8083063 Iustin Pop
2718 a8083063 Iustin Pop
2719 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2720 f3e513ad Iustin Pop
  """Rename a list of block devices.
2721 f3e513ad Iustin Pop

2722 10c2650b Iustin Pop
  @type devlist: list of tuples
2723 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2724 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2725 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2726 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2727 10c2650b Iustin Pop
      rename it to
2728 10c2650b Iustin Pop
  @rtype: boolean
2729 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2730 f3e513ad Iustin Pop

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

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

2767 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2768 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2769 d61cbe76 Iustin Pop

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

2772 778b75bb Manuel Franceschini
  """
2773 cb7c0198 Iustin Pop
  if not constants.ENABLE_FILE_STORAGE:
2774 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2775 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2776 4b97f902 Apollon Oikonomopoulos
  fs_dir = os.path.normpath(fs_dir)
2777 4b97f902 Apollon Oikonomopoulos
  base_fstore = cfg.GetFileStorageDir()
2778 4b97f902 Apollon Oikonomopoulos
  base_shared = cfg.GetSharedFileStorageDir()
2779 cf00dba0 René Nussbaumer
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2780 cf00dba0 René Nussbaumer
          utils.IsBelowDir(base_shared, fs_dir)):
2781 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2782 4b97f902 Apollon Oikonomopoulos
          " storage directory '%s' or shared storage directory '%s'",
2783 4b97f902 Apollon Oikonomopoulos
          fs_dir, base_fstore, base_shared)
2784 4b97f902 Apollon Oikonomopoulos
  return fs_dir
2785 778b75bb Manuel Franceschini
2786 778b75bb Manuel Franceschini
2787 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2788 778b75bb Manuel Franceschini
  """Create file storage directory.
2789 778b75bb Manuel Franceschini

2790 b1206984 Iustin Pop
  @type file_storage_dir: str
2791 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2792 778b75bb Manuel Franceschini

2793 b1206984 Iustin Pop
  @rtype: tuple
2794 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2795 b1206984 Iustin Pop
      creation was successful or not
2796 778b75bb Manuel Franceschini

2797 778b75bb Manuel Franceschini
  """
2798 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2799 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2800 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2801 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2802 b2b8bcce Iustin Pop
            file_storage_dir)
2803 778b75bb Manuel Franceschini
  else:
2804 b2b8bcce Iustin Pop
    try:
2805 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2806 b2b8bcce Iustin Pop
    except OSError, err:
2807 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2808 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2809 778b75bb Manuel Franceschini
2810 778b75bb Manuel Franceschini
2811 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2812 778b75bb Manuel Franceschini
  """Remove file storage directory.
2813 778b75bb Manuel Franceschini

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

2816 10c2650b Iustin Pop
  @type file_storage_dir: str
2817 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2818 10c2650b Iustin Pop
  @rtype: tuple (success,)
2819 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2820 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2821 778b75bb Manuel Franceschini

2822 778b75bb Manuel Franceschini
  """
2823 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2824 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2825 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2826 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2827 b2b8bcce Iustin Pop
            file_storage_dir)
2828 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2829 b2b8bcce Iustin Pop
    try:
2830 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2831 b2b8bcce Iustin Pop
    except OSError, err:
2832 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2833 b2b8bcce Iustin Pop
            file_storage_dir, err)
2834 b2b8bcce Iustin Pop
2835 778b75bb Manuel Franceschini
2836 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2837 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2838 778b75bb Manuel Franceschini

2839 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2840 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2841 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2842 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2843 10c2650b Iustin Pop
  @rtype: tuple (success,)
2844 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2845 10c2650b Iustin Pop
      whether the operation was successful
2846 778b75bb Manuel Franceschini

2847 778b75bb Manuel Franceschini
  """
2848 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2849 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2850 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2851 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2852 b2b8bcce Iustin Pop
      try:
2853 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2854 b2b8bcce Iustin Pop
      except OSError, err:
2855 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2856 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2857 778b75bb Manuel Franceschini
    else:
2858 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2859 b2b8bcce Iustin Pop
            old_file_storage_dir)
2860 b2b8bcce Iustin Pop
  else:
2861 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2862 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2863 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2864 778b75bb Manuel Franceschini
2865 778b75bb Manuel Franceschini
2866 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2867 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2868 ca52cdeb Michael Hanselmann

2869 10c2650b Iustin Pop
  @type file_name: str
2870 10c2650b Iustin Pop
  @param file_name: the file name we should check
2871 c8457ce7 Iustin Pop
  @rtype: None
2872 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2873 10c2650b Iustin Pop

2874 ca52cdeb Michael Hanselmann
  """
2875 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2876 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2877 dc31eae3 Michael Hanselmann
2878 dc31eae3 Michael Hanselmann
  if not result:
2879 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2880 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2881 dc31eae3 Michael Hanselmann
2882 dc31eae3 Michael Hanselmann
2883 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2884 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2885 dc31eae3 Michael Hanselmann

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

2889 10c2650b Iustin Pop
  @type file_name: str
2890 10c2650b Iustin Pop
  @param file_name: the job file name
2891 10c2650b Iustin Pop
  @type content: str
2892 10c2650b Iustin Pop
  @param content: the new job contents
2893 10c2650b Iustin Pop
  @rtype: boolean
2894 10c2650b Iustin Pop
  @return: the success of the operation
2895 10c2650b Iustin Pop

2896 dc31eae3 Michael Hanselmann
  """
2897 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2898 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2899 ca52cdeb Michael Hanselmann
2900 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2901 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2902 82b22e19 René Nussbaumer
                  gid=getents.masterd_gid)
2903 ca52cdeb Michael Hanselmann
2904 ca52cdeb Michael Hanselmann
2905 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2906 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2907 af5ebcb1 Michael Hanselmann

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

2910 10c2650b Iustin Pop
  @type old: str
2911 10c2650b Iustin Pop
  @param old: the old (actual) file name
2912 10c2650b Iustin Pop
  @type new: str
2913 10c2650b Iustin Pop
  @param new: the desired file name
2914 c8457ce7 Iustin Pop
  @rtype: tuple
2915 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2916 10c2650b Iustin Pop

2917 af5ebcb1 Michael Hanselmann
  """
2918 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2919 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2920 af5ebcb1 Michael Hanselmann
2921 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
2922 8e5a705d René Nussbaumer
2923 8e5a705d René Nussbaumer
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2924 8e5a705d René Nussbaumer
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2925 af5ebcb1 Michael Hanselmann
2926 af5ebcb1 Michael Hanselmann
2927 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2928 d61cbe76 Iustin Pop
  """Closes the given block devices.
2929 d61cbe76 Iustin Pop

2930 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2931 10c2650b Iustin Pop
  DRBD).
2932 10c2650b Iustin Pop

2933 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2934 b2e7666a Iustin Pop
      of this instance will be removed
2935 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2936 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2937 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2938 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2939 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2940 10c2650b Iustin Pop
      which will contain the error details in case we
2941 10c2650b Iustin Pop
      failed
2942 d61cbe76 Iustin Pop

2943 d61cbe76 Iustin Pop
  """
2944 d61cbe76 Iustin Pop
  bdevs = []
2945 d61cbe76 Iustin Pop
  for cf in disks:
2946 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2947 d61cbe76 Iustin Pop
    if rd is None:
2948 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2949 d61cbe76 Iustin Pop
    bdevs.append(rd)
2950 d61cbe76 Iustin Pop
2951 d61cbe76 Iustin Pop
  msg = []
2952 d61cbe76 Iustin Pop
  for rd in bdevs:
2953 d61cbe76 Iustin Pop
    try:
2954 d61cbe76 Iustin Pop
      rd.Close()
2955 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2956 d61cbe76 Iustin Pop
      msg.append(str(err))
2957 d61cbe76 Iustin Pop
  if msg:
2958 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2959 d61cbe76 Iustin Pop
  else:
2960 b2e7666a Iustin Pop
    if instance_name:
2961 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2962 d61cbe76 Iustin Pop
2963 d61cbe76 Iustin Pop
2964 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2965 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2966 6217e295 Iustin Pop

2967 6217e295 Iustin Pop
  @type hvname: string
2968 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2969 6217e295 Iustin Pop
  @type hvparams: dict
2970 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2971 c26a6bd2 Iustin Pop
  @rtype: None
2972 6217e295 Iustin Pop

2973 6217e295 Iustin Pop
  """
2974 6217e295 Iustin Pop
  try:
2975 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2976 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2977 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2978 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2979 6217e295 Iustin Pop
2980 6217e295 Iustin Pop
2981 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
2982 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
2983 acd9ff9e Iustin Pop

2984 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
2985 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
2986 acd9ff9e Iustin Pop
  @type parameters: list
2987 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
2988 acd9ff9e Iustin Pop

2989 acd9ff9e Iustin Pop
  """
2990 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
2991 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
2992 acd9ff9e Iustin Pop
  if delta:
2993 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
2994 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2995 acd9ff9e Iustin Pop
2996 acd9ff9e Iustin Pop
2997 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
2998 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
2999 acd9ff9e Iustin Pop

3000 acd9ff9e Iustin Pop
  @type required: boolean
3001 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3002 acd9ff9e Iustin Pop
      failure or not
3003 acd9ff9e Iustin Pop
  @type osname: string
3004 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3005 acd9ff9e Iustin Pop
  @type checks: list
3006 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3007 acd9ff9e Iustin Pop
  @type osparams: dict
3008 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
3009 acd9ff9e Iustin Pop
  @rtype: boolean
3010 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3011 acd9ff9e Iustin Pop
      found and L{required} was false
3012 acd9ff9e Iustin Pop

3013 acd9ff9e Iustin Pop
  """
3014 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3015 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3016 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3017 acd9ff9e Iustin Pop
3018 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3019 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3020 acd9ff9e Iustin Pop
3021 acd9ff9e Iustin Pop
  if not status:
3022 acd9ff9e Iustin Pop
    if required:
3023 acd9ff9e Iustin Pop
      _Fail(tbv)
3024 acd9ff9e Iustin Pop
    else:
3025 acd9ff9e Iustin Pop
      return False
3026 acd9ff9e Iustin Pop
3027 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3028 72db3fd7 Iustin Pop
    return True
3029 72db3fd7 Iustin Pop
3030 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3031 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3032 acd9ff9e Iustin Pop
3033 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3034 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3035 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3036 acd9ff9e Iustin Pop
  if result.failed:
3037 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3038 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3039 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3040 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3041 acd9ff9e Iustin Pop
3042 acd9ff9e Iustin Pop
  return True
3043 acd9ff9e Iustin Pop
3044 acd9ff9e Iustin Pop
3045 56aa9fd5 Iustin Pop
def DemoteFromMC():
3046 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3047 56aa9fd5 Iustin Pop

3048 56aa9fd5 Iustin Pop
  """
3049 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3050 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3051 56aa9fd5 Iustin Pop
  if master == myself:
3052 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3053 f154a7a3 Michael Hanselmann
3054 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
3055 f154a7a3 Michael Hanselmann
  if not result.failed:
3056 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3057 f154a7a3 Michael Hanselmann
3058 56aa9fd5 Iustin Pop
  try:
3059 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
3060 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
3061 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3062 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3063 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3064 f154a7a3 Michael Hanselmann
3065 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
3066 56aa9fd5 Iustin Pop
3067 56aa9fd5 Iustin Pop
3068 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3069 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3070 f942a838 Michael Hanselmann

3071 f942a838 Michael Hanselmann
  """
3072 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3073 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3074 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3075 f942a838 Michael Hanselmann
3076 f942a838 Michael Hanselmann
3077 f942a838 Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
3078 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3079 f942a838 Michael Hanselmann

3080 f942a838 Michael Hanselmann
  @type validity: int
3081 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3082 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3083 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3084 f942a838 Michael Hanselmann

3085 f942a838 Michael Hanselmann
  """
3086 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3087 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3088 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3089 f942a838 Michael Hanselmann
3090 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3091 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3092 f942a838 Michael Hanselmann
  try:
3093 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3094 f942a838 Michael Hanselmann
    assert len(name) > 5
3095 f942a838 Michael Hanselmann
3096 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3097 f942a838 Michael Hanselmann
3098 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3099 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3100 f942a838 Michael Hanselmann
3101 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3102 f942a838 Michael Hanselmann
    return (name, cert_pem)
3103 f942a838 Michael Hanselmann
  except Exception:
3104 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3105 f942a838 Michael Hanselmann
    raise
3106 f942a838 Michael Hanselmann
3107 f942a838 Michael Hanselmann
3108 f942a838 Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
3109 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3110 f942a838 Michael Hanselmann

3111 f942a838 Michael Hanselmann
  @type name: string
3112 f942a838 Michael Hanselmann
  @param name: Certificate name
3113 f942a838 Michael Hanselmann

3114 f942a838 Michael Hanselmann
  """
3115 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3116 f942a838 Michael Hanselmann
3117 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3118 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3119 f942a838 Michael Hanselmann
3120 f942a838 Michael Hanselmann
  try:
3121 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3122 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3123 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3124 f942a838 Michael Hanselmann
          cert_dir, err)
3125 f942a838 Michael Hanselmann
3126 f942a838 Michael Hanselmann
3127 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3128 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3129 1651d116 Michael Hanselmann

3130 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3131 1651d116 Michael Hanselmann
  @param instance: The instance object
3132 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3133 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3134 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3135 1651d116 Michael Hanselmann

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

3241 1651d116 Michael Hanselmann
  """
3242 1651d116 Michael Hanselmann
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3243 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3244 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3245 1651d116 Michael Hanselmann
3246 1651d116 Michael Hanselmann
3247 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3248 6613661a Iustin Pop
                            ieio, ieioargs):
3249 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3250 1651d116 Michael Hanselmann

3251 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3252 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3253 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3254 1651d116 Michael Hanselmann
  @type host: string
3255 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3256 1651d116 Michael Hanselmann
  @type port: int
3257 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3258 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3259 1651d116 Michael Hanselmann
  @param instance: Instance object
3260 6613661a Iustin Pop
  @type component: string
3261 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3262 6613661a Iustin Pop
      e.g. 'disk/0'
3263 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3264 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3265 1651d116 Michael Hanselmann

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

3378 1651d116 Michael Hanselmann
  @type names: sequence
3379 1651d116 Michael Hanselmann
  @param names: List of names
3380 1651d116 Michael Hanselmann
  @rtype: List of dicts
3381 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3382 1651d116 Michael Hanselmann
           status couldn't be read
3383 1651d116 Michael Hanselmann

3384 1651d116 Michael Hanselmann
  """
3385 1651d116 Michael Hanselmann
  result = []
3386 1651d116 Michael Hanselmann
3387 1651d116 Michael Hanselmann
  for name in names:
3388 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3389 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3390 1651d116 Michael Hanselmann
3391 1651d116 Michael Hanselmann
    try:
3392 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3393 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3394 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3395 1651d116 Michael Hanselmann
        raise
3396 1651d116 Michael Hanselmann
      data = None
3397 1651d116 Michael Hanselmann
3398 1651d116 Michael Hanselmann
    if not data:
3399 1651d116 Michael Hanselmann
      result.append(None)
3400 1651d116 Michael Hanselmann
      continue
3401 1651d116 Michael Hanselmann
3402 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3403 1651d116 Michael Hanselmann
3404 1651d116 Michael Hanselmann
  return result
3405 1651d116 Michael Hanselmann
3406 1651d116 Michael Hanselmann
3407 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3408 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3409 f81c4737 Michael Hanselmann

3410 f81c4737 Michael Hanselmann
  """
3411 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3412 f81c4737 Michael Hanselmann
3413 f81c4737 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3414 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3415 f81c4737 Michael Hanselmann
3416 f81c4737 Michael Hanselmann
  if pid:
3417 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3418 f81c4737 Michael Hanselmann
                 name, pid)
3419 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3420 f81c4737 Michael Hanselmann
3421 f81c4737 Michael Hanselmann
3422 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3423 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3424 1651d116 Michael Hanselmann

3425 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3426 1651d116 Michael Hanselmann
  whole status directory is removed.
3427 1651d116 Michael Hanselmann

3428 1651d116 Michael Hanselmann
  """
3429 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3430 1651d116 Michael Hanselmann
3431 1651d116 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3432 1651d116 Michael Hanselmann
3433 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3434 1651d116 Michael Hanselmann
3435 1651d116 Michael Hanselmann
  if pid:
3436 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3437 1651d116 Michael Hanselmann
                 name, pid)
3438 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3439 1651d116 Michael Hanselmann
3440 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3441 1651d116 Michael Hanselmann
3442 1651d116 Michael Hanselmann
3443 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3444 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3445 6b93ec9d Iustin Pop

3446 6b93ec9d Iustin Pop
  """
3447 6b93ec9d Iustin Pop
  # set the correct physical ID
3448 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3449 6b93ec9d Iustin Pop
  for cf in disks:
3450 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3451 6b93ec9d Iustin Pop
3452 6b93ec9d Iustin Pop
  bdevs = []
3453 6b93ec9d Iustin Pop
3454 6b93ec9d Iustin Pop
  for cf in disks:
3455 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3456 6b93ec9d Iustin Pop
    if rd is None:
3457 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3458 6b93ec9d Iustin Pop
    bdevs.append(rd)
3459 5a533f8a Iustin Pop
  return bdevs
3460 6b93ec9d Iustin Pop
3461 6b93ec9d Iustin Pop
3462 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3463 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3464 6b93ec9d Iustin Pop

3465 6b93ec9d Iustin Pop
  """
3466 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3467 6b93ec9d Iustin Pop
3468 6b93ec9d Iustin Pop
  # disconnect disks
3469 6b93ec9d Iustin Pop
  for rd in bdevs:
3470 6b93ec9d Iustin Pop
    try:
3471 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3472 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3473 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3474 2cc6781a Iustin Pop
            err, exc=True)
3475 6b93ec9d Iustin Pop
3476 6b93ec9d Iustin Pop
3477 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3478 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3479 6b93ec9d Iustin Pop

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

3542 6b93ec9d Iustin Pop
  """
3543 db8667b7 Iustin Pop
  def _helper(rd):
3544 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3545 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3546 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3547 db8667b7 Iustin Pop
    return stats
3548 db8667b7 Iustin Pop
3549 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3550 6b93ec9d Iustin Pop
3551 6b93ec9d Iustin Pop
  min_resync = 100
3552 6b93ec9d Iustin Pop
  alldone = True
3553 6b93ec9d Iustin Pop
  for rd in bdevs:
3554 db8667b7 Iustin Pop
    try:
3555 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3556 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3557 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3558 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3559 db8667b7 Iustin Pop
      # last check
3560 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3561 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3562 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3563 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3564 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3565 afdc3985 Iustin Pop
3566 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3567 6b93ec9d Iustin Pop
3568 6b93ec9d Iustin Pop
3569 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3570 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3571 c46b9782 Luca Bigliardi

3572 c46b9782 Luca Bigliardi
  """
3573 c46b9782 Luca Bigliardi
  try:
3574 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3575 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3576 c46b9782 Luca Bigliardi
    _Fail(str(err))
3577 c46b9782 Luca Bigliardi
3578 c46b9782 Luca Bigliardi
3579 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3580 f5118ade Iustin Pop
  """Hard-powercycle the node.
3581 f5118ade Iustin Pop

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

3585 f5118ade Iustin Pop
  """
3586 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3587 f5118ade Iustin Pop
  try:
3588 f5118ade Iustin Pop
    pid = os.fork()
3589 29921401 Iustin Pop
  except OSError:
3590 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3591 f5118ade Iustin Pop
    pid = 0
3592 f5118ade Iustin Pop
  if pid > 0:
3593 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3594 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3595 1af6ac0f Luca Bigliardi
  try:
3596 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3597 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3598 1af6ac0f Luca Bigliardi
    pass
3599 f5118ade Iustin Pop
  time.sleep(5)
3600 f5118ade Iustin Pop
  hyper.PowercycleNode()
3601 f5118ade Iustin Pop
3602 f5118ade Iustin Pop
3603 a8083063 Iustin Pop
class HooksRunner(object):
3604 a8083063 Iustin Pop
  """Hook runner.
3605 a8083063 Iustin Pop

3606 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3607 10c2650b Iustin Pop
  on the master side.
3608 a8083063 Iustin Pop

3609 a8083063 Iustin Pop
  """
3610 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3611 a8083063 Iustin Pop
    """Constructor for hooks runner.
3612 a8083063 Iustin Pop

3613 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
3614 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
3615 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3616 a8083063 Iustin Pop

3617 a8083063 Iustin Pop
    """
3618 a8083063 Iustin Pop
    if hooks_base_dir is None:
3619 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
3620 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3621 fe267188 Iustin Pop
    # constant
3622 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3623 a8083063 Iustin Pop
3624 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3625 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3626 0fa481f5 Andrea Spadaccini

3627 0fa481f5 Andrea Spadaccini
    """
3628 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3629 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3630 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3631 0fa481f5 Andrea Spadaccini
    assert node == myself
3632 0fa481f5 Andrea Spadaccini
3633 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3634 0fa481f5 Andrea Spadaccini
3635 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3636 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3637 0fa481f5 Andrea Spadaccini
3638 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3639 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3640 a8083063 Iustin Pop

3641 10c2650b Iustin Pop
    @type hpath: str
3642 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3643 10c2650b Iustin Pop
        holds the scripts
3644 10c2650b Iustin Pop
    @type phase: str
3645 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3646 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3647 10c2650b Iustin Pop
    @type env: dict
3648 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3649 10c2650b Iustin Pop
    @rtype: list
3650 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3651 10c2650b Iustin Pop
      - script path
3652 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3653 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3654 10c2650b Iustin Pop
      - output of the script
3655 10c2650b Iustin Pop

3656 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3657 10c2650b Iustin Pop
        parameters
3658 a8083063 Iustin Pop

3659 a8083063 Iustin Pop
    """
3660 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3661 a8083063 Iustin Pop
      suffix = "pre"
3662 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3663 a8083063 Iustin Pop
      suffix = "post"
3664 a8083063 Iustin Pop
    else:
3665 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3666 3fb4f740 Iustin Pop
3667 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3668 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3669 6bb65e3a Guido Trotter
3670 6bb65e3a Guido Trotter
    results = []
3671 a9b7e346 Iustin Pop
3672 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3673 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3674 a9b7e346 Iustin Pop
      # warning at every operation
3675 a9b7e346 Iustin Pop
      return results
3676 a9b7e346 Iustin Pop
3677 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3678 a9b7e346 Iustin Pop
3679 6bb65e3a Guido Trotter
    for (relname, relstatus, runresult)  in runparts_results:
3680 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3681 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3682 a8083063 Iustin Pop
        output = ""
3683 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3684 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3685 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3686 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3687 6bb65e3a Guido Trotter
        if runresult.failed:
3688 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3689 a8083063 Iustin Pop
        else:
3690 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3691 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3692 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3693 6bb65e3a Guido Trotter
3694 6bb65e3a Guido Trotter
    return results
3695 3f78eef2 Iustin Pop
3696 3f78eef2 Iustin Pop
3697 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3698 8d528b7c Iustin Pop
  """IAllocator runner.
3699 8d528b7c Iustin Pop

3700 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3701 8d528b7c Iustin Pop
  the master side.
3702 8d528b7c Iustin Pop

3703 8d528b7c Iustin Pop
  """
3704 7e950d31 Iustin Pop
  @staticmethod
3705 7e950d31 Iustin Pop
  def Run(name, idata):
3706 8d528b7c Iustin Pop
    """Run an iallocator script.
3707 8d528b7c Iustin Pop

3708 10c2650b Iustin Pop
    @type name: str
3709 10c2650b Iustin Pop
    @param name: the iallocator script name
3710 10c2650b Iustin Pop
    @type idata: str
3711 10c2650b Iustin Pop
    @param idata: the allocator input data
3712 10c2650b Iustin Pop

3713 10c2650b Iustin Pop
    @rtype: tuple
3714 87f5c298 Iustin Pop
    @return: two element tuple of:
3715 87f5c298 Iustin Pop
       - status
3716 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3717 8d528b7c Iustin Pop

3718 8d528b7c Iustin Pop
    """
3719 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3720 8d528b7c Iustin Pop
                                  os.path.isfile)
3721 8d528b7c Iustin Pop
    if alloc_script is None:
3722 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3723 8d528b7c Iustin Pop
3724 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3725 8d528b7c Iustin Pop
    try:
3726 8d528b7c Iustin Pop
      os.write(fd, idata)
3727 8d528b7c Iustin Pop
      os.close(fd)
3728 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3729 8d528b7c Iustin Pop
      if result.failed:
3730 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3731 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3732 8d528b7c Iustin Pop
    finally:
3733 8d528b7c Iustin Pop
      os.unlink(fin_name)
3734 8d528b7c Iustin Pop
3735 c26a6bd2 Iustin Pop
    return result.stdout
3736 8d528b7c Iustin Pop
3737 8d528b7c Iustin Pop
3738 3f78eef2 Iustin Pop
class DevCacheManager(object):
3739 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3740 3f78eef2 Iustin Pop

3741 3f78eef2 Iustin Pop
  """
3742 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3743 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3744 3f78eef2 Iustin Pop
3745 3f78eef2 Iustin Pop
  @classmethod
3746 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3747 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3748 3f78eef2 Iustin Pop

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

3752 10c2650b Iustin Pop
    @type dev_path: str
3753 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3754 10c2650b Iustin Pop
    @rtype: str
3755 10c2650b Iustin Pop
    @return: the converted path name
3756 3f78eef2 Iustin Pop

3757 3f78eef2 Iustin Pop
    """
3758 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3759 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3760 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3761 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3762 3f78eef2 Iustin Pop
    return fpath
3763 3f78eef2 Iustin Pop
3764 3f78eef2 Iustin Pop
  @classmethod
3765 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3766 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3767 3f78eef2 Iustin Pop

3768 10c2650b Iustin Pop
    @type dev_path: str
3769 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3770 10c2650b Iustin Pop
    @type owner: str
3771 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3772 10c2650b Iustin Pop
    @type on_primary: bool
3773 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3774 10c2650b Iustin Pop
        node nor not
3775 10c2650b Iustin Pop
    @type iv_name: str
3776 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3777 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3778 10c2650b Iustin Pop

3779 10c2650b Iustin Pop
    @rtype: None
3780 10c2650b Iustin Pop

3781 3f78eef2 Iustin Pop
    """
3782 cf5a8306 Iustin Pop
    if dev_path is None:
3783 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3784 cf5a8306 Iustin Pop
      return
3785 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3786 3f78eef2 Iustin Pop
    if on_primary:
3787 3f78eef2 Iustin Pop
      state = "primary"
3788 3f78eef2 Iustin Pop
    else:
3789 3f78eef2 Iustin Pop
      state = "secondary"
3790 3f78eef2 Iustin Pop
    if iv_name is None:
3791 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3792 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3793 3f78eef2 Iustin Pop
    try:
3794 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3795 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3796 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3797 3f78eef2 Iustin Pop
3798 3f78eef2 Iustin Pop
  @classmethod
3799 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3800 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3801 3f78eef2 Iustin Pop

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

3805 10c2650b Iustin Pop
    @type dev_path: str
3806 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3807 10c2650b Iustin Pop

3808 10c2650b Iustin Pop
    @rtype: None
3809 10c2650b Iustin Pop

3810 3f78eef2 Iustin Pop
    """
3811 cf5a8306 Iustin Pop
    if dev_path is None:
3812 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3813 cf5a8306 Iustin Pop
      return
3814 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3815 3f78eef2 Iustin Pop
    try:
3816 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3817 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3818 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)