Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 9d276e93

History | View | Annotate | Download (136.9 kB)

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

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

29 360b0dc2 Iustin Pop
"""
30 a8083063 Iustin Pop
31 b459a848 Andrea Spadaccini
# pylint: disable=E1103
32 6c881c52 Iustin Pop
33 6c881c52 Iustin Pop
# E1103: %s %r has no %r member (but some types could not be
34 6c881c52 Iustin Pop
# inferred), because the _TryOSFromDisk returns either (True, os_obj)
35 6c881c52 Iustin Pop
# or (False, "string") which confuses pylint
36 6c881c52 Iustin Pop
37 a8083063 Iustin Pop
38 a8083063 Iustin Pop
import os
39 a8083063 Iustin Pop
import os.path
40 a8083063 Iustin Pop
import shutil
41 a8083063 Iustin Pop
import time
42 a8083063 Iustin Pop
import stat
43 a8083063 Iustin Pop
import errno
44 a8083063 Iustin Pop
import re
45 b544cfe0 Iustin Pop
import random
46 18682bca Iustin Pop
import logging
47 3b9e6a30 Iustin Pop
import tempfile
48 12bce260 Michael Hanselmann
import zlib
49 12bce260 Michael Hanselmann
import base64
50 f81c4737 Michael Hanselmann
import signal
51 a8083063 Iustin Pop
52 a8083063 Iustin Pop
from ganeti import errors
53 a8083063 Iustin Pop
from ganeti import utils
54 a8083063 Iustin Pop
from ganeti import ssh
55 a8083063 Iustin Pop
from ganeti import hypervisor
56 a8083063 Iustin Pop
from ganeti import constants
57 cde49218 Helga Velroyen
from ganeti.storage import bdev
58 cde49218 Helga Velroyen
from ganeti.storage import drbd
59 13669ecd Helga Velroyen
from ganeti.storage import filestorage
60 a8083063 Iustin Pop
from ganeti import objects
61 880478f8 Iustin Pop
from ganeti import ssconf
62 1651d116 Michael Hanselmann
from ganeti import serializer
63 a744b676 Manuel Franceschini
from ganeti import netutils
64 82b22e19 René Nussbaumer
from ganeti import runtime
65 3ccd3243 Andrea Spadaccini
from ganeti import compat
66 710f30ec Michael Hanselmann
from ganeti import pathutils
67 cffbbae7 Michael Hanselmann
from ganeti import vcluster
68 99e222b1 Michael Hanselmann
from ganeti import ht
69 cde49218 Helga Velroyen
from ganeti.storage.base import BlockDev
70 cde49218 Helga Velroyen
from ganeti.storage.drbd import DRBD8
71 68d95757 Guido Trotter
from ganeti import hooksmaster
72 a8083063 Iustin Pop
73 a8083063 Iustin Pop
74 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
75 b8028dcf Michael Hanselmann
_ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
76 710f30ec Michael Hanselmann
  pathutils.DATA_DIR,
77 710f30ec Michael Hanselmann
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
78 710f30ec Michael Hanselmann
  pathutils.QUEUE_DIR,
79 710f30ec Michael Hanselmann
  pathutils.CRYPTO_KEYS_DIR,
80 714ea7ca Iustin Pop
  ])
81 f942a838 Michael Hanselmann
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
82 f942a838 Michael Hanselmann
_X509_KEY_FILE = "key"
83 f942a838 Michael Hanselmann
_X509_CERT_FILE = "cert"
84 1651d116 Michael Hanselmann
_IES_STATUS_FILE = "status"
85 1651d116 Michael Hanselmann
_IES_PID_FILE = "pid"
86 1651d116 Michael Hanselmann
_IES_CA_FILE = "ca"
87 13998ef2 Michael Hanselmann
88 0b5303da Iustin Pop
#: Valid LVS output line regex
89 a1f38213 Iustin Pop
_LVSLINE_REGEX = re.compile("^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
90 0b5303da Iustin Pop
91 702eff21 Andrea Spadaccini
# Actions for the master setup script
92 702eff21 Andrea Spadaccini
_MASTER_START = "start"
93 702eff21 Andrea Spadaccini
_MASTER_STOP = "stop"
94 702eff21 Andrea Spadaccini
95 45bc4635 Iustin Pop
#: Maximum file permissions for restricted command directory and executables
96 1a2eb2dc Michael Hanselmann
_RCMD_MAX_MODE = (stat.S_IRWXU |
97 1a2eb2dc Michael Hanselmann
                  stat.S_IRGRP | stat.S_IXGRP |
98 1a2eb2dc Michael Hanselmann
                  stat.S_IROTH | stat.S_IXOTH)
99 1a2eb2dc Michael Hanselmann
100 45bc4635 Iustin Pop
#: Delay before returning an error for restricted commands
101 1a2eb2dc Michael Hanselmann
_RCMD_INVALID_DELAY = 10
102 1a2eb2dc Michael Hanselmann
103 45bc4635 Iustin Pop
#: How long to wait to acquire lock for restricted commands (shorter than
104 1a2eb2dc Michael Hanselmann
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
105 1a2eb2dc Michael Hanselmann
#: command requests arrive
106 1a2eb2dc Michael Hanselmann
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
107 1a2eb2dc Michael Hanselmann
108 13998ef2 Michael Hanselmann
109 2cc6781a Iustin Pop
class RPCFail(Exception):
110 2cc6781a Iustin Pop
  """Class denoting RPC failure.
111 2cc6781a Iustin Pop

112 2cc6781a Iustin Pop
  Its argument is the error message.
113 2cc6781a Iustin Pop

114 2cc6781a Iustin Pop
  """
115 2cc6781a Iustin Pop
116 13998ef2 Michael Hanselmann
117 584ea340 Michele Tartara
def _GetInstReasonFilename(instance_name):
118 a59d5fa1 Michele Tartara
  """Path of the file containing the reason of the instance status change.
119 a59d5fa1 Michele Tartara

120 a59d5fa1 Michele Tartara
  @type instance_name: string
121 a59d5fa1 Michele Tartara
  @param instance_name: The name of the instance
122 a59d5fa1 Michele Tartara
  @rtype: string
123 a59d5fa1 Michele Tartara
  @return: The path of the file
124 a59d5fa1 Michele Tartara

125 a59d5fa1 Michele Tartara
  """
126 a59d5fa1 Michele Tartara
  return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
127 a59d5fa1 Michele Tartara
128 a59d5fa1 Michele Tartara
129 584ea340 Michele Tartara
def _StoreInstReasonTrail(instance_name, trail):
130 584ea340 Michele Tartara
  """Serialize a reason trail related to an instance change of state to file.
131 584ea340 Michele Tartara

132 584ea340 Michele Tartara
  The exact location of the file depends on the name of the instance and on
133 584ea340 Michele Tartara
  the configuration of the Ganeti cluster defined at deploy time.
134 584ea340 Michele Tartara

135 584ea340 Michele Tartara
  @type instance_name: string
136 584ea340 Michele Tartara
  @param instance_name: The name of the instance
137 584ea340 Michele Tartara
  @rtype: None
138 584ea340 Michele Tartara

139 584ea340 Michele Tartara
  """
140 584ea340 Michele Tartara
  json = serializer.DumpJson(trail)
141 584ea340 Michele Tartara
  filename = _GetInstReasonFilename(instance_name)
142 584ea340 Michele Tartara
  utils.WriteFile(filename, data=json)
143 584ea340 Michele Tartara
144 584ea340 Michele Tartara
145 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
146 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
147 2cc6781a Iustin Pop

148 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
149 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
150 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
151 2cc6781a Iustin Pop
  daemon.
152 2cc6781a Iustin Pop

153 2cc6781a Iustin Pop
  @type msg: string
154 2cc6781a Iustin Pop
  @param msg: the text of the exception
155 2cc6781a Iustin Pop
  @raise RPCFail
156 2cc6781a Iustin Pop

157 2cc6781a Iustin Pop
  """
158 2cc6781a Iustin Pop
  if args:
159 2cc6781a Iustin Pop
    msg = msg % args
160 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
161 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
162 afdc3985 Iustin Pop
      logging.exception(msg)
163 afdc3985 Iustin Pop
    else:
164 afdc3985 Iustin Pop
      logging.error(msg)
165 2cc6781a Iustin Pop
  raise RPCFail(msg)
166 2cc6781a Iustin Pop
167 2cc6781a Iustin Pop
168 c657dcc9 Michael Hanselmann
def _GetConfig():
169 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
170 10c2650b Iustin Pop

171 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
172 93384844 Iustin Pop
  @return: a SimpleStore instance
173 10c2650b Iustin Pop

174 10c2650b Iustin Pop
  """
175 93384844 Iustin Pop
  return ssconf.SimpleStore()
176 c657dcc9 Michael Hanselmann
177 c657dcc9 Michael Hanselmann
178 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
179 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
180 10c2650b Iustin Pop

181 10c2650b Iustin Pop
  @type cluster_name: str
182 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
183 10c2650b Iustin Pop
      by the SshRunner constructor
184 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
185 10c2650b Iustin Pop
  @return: an SshRunner instance
186 10c2650b Iustin Pop

187 10c2650b Iustin Pop
  """
188 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
189 c92b310a Michael Hanselmann
190 c92b310a Michael Hanselmann
191 12bce260 Michael Hanselmann
def _Decompress(data):
192 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
193 12bce260 Michael Hanselmann

194 12bce260 Michael Hanselmann
  @type data: list or tuple
195 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
196 12bce260 Michael Hanselmann
  @rtype: str
197 12bce260 Michael Hanselmann
  @return: Decompressed data
198 12bce260 Michael Hanselmann

199 12bce260 Michael Hanselmann
  """
200 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
201 12bce260 Michael Hanselmann
  assert len(data) == 2
202 12bce260 Michael Hanselmann
  (encoding, content) = data
203 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
204 12bce260 Michael Hanselmann
    return content
205 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
206 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
207 12bce260 Michael Hanselmann
  else:
208 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
209 12bce260 Michael Hanselmann
210 12bce260 Michael Hanselmann
211 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
212 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
213 76ab5558 Michael Hanselmann

214 10c2650b Iustin Pop
  @type path: str
215 10c2650b Iustin Pop
  @param path: the directory to clean
216 76ab5558 Michael Hanselmann
  @type exclude: list
217 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
218 10c2650b Iustin Pop
      to the empty list
219 76ab5558 Michael Hanselmann

220 76ab5558 Michael Hanselmann
  """
221 714ea7ca Iustin Pop
  if path not in _ALLOWED_CLEAN_DIRS:
222 714ea7ca Iustin Pop
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
223 714ea7ca Iustin Pop
          path)
224 714ea7ca Iustin Pop
225 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
226 3956cee1 Michael Hanselmann
    return
227 3bc6be5c Iustin Pop
  if exclude is None:
228 3bc6be5c Iustin Pop
    exclude = []
229 3bc6be5c Iustin Pop
  else:
230 3bc6be5c Iustin Pop
    # Normalize excluded paths
231 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
232 76ab5558 Michael Hanselmann
233 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
234 c4feafe8 Iustin Pop
    full_name = utils.PathJoin(path, rel_name)
235 76ab5558 Michael Hanselmann
    if full_name in exclude:
236 76ab5558 Michael Hanselmann
      continue
237 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
238 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
239 3956cee1 Michael Hanselmann
240 3956cee1 Michael Hanselmann
241 360b0dc2 Iustin Pop
def _BuildUploadFileList():
242 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
243 360b0dc2 Iustin Pop

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

246 360b0dc2 Iustin Pop
  """
247 b397a7d2 Iustin Pop
  allowed_files = set([
248 710f30ec Michael Hanselmann
    pathutils.CLUSTER_CONF_FILE,
249 ee045466 Michael Hanselmann
    pathutils.ETC_HOSTS,
250 710f30ec Michael Hanselmann
    pathutils.SSH_KNOWN_HOSTS_FILE,
251 710f30ec Michael Hanselmann
    pathutils.VNC_PASSWORD_FILE,
252 710f30ec Michael Hanselmann
    pathutils.RAPI_CERT_FILE,
253 710f30ec Michael Hanselmann
    pathutils.SPICE_CERT_FILE,
254 710f30ec Michael Hanselmann
    pathutils.SPICE_CACERT_FILE,
255 710f30ec Michael Hanselmann
    pathutils.RAPI_USERS_FILE,
256 710f30ec Michael Hanselmann
    pathutils.CONFD_HMAC_KEY,
257 710f30ec Michael Hanselmann
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
258 b397a7d2 Iustin Pop
    ])
259 b397a7d2 Iustin Pop
260 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
261 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
262 69ab2e12 Guido Trotter
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
263 b397a7d2 Iustin Pop
264 3439fd6b Michael Hanselmann
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
265 3439fd6b Michael Hanselmann
    "Allowed file storage paths should never be uploaded via RPC"
266 3439fd6b Michael Hanselmann
267 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
268 360b0dc2 Iustin Pop
269 360b0dc2 Iustin Pop
270 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
271 360b0dc2 Iustin Pop
272 360b0dc2 Iustin Pop
273 1bc59f76 Michael Hanselmann
def JobQueuePurge():
274 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
275 10c2650b Iustin Pop

276 c8457ce7 Iustin Pop
  @rtype: tuple
277 c8457ce7 Iustin Pop
  @return: True, None
278 24fc781f Michael Hanselmann

279 24fc781f Michael Hanselmann
  """
280 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
281 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
282 24fc781f Michael Hanselmann
283 24fc781f Michael Hanselmann
284 bd1e4562 Iustin Pop
def GetMasterInfo():
285 bd1e4562 Iustin Pop
  """Returns master information.
286 bd1e4562 Iustin Pop

287 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
288 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
289 bd1e4562 Iustin Pop

290 bd1e4562 Iustin Pop
  @rtype: tuple
291 909b3a0e Andrea Spadaccini
  @return: master_netdev, master_ip, master_name, primary_ip_family,
292 909b3a0e Andrea Spadaccini
    master_netmask
293 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
294 b1b6ea87 Iustin Pop

295 b1b6ea87 Iustin Pop
  """
296 b1b6ea87 Iustin Pop
  try:
297 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
298 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
299 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
300 5a8648eb Andrea Spadaccini
    master_netmask = cfg.GetMasterNetmask()
301 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
302 d8e0caa6 Manuel Franceschini
    primary_ip_family = cfg.GetPrimaryIPFamily()
303 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
304 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
305 909b3a0e Andrea Spadaccini
  return (master_netdev, master_ip, master_node, primary_ip_family,
306 5ae4945a Iustin Pop
          master_netmask)
307 b1b6ea87 Iustin Pop
308 b1b6ea87 Iustin Pop
309 0fa481f5 Andrea Spadaccini
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
310 0fa481f5 Andrea Spadaccini
  """Decorator that runs hooks before and after the decorated function.
311 0fa481f5 Andrea Spadaccini

312 0fa481f5 Andrea Spadaccini
  @type hook_opcode: string
313 0fa481f5 Andrea Spadaccini
  @param hook_opcode: opcode of the hook
314 0fa481f5 Andrea Spadaccini
  @type hooks_path: string
315 0fa481f5 Andrea Spadaccini
  @param hooks_path: path of the hooks
316 0fa481f5 Andrea Spadaccini
  @type env_builder_fn: function
317 0fa481f5 Andrea Spadaccini
  @param env_builder_fn: function that returns a dictionary containing the
318 3ccd3243 Andrea Spadaccini
    environment variables for the hooks. Will get all the parameters of the
319 3ccd3243 Andrea Spadaccini
    decorated function.
320 0fa481f5 Andrea Spadaccini
  @raise RPCFail: in case of pre-hook failure
321 0fa481f5 Andrea Spadaccini

322 0fa481f5 Andrea Spadaccini
  """
323 0fa481f5 Andrea Spadaccini
  def decorator(fn):
324 0fa481f5 Andrea Spadaccini
    def wrapper(*args, **kwargs):
325 0fa481f5 Andrea Spadaccini
      _, myself = ssconf.GetMasterAndMyself()
326 0fa481f5 Andrea Spadaccini
      nodes = ([myself], [myself])  # these hooks run locally
327 0fa481f5 Andrea Spadaccini
328 3ccd3243 Andrea Spadaccini
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
329 3ccd3243 Andrea Spadaccini
330 0fa481f5 Andrea Spadaccini
      cfg = _GetConfig()
331 0fa481f5 Andrea Spadaccini
      hr = HooksRunner()
332 68d95757 Guido Trotter
      hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
333 68d95757 Guido Trotter
                                   hr.RunLocalHooks, None, env_fn,
334 68d95757 Guido Trotter
                                   logging.warning, cfg.GetClusterName(),
335 68d95757 Guido Trotter
                                   cfg.GetMasterNode())
336 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
337 0fa481f5 Andrea Spadaccini
      result = fn(*args, **kwargs)
338 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_POST)
339 0fa481f5 Andrea Spadaccini
340 0fa481f5 Andrea Spadaccini
      return result
341 0fa481f5 Andrea Spadaccini
    return wrapper
342 0fa481f5 Andrea Spadaccini
  return decorator
343 0fa481f5 Andrea Spadaccini
344 0fa481f5 Andrea Spadaccini
345 57c7bc57 Andrea Spadaccini
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
346 2d88fdd3 Andrea Spadaccini
  """Builds environment variables for master IP hooks.
347 2d88fdd3 Andrea Spadaccini

348 3ccd3243 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
349 3ccd3243 Andrea Spadaccini
  @param master_params: network parameters of the master
350 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
351 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
352 57c7bc57 Andrea Spadaccini
    address setup script (unused, but necessary per the implementation of the
353 57c7bc57 Andrea Spadaccini
    _RunLocalHooks decorator)
354 3ccd3243 Andrea Spadaccini

355 2d88fdd3 Andrea Spadaccini
  """
356 57c7bc57 Andrea Spadaccini
  # pylint: disable=W0613
357 3ccd3243 Andrea Spadaccini
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
358 2d88fdd3 Andrea Spadaccini
  env = {
359 3ccd3243 Andrea Spadaccini
    "MASTER_NETDEV": master_params.netdev,
360 3ccd3243 Andrea Spadaccini
    "MASTER_IP": master_params.ip,
361 702eff21 Andrea Spadaccini
    "MASTER_NETMASK": str(master_params.netmask),
362 3ccd3243 Andrea Spadaccini
    "CLUSTER_IP_VERSION": str(ver),
363 2d88fdd3 Andrea Spadaccini
  }
364 2d88fdd3 Andrea Spadaccini
365 2d88fdd3 Andrea Spadaccini
  return env
366 2d88fdd3 Andrea Spadaccini
367 2d88fdd3 Andrea Spadaccini
368 702eff21 Andrea Spadaccini
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
369 702eff21 Andrea Spadaccini
  """Execute the master IP address setup script.
370 702eff21 Andrea Spadaccini

371 702eff21 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
372 702eff21 Andrea Spadaccini
  @param master_params: network parameters of the master
373 702eff21 Andrea Spadaccini
  @type action: string
374 702eff21 Andrea Spadaccini
  @param action: action to pass to the script. Must be one of
375 702eff21 Andrea Spadaccini
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
376 702eff21 Andrea Spadaccini
  @type use_external_mip_script: boolean
377 702eff21 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
378 702eff21 Andrea Spadaccini
    address setup script
379 702eff21 Andrea Spadaccini
  @raise backend.RPCFail: if there are errors during the execution of the
380 702eff21 Andrea Spadaccini
    script
381 702eff21 Andrea Spadaccini

382 702eff21 Andrea Spadaccini
  """
383 702eff21 Andrea Spadaccini
  env = _BuildMasterIpEnv(master_params)
384 702eff21 Andrea Spadaccini
385 702eff21 Andrea Spadaccini
  if use_external_mip_script:
386 710f30ec Michael Hanselmann
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
387 702eff21 Andrea Spadaccini
  else:
388 710f30ec Michael Hanselmann
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
389 702eff21 Andrea Spadaccini
390 702eff21 Andrea Spadaccini
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
391 702eff21 Andrea Spadaccini
392 702eff21 Andrea Spadaccini
  if result.failed:
393 19e1b715 Iustin Pop
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
394 19e1b715 Iustin Pop
          (action, result.exit_code, result.output), log=True)
395 702eff21 Andrea Spadaccini
396 702eff21 Andrea Spadaccini
397 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
398 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
399 57c7bc57 Andrea Spadaccini
def ActivateMasterIp(master_params, use_external_mip_script):
400 fb460cf7 Andrea Spadaccini
  """Activate the IP address of the master daemon.
401 fb460cf7 Andrea Spadaccini

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

409 fb460cf7 Andrea Spadaccini
  """
410 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_START,
411 702eff21 Andrea Spadaccini
                        use_external_mip_script)
412 fb460cf7 Andrea Spadaccini
413 fb460cf7 Andrea Spadaccini
414 fb460cf7 Andrea Spadaccini
def StartMasterDaemons(no_voting):
415 a8083063 Iustin Pop
  """Activate local node as master node.
416 a8083063 Iustin Pop

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

419 3583908a Guido Trotter
  @type no_voting: boolean
420 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
421 fb460cf7 Andrea Spadaccini
      but still non-interactively
422 10c2650b Iustin Pop
  @rtype: None
423 a8083063 Iustin Pop

424 a8083063 Iustin Pop
  """
425 a8083063 Iustin Pop
426 fb460cf7 Andrea Spadaccini
  if no_voting:
427 fb460cf7 Andrea Spadaccini
    masterd_args = "--no-voting --yes-do-it"
428 fb460cf7 Andrea Spadaccini
  else:
429 fb460cf7 Andrea Spadaccini
    masterd_args = ""
430 f154a7a3 Michael Hanselmann
431 fb460cf7 Andrea Spadaccini
  env = {
432 fb460cf7 Andrea Spadaccini
    "EXTRA_MASTERD_ARGS": masterd_args,
433 fb460cf7 Andrea Spadaccini
    }
434 fb460cf7 Andrea Spadaccini
435 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
436 fb460cf7 Andrea Spadaccini
  if result.failed:
437 fb460cf7 Andrea Spadaccini
    msg = "Can't start Ganeti master: %s" % result.output
438 fb460cf7 Andrea Spadaccini
    logging.error(msg)
439 fb460cf7 Andrea Spadaccini
    _Fail(msg)
440 f154a7a3 Michael Hanselmann
441 fb460cf7 Andrea Spadaccini
442 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
443 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
444 57c7bc57 Andrea Spadaccini
def DeactivateMasterIp(master_params, use_external_mip_script):
445 fb460cf7 Andrea Spadaccini
  """Deactivate the master IP on this node.
446 a8083063 Iustin Pop

447 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
448 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
449 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
450 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
451 57c7bc57 Andrea Spadaccini
    address setup script
452 702eff21 Andrea Spadaccini
  @raise RPCFail: in case of errors during the IP turndown
453 96e0d5cc Andrea Spadaccini

454 a8083063 Iustin Pop
  """
455 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_STOP,
456 702eff21 Andrea Spadaccini
                        use_external_mip_script)
457 b1b6ea87 Iustin Pop
458 fb460cf7 Andrea Spadaccini
459 fb460cf7 Andrea Spadaccini
def StopMasterDaemons():
460 fb460cf7 Andrea Spadaccini
  """Stop the master daemons on this node.
461 fb460cf7 Andrea Spadaccini

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

464 fb460cf7 Andrea Spadaccini
  @rtype: None
465 fb460cf7 Andrea Spadaccini

466 fb460cf7 Andrea Spadaccini
  """
467 fb460cf7 Andrea Spadaccini
  # TODO: log and report back to the caller the error failures; we
468 fb460cf7 Andrea Spadaccini
  # need to decide in which case we fail the RPC for this
469 fb460cf7 Andrea Spadaccini
470 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
471 fb460cf7 Andrea Spadaccini
  if result.failed:
472 fb460cf7 Andrea Spadaccini
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
473 fb460cf7 Andrea Spadaccini
                  " and error %s",
474 fb460cf7 Andrea Spadaccini
                  result.cmd, result.exit_code, result.output)
475 a8083063 Iustin Pop
476 a8083063 Iustin Pop
477 41e079ce Andrea Spadaccini
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
478 5a8648eb Andrea Spadaccini
  """Change the netmask of the master IP.
479 5a8648eb Andrea Spadaccini

480 41e079ce Andrea Spadaccini
  @param old_netmask: the old value of the netmask
481 41e079ce Andrea Spadaccini
  @param netmask: the new value of the netmask
482 41e079ce Andrea Spadaccini
  @param master_ip: the master IP
483 41e079ce Andrea Spadaccini
  @param master_netdev: the master network device
484 41e079ce Andrea Spadaccini

485 5a8648eb Andrea Spadaccini
  """
486 5a8648eb Andrea Spadaccini
  if old_netmask == netmask:
487 5a8648eb Andrea Spadaccini
    return
488 5a8648eb Andrea Spadaccini
489 9e6014b9 Andrea Spadaccini
  if not netutils.IPAddress.Own(master_ip):
490 9e6014b9 Andrea Spadaccini
    _Fail("The master IP address is not up, not attempting to change its"
491 9e6014b9 Andrea Spadaccini
          " netmask")
492 9e6014b9 Andrea Spadaccini
493 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
494 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, netmask),
495 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
496 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
497 5a8648eb Andrea Spadaccini
  if result.failed:
498 9e6014b9 Andrea Spadaccini
    _Fail("Could not set the new netmask on the master IP address")
499 5a8648eb Andrea Spadaccini
500 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
501 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, old_netmask),
502 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
503 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
504 5a8648eb Andrea Spadaccini
  if result.failed:
505 9e6014b9 Andrea Spadaccini
    _Fail("Could not bring down the master IP address with the old netmask")
506 5a8648eb Andrea Spadaccini
507 5a8648eb Andrea Spadaccini
508 19ddc57a René Nussbaumer
def EtcHostsModify(mode, host, ip):
509 19ddc57a René Nussbaumer
  """Modify a host entry in /etc/hosts.
510 19ddc57a René Nussbaumer

511 19ddc57a René Nussbaumer
  @param mode: The mode to operate. Either add or remove entry
512 19ddc57a René Nussbaumer
  @param host: The host to operate on
513 19ddc57a René Nussbaumer
  @param ip: The ip associated with the entry
514 19ddc57a René Nussbaumer

515 19ddc57a René Nussbaumer
  """
516 19ddc57a René Nussbaumer
  if mode == constants.ETC_HOSTS_ADD:
517 19ddc57a René Nussbaumer
    if not ip:
518 19ddc57a René Nussbaumer
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
519 19ddc57a René Nussbaumer
              " present")
520 19ddc57a René Nussbaumer
    utils.AddHostToEtcHosts(host, ip)
521 19ddc57a René Nussbaumer
  elif mode == constants.ETC_HOSTS_REMOVE:
522 19ddc57a René Nussbaumer
    if ip:
523 19ddc57a René Nussbaumer
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
524 19ddc57a René Nussbaumer
              " parameter is present")
525 19ddc57a René Nussbaumer
    utils.RemoveHostFromEtcHosts(host)
526 19ddc57a René Nussbaumer
  else:
527 19ddc57a René Nussbaumer
    RPCFail("Mode not supported")
528 19ddc57a René Nussbaumer
529 19ddc57a René Nussbaumer
530 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
531 10c2650b Iustin Pop
  """Cleans up and remove the current node.
532 10c2650b Iustin Pop

533 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
534 10c2650b Iustin Pop
  from the cluster.
535 10c2650b Iustin Pop

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

540 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
541 b989b9d9 Ken Wehr

542 a8083063 Iustin Pop
  """
543 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.DATA_DIR)
544 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
545 1bc59f76 Michael Hanselmann
  JobQueuePurge()
546 f78346f5 Michael Hanselmann
547 b989b9d9 Ken Wehr
  if modify_ssh_setup:
548 b989b9d9 Ken Wehr
    try:
549 052783ff Michael Hanselmann
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
550 7900ed01 Iustin Pop
551 b989b9d9 Ken Wehr
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
552 a8083063 Iustin Pop
553 b989b9d9 Ken Wehr
      utils.RemoveFile(priv_key)
554 b989b9d9 Ken Wehr
      utils.RemoveFile(pub_key)
555 b989b9d9 Ken Wehr
    except errors.OpExecError:
556 b989b9d9 Ken Wehr
      logging.exception("Error while processing ssh files")
557 a8083063 Iustin Pop
558 ed008420 Guido Trotter
  try:
559 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
560 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
561 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
562 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
563 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
564 b459a848 Andrea Spadaccini
  except: # pylint: disable=W0702
565 ed008420 Guido Trotter
    logging.exception("Error while removing cluster secrets")
566 ed008420 Guido Trotter
567 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
568 f154a7a3 Michael Hanselmann
  if result.failed:
569 f154a7a3 Michael Hanselmann
    logging.error("Command %s failed with exitcode %s and error %s",
570 f154a7a3 Michael Hanselmann
                  result.cmd, result.exit_code, result.output)
571 ed008420 Guido Trotter
572 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
573 d0c8c01d Iustin Pop
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
574 6d8b6238 Guido Trotter
575 a8083063 Iustin Pop
576 b01b7a50 Helga Velroyen
def _CheckStorageParams(params, num_params):
577 b01b7a50 Helga Velroyen
  """Performs sanity checks for storage parameters.
578 b01b7a50 Helga Velroyen

579 b01b7a50 Helga Velroyen
  @type params: list
580 b01b7a50 Helga Velroyen
  @param params: list of storage parameters
581 b01b7a50 Helga Velroyen
  @type num_params: int
582 b01b7a50 Helga Velroyen
  @param num_params: expected number of parameters
583 b01b7a50 Helga Velroyen

584 b01b7a50 Helga Velroyen
  """
585 b01b7a50 Helga Velroyen
  if params is None:
586 b01b7a50 Helga Velroyen
    raise errors.ProgrammerError("No storage parameters for storage"
587 b01b7a50 Helga Velroyen
                                 " reporting is provided.")
588 b01b7a50 Helga Velroyen
  if not isinstance(params, list):
589 b01b7a50 Helga Velroyen
    raise errors.ProgrammerError("The storage parameters are not of type"
590 b01b7a50 Helga Velroyen
                                 " list: '%s'" % params)
591 b01b7a50 Helga Velroyen
  if not len(params) == num_params:
592 b01b7a50 Helga Velroyen
    raise errors.ProgrammerError("Did not receive the expected number of"
593 b01b7a50 Helga Velroyen
                                 "storage parameters: expected %s,"
594 b01b7a50 Helga Velroyen
                                 " received '%s'" % (num_params, len(params)))
595 b01b7a50 Helga Velroyen
596 b01b7a50 Helga Velroyen
597 3c8a599a Helga Velroyen
def _CheckLvmStorageParams(params):
598 3c8a599a Helga Velroyen
  """Performs sanity check for the 'exclusive storage' flag.
599 3c8a599a Helga Velroyen

600 3c8a599a Helga Velroyen
  @see: C{_CheckStorageParams}
601 3c8a599a Helga Velroyen

602 3c8a599a Helga Velroyen
  """
603 3c8a599a Helga Velroyen
  _CheckStorageParams(params, 1)
604 3c8a599a Helga Velroyen
  excl_stor = params[0]
605 3c8a599a Helga Velroyen
  if not isinstance(params[0], bool):
606 3c8a599a Helga Velroyen
    raise errors.ProgrammerError("Exclusive storage parameter is not"
607 3c8a599a Helga Velroyen
                                 " boolean: '%s'." % excl_stor)
608 3c8a599a Helga Velroyen
  return excl_stor
609 3c8a599a Helga Velroyen
610 3c8a599a Helga Velroyen
611 52a8a6ae Helga Velroyen
def _GetLvmVgSpaceInfo(name, params):
612 52a8a6ae Helga Velroyen
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.
613 52a8a6ae Helga Velroyen

614 52a8a6ae Helga Velroyen
  @type name: string
615 52a8a6ae Helga Velroyen
  @param name: name of the volume group
616 52a8a6ae Helga Velroyen
  @type params: list
617 52a8a6ae Helga Velroyen
  @param params: list of storage parameters, which in this case should be
618 52a8a6ae Helga Velroyen
    containing only one for exclusive storage
619 52a8a6ae Helga Velroyen

620 52a8a6ae Helga Velroyen
  """
621 3c8a599a Helga Velroyen
  excl_stor = _CheckLvmStorageParams(params)
622 52a8a6ae Helga Velroyen
  return _GetVgInfo(name, excl_stor)
623 52a8a6ae Helga Velroyen
624 52a8a6ae Helga Velroyen
625 3f73b3ae Helga Velroyen
def _GetVgInfo(
626 3f73b3ae Helga Velroyen
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
627 78519c10 Michael Hanselmann
  """Retrieves information about a LVM volume group.
628 78519c10 Michael Hanselmann

629 78519c10 Michael Hanselmann
  """
630 78519c10 Michael Hanselmann
  # TODO: GetVGInfo supports returning information for multiple VGs at once
631 3f73b3ae Helga Velroyen
  vginfo = info_fn([name], excl_stor)
632 78519c10 Michael Hanselmann
  if vginfo:
633 78519c10 Michael Hanselmann
    vg_free = int(round(vginfo[0][0], 0))
634 78519c10 Michael Hanselmann
    vg_size = int(round(vginfo[0][1], 0))
635 78519c10 Michael Hanselmann
  else:
636 78519c10 Michael Hanselmann
    vg_free = None
637 78519c10 Michael Hanselmann
    vg_size = None
638 78519c10 Michael Hanselmann
639 78519c10 Michael Hanselmann
  return {
640 0f0f6d7d Helga Velroyen
    "type": constants.ST_LVM_VG,
641 78519c10 Michael Hanselmann
    "name": name,
642 32389d91 Helga Velroyen
    "storage_free": vg_free,
643 32389d91 Helga Velroyen
    "storage_size": vg_size,
644 78519c10 Michael Hanselmann
    }
645 78519c10 Michael Hanselmann
646 78519c10 Michael Hanselmann
647 3c8a599a Helga Velroyen
def _GetLvmPvSpaceInfo(name, params):
648 3c8a599a Helga Velroyen
  """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
649 3c8a599a Helga Velroyen

650 a18ab868 Helga Velroyen
  @see: C{_GetLvmVgSpaceInfo}
651 3c8a599a Helga Velroyen

652 3c8a599a Helga Velroyen
  """
653 3c8a599a Helga Velroyen
  excl_stor = _CheckLvmStorageParams(params)
654 3c8a599a Helga Velroyen
  return _GetVgSpindlesInfo(name, excl_stor)
655 3f73b3ae Helga Velroyen
656 3c8a599a Helga Velroyen
657 a18ab868 Helga Velroyen
def _GetVgSpindlesInfo(
658 a18ab868 Helga Velroyen
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
659 a1860404 Bernardo Dal Seno
  """Retrieves information about spindles in an LVM volume group.
660 a1860404 Bernardo Dal Seno

661 a1860404 Bernardo Dal Seno
  @type name: string
662 a1860404 Bernardo Dal Seno
  @param name: VG name
663 a1860404 Bernardo Dal Seno
  @type excl_stor: bool
664 a1860404 Bernardo Dal Seno
  @param excl_stor: exclusive storage
665 a1860404 Bernardo Dal Seno
  @rtype: dict
666 a1860404 Bernardo Dal Seno
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
667 a1860404 Bernardo Dal Seno
      free spindles, total spindles respectively
668 a1860404 Bernardo Dal Seno

669 a1860404 Bernardo Dal Seno
  """
670 a1860404 Bernardo Dal Seno
  if excl_stor:
671 a18ab868 Helga Velroyen
    (vg_free, vg_size) = info_fn(name)
672 a1860404 Bernardo Dal Seno
  else:
673 a1860404 Bernardo Dal Seno
    vg_free = 0
674 a1860404 Bernardo Dal Seno
    vg_size = 0
675 a1860404 Bernardo Dal Seno
  return {
676 0f0f6d7d Helga Velroyen
    "type": constants.ST_LVM_PV,
677 a1860404 Bernardo Dal Seno
    "name": name,
678 32389d91 Helga Velroyen
    "storage_free": vg_free,
679 32389d91 Helga Velroyen
    "storage_size": vg_size,
680 a1860404 Bernardo Dal Seno
    }
681 a1860404 Bernardo Dal Seno
682 a1860404 Bernardo Dal Seno
683 439e1d3f Helga Velroyen
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
684 78519c10 Michael Hanselmann
  """Retrieves node information from a hypervisor.
685 78519c10 Michael Hanselmann

686 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
687 78519c10 Michael Hanselmann

688 78519c10 Michael Hanselmann
    - vg_size is the size of the configured volume group in MiB
689 78519c10 Michael Hanselmann
    - vg_free is the free size of the volume group in MiB
690 78519c10 Michael Hanselmann
    - memory_dom0 is the memory allocated for domain0 in MiB
691 78519c10 Michael Hanselmann
    - memory_free is the currently available (free) ram in MiB
692 78519c10 Michael Hanselmann
    - memory_total is the total number of ram in MiB
693 78519c10 Michael Hanselmann
    - hv_version: the hypervisor version, if available
694 78519c10 Michael Hanselmann

695 439e1d3f Helga Velroyen
  @type hvparams: dict of string
696 439e1d3f Helga Velroyen
  @param hvparams: the hypervisor's hvparams
697 439e1d3f Helga Velroyen

698 78519c10 Michael Hanselmann
  """
699 439e1d3f Helga Velroyen
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
700 439e1d3f Helga Velroyen
701 439e1d3f Helga Velroyen
702 439e1d3f Helga Velroyen
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
703 439e1d3f Helga Velroyen
  """Retrieves node information for all hypervisors.
704 439e1d3f Helga Velroyen

705 439e1d3f Helga Velroyen
  See C{_GetHvInfo} for information on the output.
706 439e1d3f Helga Velroyen

707 439e1d3f Helga Velroyen
  @type hv_specs: list of pairs (string, dict of strings)
708 439e1d3f Helga Velroyen
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
709 439e1d3f Helga Velroyen

710 439e1d3f Helga Velroyen
  """
711 439e1d3f Helga Velroyen
  if hv_specs is None:
712 439e1d3f Helga Velroyen
    return None
713 439e1d3f Helga Velroyen
714 439e1d3f Helga Velroyen
  result = []
715 439e1d3f Helga Velroyen
  for hvname, hvparams in hv_specs:
716 439e1d3f Helga Velroyen
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
717 439e1d3f Helga Velroyen
  return result
718 78519c10 Michael Hanselmann
719 78519c10 Michael Hanselmann
720 78519c10 Michael Hanselmann
def _GetNamedNodeInfo(names, fn):
721 78519c10 Michael Hanselmann
  """Calls C{fn} for all names in C{names} and returns a dictionary.
722 78519c10 Michael Hanselmann

723 78519c10 Michael Hanselmann
  @rtype: None or dict
724 78519c10 Michael Hanselmann

725 78519c10 Michael Hanselmann
  """
726 78519c10 Michael Hanselmann
  if names is None:
727 78519c10 Michael Hanselmann
    return None
728 78519c10 Michael Hanselmann
  else:
729 ff3be305 Michael Hanselmann
    return map(fn, names)
730 78519c10 Michael Hanselmann
731 78519c10 Michael Hanselmann
732 152759e4 Helga Velroyen
def GetNodeInfo(storage_units, hv_specs):
733 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
734 a8083063 Iustin Pop

735 152759e4 Helga Velroyen
  @type storage_units: list of tuples (string, string, list)
736 152759e4 Helga Velroyen
  @param storage_units: List of tuples (storage unit, identifier, parameters) to
737 152759e4 Helga Velroyen
    ask for disk space information. In case of lvm-vg, the identifier is
738 152759e4 Helga Velroyen
    the VG name. The parameters can contain additional, storage-type-specific
739 152759e4 Helga Velroyen
    parameters, for example exclusive storage for lvm storage.
740 439e1d3f Helga Velroyen
  @type hv_specs: list of pairs (string, dict of strings)
741 439e1d3f Helga Velroyen
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
742 78519c10 Michael Hanselmann
  @rtype: tuple; (string, None/dict, None/dict)
743 78519c10 Michael Hanselmann
  @return: Tuple containing boot ID, volume group information and hypervisor
744 78519c10 Michael Hanselmann
    information
745 a8083063 Iustin Pop

746 098c0958 Michael Hanselmann
  """
747 78519c10 Michael Hanselmann
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
748 4b92e992 Helga Velroyen
  storage_info = _GetNamedNodeInfo(
749 4b92e992 Helga Velroyen
    storage_units,
750 152759e4 Helga Velroyen
    (lambda (storage_type, storage_key, storage_params):
751 152759e4 Helga Velroyen
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
752 439e1d3f Helga Velroyen
  hv_info = _GetHvInfoAll(hv_specs)
753 4b92e992 Helga Velroyen
  return (bootid, storage_info, hv_info)
754 4b92e992 Helga Velroyen
755 4b92e992 Helga Velroyen
756 b01b7a50 Helga Velroyen
def _GetFileStorageSpaceInfo(path, params):
757 13669ecd Helga Velroyen
  """Wrapper around filestorage.GetSpaceInfo.
758 13669ecd Helga Velroyen

759 13669ecd Helga Velroyen
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
760 13669ecd Helga Velroyen
  and ignore the *args parameter to not leak it into the filestorage
761 13669ecd Helga Velroyen
  module's code.
762 13669ecd Helga Velroyen

763 13669ecd Helga Velroyen
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
764 13669ecd Helga Velroyen
    parameters.
765 13669ecd Helga Velroyen

766 13669ecd Helga Velroyen
  """
767 b01b7a50 Helga Velroyen
  _CheckStorageParams(params, 0)
768 13669ecd Helga Velroyen
  return filestorage.GetFileStorageSpaceInfo(path)
769 13669ecd Helga Velroyen
770 13669ecd Helga Velroyen
771 4b92e992 Helga Velroyen
# FIXME: implement storage reporting for all missing storage types.
772 4b92e992 Helga Velroyen
_STORAGE_TYPE_INFO_FN = {
773 4b92e992 Helga Velroyen
  constants.ST_BLOCK: None,
774 4b92e992 Helga Velroyen
  constants.ST_DISKLESS: None,
775 4b92e992 Helga Velroyen
  constants.ST_EXT: None,
776 13669ecd Helga Velroyen
  constants.ST_FILE: _GetFileStorageSpaceInfo,
777 3c8a599a Helga Velroyen
  constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
778 52a8a6ae Helga Velroyen
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
779 4b92e992 Helga Velroyen
  constants.ST_RADOS: None,
780 4b92e992 Helga Velroyen
}
781 4b92e992 Helga Velroyen
782 4b92e992 Helga Velroyen
783 4b92e992 Helga Velroyen
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
784 4b92e992 Helga Velroyen
  """Looks up and applies the correct function to calculate free and total
785 4b92e992 Helga Velroyen
  storage for the given storage type.
786 4b92e992 Helga Velroyen

787 4b92e992 Helga Velroyen
  @type storage_type: string
788 4b92e992 Helga Velroyen
  @param storage_type: the storage type for which the storage shall be reported.
789 4b92e992 Helga Velroyen
  @type storage_key: string
790 4b92e992 Helga Velroyen
  @param storage_key: identifier of a storage unit, e.g. the volume group name
791 4b92e992 Helga Velroyen
    of an LVM storage unit
792 4b92e992 Helga Velroyen
  @type args: any
793 4b92e992 Helga Velroyen
  @param args: various parameters that can be used for storage reporting. These
794 4b92e992 Helga Velroyen
    parameters and their semantics vary from storage type to storage type and
795 4b92e992 Helga Velroyen
    are just propagated in this function.
796 4b92e992 Helga Velroyen
  @return: the results of the application of the storage space function (see
797 4b92e992 Helga Velroyen
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
798 4b92e992 Helga Velroyen
    storage type
799 4b92e992 Helga Velroyen
  @raises NotImplementedError: for storage types who don't support space
800 4b92e992 Helga Velroyen
    reporting yet
801 4b92e992 Helga Velroyen
  """
802 4b92e992 Helga Velroyen
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
803 4b92e992 Helga Velroyen
  if fn is not None:
804 4b92e992 Helga Velroyen
    return fn(storage_key, *args)
805 4b92e992 Helga Velroyen
  else:
806 4b92e992 Helga Velroyen
    raise NotImplementedError
807 a8083063 Iustin Pop
808 a8083063 Iustin Pop
809 d5a690cb Bernardo Dal Seno
def _CheckExclusivePvs(pvi_list):
810 d5a690cb Bernardo Dal Seno
  """Check that PVs are not shared among LVs
811 d5a690cb Bernardo Dal Seno

812 d5a690cb Bernardo Dal Seno
  @type pvi_list: list of L{objects.LvmPvInfo} objects
813 d5a690cb Bernardo Dal Seno
  @param pvi_list: information about the PVs
814 d5a690cb Bernardo Dal Seno

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

818 d5a690cb Bernardo Dal Seno
  """
819 d5a690cb Bernardo Dal Seno
  res = []
820 d5a690cb Bernardo Dal Seno
  for pvi in pvi_list:
821 d5a690cb Bernardo Dal Seno
    if len(pvi.lv_list) > 1:
822 d5a690cb Bernardo Dal Seno
      res.append((pvi.name, pvi.lv_list))
823 d5a690cb Bernardo Dal Seno
  return res
824 d5a690cb Bernardo Dal Seno
825 d5a690cb Bernardo Dal Seno
826 75bf3149 Helga Velroyen
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
827 75bf3149 Helga Velroyen
                       get_hv_fn=hypervisor.GetHypervisor):
828 75bf3149 Helga Velroyen
  """Verifies the hypervisor. Appends the results to the 'results' list.
829 75bf3149 Helga Velroyen

830 75bf3149 Helga Velroyen
  @type what: C{dict}
831 75bf3149 Helga Velroyen
  @param what: a dictionary of things to check
832 75bf3149 Helga Velroyen
  @type vm_capable: boolean
833 5b0dfcef Helga Velroyen
  @param vm_capable: whether or not this node is vm capable
834 75bf3149 Helga Velroyen
  @type result: dict
835 75bf3149 Helga Velroyen
  @param result: dictionary of verification results; results of the
836 75bf3149 Helga Velroyen
    verifications in this function will be added here
837 75bf3149 Helga Velroyen
  @type all_hvparams: dict of dict of string
838 75bf3149 Helga Velroyen
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
839 75bf3149 Helga Velroyen
  @type get_hv_fn: function
840 75bf3149 Helga Velroyen
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
841 75bf3149 Helga Velroyen

842 75bf3149 Helga Velroyen
  """
843 75bf3149 Helga Velroyen
  if not vm_capable:
844 75bf3149 Helga Velroyen
    return
845 75bf3149 Helga Velroyen
846 75bf3149 Helga Velroyen
  if constants.NV_HYPERVISOR in what:
847 75bf3149 Helga Velroyen
    result[constants.NV_HYPERVISOR] = {}
848 75bf3149 Helga Velroyen
    for hv_name in what[constants.NV_HYPERVISOR]:
849 75bf3149 Helga Velroyen
      hvparams = all_hvparams[hv_name]
850 75bf3149 Helga Velroyen
      try:
851 75bf3149 Helga Velroyen
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
852 75bf3149 Helga Velroyen
      except errors.HypervisorError, err:
853 75bf3149 Helga Velroyen
        val = "Error while checking hypervisor: %s" % str(err)
854 75bf3149 Helga Velroyen
      result[constants.NV_HYPERVISOR][hv_name] = val
855 75bf3149 Helga Velroyen
856 75bf3149 Helga Velroyen
857 75bf3149 Helga Velroyen
def _VerifyHvparams(what, vm_capable, result,
858 75bf3149 Helga Velroyen
                    get_hv_fn=hypervisor.GetHypervisor):
859 75bf3149 Helga Velroyen
  """Verifies the hvparams. Appends the results to the 'results' list.
860 75bf3149 Helga Velroyen

861 75bf3149 Helga Velroyen
  @type what: C{dict}
862 75bf3149 Helga Velroyen
  @param what: a dictionary of things to check
863 75bf3149 Helga Velroyen
  @type vm_capable: boolean
864 5b0dfcef Helga Velroyen
  @param vm_capable: whether or not this node is vm capable
865 75bf3149 Helga Velroyen
  @type result: dict
866 75bf3149 Helga Velroyen
  @param result: dictionary of verification results; results of the
867 75bf3149 Helga Velroyen
    verifications in this function will be added here
868 75bf3149 Helga Velroyen
  @type get_hv_fn: function
869 75bf3149 Helga Velroyen
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
870 75bf3149 Helga Velroyen

871 75bf3149 Helga Velroyen
  """
872 75bf3149 Helga Velroyen
  if not vm_capable:
873 75bf3149 Helga Velroyen
    return
874 75bf3149 Helga Velroyen
875 75bf3149 Helga Velroyen
  if constants.NV_HVPARAMS in what:
876 75bf3149 Helga Velroyen
    result[constants.NV_HVPARAMS] = []
877 75bf3149 Helga Velroyen
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
878 75bf3149 Helga Velroyen
      try:
879 75bf3149 Helga Velroyen
        logging.info("Validating hv %s, %s", hv_name, hvparms)
880 75bf3149 Helga Velroyen
        get_hv_fn(hv_name).ValidateParameters(hvparms)
881 75bf3149 Helga Velroyen
      except errors.HypervisorError, err:
882 75bf3149 Helga Velroyen
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
883 75bf3149 Helga Velroyen
884 75bf3149 Helga Velroyen
885 5b0dfcef Helga Velroyen
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
886 5b0dfcef Helga Velroyen
  """Verifies the instance list.
887 5b0dfcef Helga Velroyen

888 5b0dfcef Helga Velroyen
  @type what: C{dict}
889 5b0dfcef Helga Velroyen
  @param what: a dictionary of things to check
890 5b0dfcef Helga Velroyen
  @type vm_capable: boolean
891 5b0dfcef Helga Velroyen
  @param vm_capable: whether or not this node is vm capable
892 5b0dfcef Helga Velroyen
  @type result: dict
893 5b0dfcef Helga Velroyen
  @param result: dictionary of verification results; results of the
894 5b0dfcef Helga Velroyen
    verifications in this function will be added here
895 5b0dfcef Helga Velroyen
  @type all_hvparams: dict of dict of string
896 5b0dfcef Helga Velroyen
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
897 5b0dfcef Helga Velroyen

898 5b0dfcef Helga Velroyen
  """
899 5b0dfcef Helga Velroyen
  if constants.NV_INSTANCELIST in what and vm_capable:
900 5b0dfcef Helga Velroyen
    # GetInstanceList can fail
901 5b0dfcef Helga Velroyen
    try:
902 5b0dfcef Helga Velroyen
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
903 5b0dfcef Helga Velroyen
                            all_hvparams=all_hvparams)
904 5b0dfcef Helga Velroyen
    except RPCFail, err:
905 5b0dfcef Helga Velroyen
      val = str(err)
906 5b0dfcef Helga Velroyen
    result[constants.NV_INSTANCELIST] = val
907 5b0dfcef Helga Velroyen
908 5b0dfcef Helga Velroyen
909 5b0dfcef Helga Velroyen
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
910 5b0dfcef Helga Velroyen
  """Verifies the node info.
911 5b0dfcef Helga Velroyen

912 5b0dfcef Helga Velroyen
  @type what: C{dict}
913 5b0dfcef Helga Velroyen
  @param what: a dictionary of things to check
914 5b0dfcef Helga Velroyen
  @type vm_capable: boolean
915 5b0dfcef Helga Velroyen
  @param vm_capable: whether or not this node is vm capable
916 5b0dfcef Helga Velroyen
  @type result: dict
917 5b0dfcef Helga Velroyen
  @param result: dictionary of verification results; results of the
918 5b0dfcef Helga Velroyen
    verifications in this function will be added here
919 5b0dfcef Helga Velroyen
  @type all_hvparams: dict of dict of string
920 5b0dfcef Helga Velroyen
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
921 5b0dfcef Helga Velroyen

922 5b0dfcef Helga Velroyen
  """
923 5b0dfcef Helga Velroyen
  if constants.NV_HVINFO in what and vm_capable:
924 5b0dfcef Helga Velroyen
    hvname = what[constants.NV_HVINFO]
925 5b0dfcef Helga Velroyen
    hyper = hypervisor.GetHypervisor(hvname)
926 5b0dfcef Helga Velroyen
    hvparams = all_hvparams[hvname]
927 5b0dfcef Helga Velroyen
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
928 5b0dfcef Helga Velroyen
929 5b0dfcef Helga Velroyen
930 5b0dfcef Helga Velroyen
def VerifyNode(what, cluster_name, all_hvparams):
931 a8083063 Iustin Pop
  """Verify the status of the local node.
932 a8083063 Iustin Pop

933 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
934 e69d05fd Iustin Pop
  local node.
935 e69d05fd Iustin Pop

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

939 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
940 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
941 e69d05fd Iustin Pop
  report).
942 a8083063 Iustin Pop

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

947 e69d05fd Iustin Pop
  @type what: C{dict}
948 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
949 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
950 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
951 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
952 e69d05fd Iustin Pop
        connectivity with
953 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
954 5b0dfcef Helga Velroyen
  @type cluster_name: string
955 5b0dfcef Helga Velroyen
  @param cluster_name: the cluster's name
956 5b0dfcef Helga Velroyen
  @type all_hvparams: dict of dict of strings
957 5b0dfcef Helga Velroyen
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
958 10c2650b Iustin Pop
  @rtype: dict
959 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
960 10c2650b Iustin Pop
      values representing the result of the checks
961 a8083063 Iustin Pop

962 a8083063 Iustin Pop
  """
963 a8083063 Iustin Pop
  result = {}
964 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
965 a744b676 Manuel Franceschini
  port = netutils.GetDaemonPort(constants.NODED)
966 8964ee14 Iustin Pop
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
967 a8083063 Iustin Pop
968 75bf3149 Helga Velroyen
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
969 75bf3149 Helga Velroyen
  _VerifyHvparams(what, vm_capable, result)
970 58a59652 Iustin Pop
971 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
972 47130d50 Michael Hanselmann
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
973 47130d50 Michael Hanselmann
                                              what[constants.NV_FILELIST]))
974 47130d50 Michael Hanselmann
    result[constants.NV_FILELIST] = \
975 47130d50 Michael Hanselmann
      dict((vcluster.MakeVirtualPath(key), value)
976 47130d50 Michael Hanselmann
           for (key, value) in fingerprints.items())
977 25361b9a Iustin Pop
978 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
979 64c7b383 Michael Hanselmann
    (nodes, bynode) = what[constants.NV_NODELIST]
980 64c7b383 Michael Hanselmann
981 64c7b383 Michael Hanselmann
    # Add nodes from other groups (different for each node)
982 64c7b383 Michael Hanselmann
    try:
983 64c7b383 Michael Hanselmann
      nodes.extend(bynode[my_name])
984 64c7b383 Michael Hanselmann
    except KeyError:
985 64c7b383 Michael Hanselmann
      pass
986 64c7b383 Michael Hanselmann
987 64c7b383 Michael Hanselmann
    # Use a random order
988 64c7b383 Michael Hanselmann
    random.shuffle(nodes)
989 64c7b383 Michael Hanselmann
990 64c7b383 Michael Hanselmann
    # Try to contact all nodes
991 64c7b383 Michael Hanselmann
    val = {}
992 64c7b383 Michael Hanselmann
    for node in nodes:
993 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
994 a8083063 Iustin Pop
      if not success:
995 64c7b383 Michael Hanselmann
        val[node] = message
996 64c7b383 Michael Hanselmann
997 64c7b383 Michael Hanselmann
    result[constants.NV_NODELIST] = val
998 25361b9a Iustin Pop
999 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
1000 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
1001 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
1002 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
1003 9d4bfc96 Iustin Pop
      if name == my_name:
1004 9d4bfc96 Iustin Pop
        my_pip = pip
1005 9d4bfc96 Iustin Pop
        my_sip = sip
1006 9d4bfc96 Iustin Pop
        break
1007 9d4bfc96 Iustin Pop
    if not my_pip:
1008 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
1009 25361b9a Iustin Pop
                      " in the node list")
1010 9d4bfc96 Iustin Pop
    else:
1011 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
1012 9d4bfc96 Iustin Pop
        fail = []
1013 a744b676 Manuel Franceschini
        if not netutils.TcpPing(pip, port, source=my_pip):
1014 9d4bfc96 Iustin Pop
          fail.append("primary")
1015 9d4bfc96 Iustin Pop
        if sip != pip:
1016 a744b676 Manuel Franceschini
          if not netutils.TcpPing(sip, port, source=my_sip):
1017 9d4bfc96 Iustin Pop
            fail.append("secondary")
1018 9d4bfc96 Iustin Pop
        if fail:
1019 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
1020 25361b9a Iustin Pop
                       " and ".join(fail))
1021 25361b9a Iustin Pop
1022 a3a5f850 Iustin Pop
  if constants.NV_MASTERIP in what:
1023 a3a5f850 Iustin Pop
    # FIXME: add checks on incoming data structures (here and in the
1024 a3a5f850 Iustin Pop
    # rest of the function)
1025 a3a5f850 Iustin Pop
    master_name, master_ip = what[constants.NV_MASTERIP]
1026 a3a5f850 Iustin Pop
    if master_name == my_name:
1027 9769bb78 Manuel Franceschini
      source = constants.IP4_ADDRESS_LOCALHOST
1028 a3a5f850 Iustin Pop
    else:
1029 a3a5f850 Iustin Pop
      source = None
1030 a744b676 Manuel Franceschini
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1031 5ae4945a Iustin Pop
                                                     source=source)
1032 a3a5f850 Iustin Pop
1033 17b0b812 Andrea Spadaccini
  if constants.NV_USERSCRIPTS in what:
1034 17b0b812 Andrea Spadaccini
    result[constants.NV_USERSCRIPTS] = \
1035 17b0b812 Andrea Spadaccini
      [script for script in what[constants.NV_USERSCRIPTS]
1036 10b86782 Michael Hanselmann
       if not utils.IsExecutable(script)]
1037 17b0b812 Andrea Spadaccini
1038 16f41f24 René Nussbaumer
  if constants.NV_OOB_PATHS in what:
1039 16f41f24 René Nussbaumer
    result[constants.NV_OOB_PATHS] = tmp = []
1040 16f41f24 René Nussbaumer
    for path in what[constants.NV_OOB_PATHS]:
1041 16f41f24 René Nussbaumer
      try:
1042 16f41f24 René Nussbaumer
        st = os.stat(path)
1043 16f41f24 René Nussbaumer
      except OSError, err:
1044 16f41f24 René Nussbaumer
        tmp.append("error stating out of band helper: %s" % err)
1045 16f41f24 René Nussbaumer
      else:
1046 16f41f24 René Nussbaumer
        if stat.S_ISREG(st.st_mode):
1047 16f41f24 René Nussbaumer
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1048 16f41f24 René Nussbaumer
            tmp.append(None)
1049 16f41f24 René Nussbaumer
          else:
1050 16f41f24 René Nussbaumer
            tmp.append("out of band helper %s is not executable" % path)
1051 16f41f24 René Nussbaumer
        else:
1052 16f41f24 René Nussbaumer
          tmp.append("out of band helper %s is not a file" % path)
1053 16f41f24 René Nussbaumer
1054 8964ee14 Iustin Pop
  if constants.NV_LVLIST in what and vm_capable:
1055 ed904904 Iustin Pop
    try:
1056 84d7e26b Dmitry Chernyak
      val = GetVolumeList(utils.ListVolumeGroups().keys())
1057 ed904904 Iustin Pop
    except RPCFail, err:
1058 ed904904 Iustin Pop
      val = str(err)
1059 ed904904 Iustin Pop
    result[constants.NV_LVLIST] = val
1060 25361b9a Iustin Pop
1061 5b0dfcef Helga Velroyen
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1062 25361b9a Iustin Pop
1063 8964ee14 Iustin Pop
  if constants.NV_VGLIST in what and vm_capable:
1064 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1065 25361b9a Iustin Pop
1066 8964ee14 Iustin Pop
  if constants.NV_PVLIST in what and vm_capable:
1067 d5a690cb Bernardo Dal Seno
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1068 59726e15 Bernardo Dal Seno
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1069 d5a690cb Bernardo Dal Seno
                                       filter_allocatable=False,
1070 d5a690cb Bernardo Dal Seno
                                       include_lvs=check_exclusive_pvs)
1071 d5a690cb Bernardo Dal Seno
    if check_exclusive_pvs:
1072 d5a690cb Bernardo Dal Seno
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1073 d5a690cb Bernardo Dal Seno
      for pvi in val:
1074 d5a690cb Bernardo Dal Seno
        # Avoid sending useless data on the wire
1075 d5a690cb Bernardo Dal Seno
        pvi.lv_list = []
1076 59726e15 Bernardo Dal Seno
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1077 d091393e Iustin Pop
1078 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
1079 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1080 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
1081 25361b9a Iustin Pop
1082 5b0dfcef Helga Velroyen
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1083 9d4bfc96 Iustin Pop
1084 5bb0a1cb Thomas Thrainer
  if constants.NV_DRBDVERSION in what and vm_capable:
1085 5bb0a1cb Thomas Thrainer
    try:
1086 47e0abee Thomas Thrainer
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1087 5bb0a1cb Thomas Thrainer
    except errors.BlockDeviceError, err:
1088 5bb0a1cb Thomas Thrainer
      logging.warning("Can't get DRBD version", exc_info=True)
1089 5bb0a1cb Thomas Thrainer
      drbd_version = str(err)
1090 5bb0a1cb Thomas Thrainer
    result[constants.NV_DRBDVERSION] = drbd_version
1091 5bb0a1cb Thomas Thrainer
1092 8964ee14 Iustin Pop
  if constants.NV_DRBDLIST in what and vm_capable:
1093 6d2e83d5 Iustin Pop
    try:
1094 47e0abee Thomas Thrainer
      used_minors = drbd.DRBD8.GetUsedDevs()
1095 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
1096 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
1097 f6eaed12 Iustin Pop
      used_minors = str(err)
1098 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
1099 6d2e83d5 Iustin Pop
1100 8964ee14 Iustin Pop
  if constants.NV_DRBDHELPER in what and vm_capable:
1101 7ef40fbe Luca Bigliardi
    status = True
1102 7ef40fbe Luca Bigliardi
    try:
1103 47e0abee Thomas Thrainer
      payload = drbd.DRBD8.GetUsermodeHelper()
1104 7ef40fbe Luca Bigliardi
    except errors.BlockDeviceError, err:
1105 7ef40fbe Luca Bigliardi
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1106 7ef40fbe Luca Bigliardi
      status = False
1107 7ef40fbe Luca Bigliardi
      payload = str(err)
1108 7ef40fbe Luca Bigliardi
    result[constants.NV_DRBDHELPER] = (status, payload)
1109 7ef40fbe Luca Bigliardi
1110 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
1111 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
1112 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1113 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1114 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
1115 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
1116 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
1117 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
1118 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1119 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
1120 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
1121 313b2dd4 Michael Hanselmann
1122 313b2dd4 Michael Hanselmann
  if constants.NV_TIME in what:
1123 313b2dd4 Michael Hanselmann
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1124 313b2dd4 Michael Hanselmann
1125 8964ee14 Iustin Pop
  if constants.NV_OSLIST in what and vm_capable:
1126 b0d85178 Iustin Pop
    result[constants.NV_OSLIST] = DiagnoseOS()
1127 b0d85178 Iustin Pop
1128 20d317d4 Iustin Pop
  if constants.NV_BRIDGES in what and vm_capable:
1129 20d317d4 Iustin Pop
    result[constants.NV_BRIDGES] = [bridge
1130 20d317d4 Iustin Pop
                                    for bridge in what[constants.NV_BRIDGES]
1131 20d317d4 Iustin Pop
                                    if not utils.BridgeExists(bridge)]
1132 23e3c9b7 Michael Hanselmann
1133 72b35807 Michael Hanselmann
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
1134 72b35807 Michael Hanselmann
    result[constants.NV_FILE_STORAGE_PATHS] = \
1135 72b35807 Michael Hanselmann
      bdev.ComputeWrongFileStoragePaths()
1136 72b35807 Michael Hanselmann
1137 c26a6bd2 Iustin Pop
  return result
1138 a8083063 Iustin Pop
1139 a8083063 Iustin Pop
1140 2be7273c Apollon Oikonomopoulos
def GetBlockDevSizes(devices):
1141 2be7273c Apollon Oikonomopoulos
  """Return the size of the given block devices
1142 2be7273c Apollon Oikonomopoulos

1143 2be7273c Apollon Oikonomopoulos
  @type devices: list
1144 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
1145 2be7273c Apollon Oikonomopoulos
  @rtype: dict
1146 2be7273c Apollon Oikonomopoulos
  @return:
1147 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
1148 2be7273c Apollon Oikonomopoulos
    size in MiB.
1149 2be7273c Apollon Oikonomopoulos

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

1152 2be7273c Apollon Oikonomopoulos
  """
1153 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
1154 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
1155 2be7273c Apollon Oikonomopoulos
1156 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
1157 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1158 2be7273c Apollon Oikonomopoulos
      continue
1159 2be7273c Apollon Oikonomopoulos
1160 2be7273c Apollon Oikonomopoulos
    try:
1161 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
1162 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
1163 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1164 2be7273c Apollon Oikonomopoulos
      continue
1165 2be7273c Apollon Oikonomopoulos
1166 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
1167 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1168 2be7273c Apollon Oikonomopoulos
      if result.failed:
1169 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
1170 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
1171 2be7273c Apollon Oikonomopoulos
        continue
1172 2be7273c Apollon Oikonomopoulos
1173 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
1174 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
1175 2be7273c Apollon Oikonomopoulos
  return blockdevs
1176 2be7273c Apollon Oikonomopoulos
1177 2be7273c Apollon Oikonomopoulos
1178 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
1179 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
1180 a8083063 Iustin Pop

1181 84d7e26b Dmitry Chernyak
  @type vg_names: list
1182 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
1183 397693d3 Iustin Pop
      empty for all volume groups
1184 10c2650b Iustin Pop
  @rtype: dict
1185 10c2650b Iustin Pop
  @return:
1186 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
1187 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
1188 10c2650b Iustin Pop

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

1191 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
1192 10c2650b Iustin Pop
      details.
1193 a8083063 Iustin Pop

1194 a8083063 Iustin Pop
  """
1195 cb2037a2 Iustin Pop
  lvs = {}
1196 d0c8c01d Iustin Pop
  sep = "|"
1197 397693d3 Iustin Pop
  if not vg_names:
1198 397693d3 Iustin Pop
    vg_names = []
1199 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1200 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
1201 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1202 a8083063 Iustin Pop
  if result.failed:
1203 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1204 cb2037a2 Iustin Pop
1205 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
1206 df4c2628 Iustin Pop
    line = line.strip()
1207 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
1208 df4c2628 Iustin Pop
    if not match:
1209 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
1210 df4c2628 Iustin Pop
      continue
1211 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
1212 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
1213 d0c8c01d Iustin Pop
    online = attr[5] == "o"
1214 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
1215 33f2a81a Iustin Pop
    if virtual:
1216 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
1217 33f2a81a Iustin Pop
      # don't really hold data
1218 33f2a81a Iustin Pop
      continue
1219 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
1220 cb2037a2 Iustin Pop
1221 cb2037a2 Iustin Pop
  return lvs
1222 a8083063 Iustin Pop
1223 a8083063 Iustin Pop
1224 a8083063 Iustin Pop
def ListVolumeGroups():
1225 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
1226 a8083063 Iustin Pop

1227 10c2650b Iustin Pop
  @rtype: dict
1228 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
1229 10c2650b Iustin Pop
      size of the volume
1230 a8083063 Iustin Pop

1231 a8083063 Iustin Pop
  """
1232 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
1233 a8083063 Iustin Pop
1234 a8083063 Iustin Pop
1235 dcb93971 Michael Hanselmann
def NodeVolumes():
1236 dcb93971 Michael Hanselmann
  """List all volumes on this node.
1237 dcb93971 Michael Hanselmann

1238 10c2650b Iustin Pop
  @rtype: list
1239 10c2650b Iustin Pop
  @return:
1240 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
1241 10c2650b Iustin Pop
      - name: the logical volume name,
1242 10c2650b Iustin Pop
      - size: the size of the logical volume
1243 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
1244 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
1245 10c2650b Iustin Pop

1246 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
1247 10c2650b Iustin Pop
    error.
1248 10c2650b Iustin Pop

1249 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
1250 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
1251 10c2650b Iustin Pop
    multiple times.
1252 10c2650b Iustin Pop

1253 dcb93971 Michael Hanselmann
  """
1254 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1255 dcb93971 Michael Hanselmann
                         "--separator=|",
1256 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
1257 dcb93971 Michael Hanselmann
  if result.failed:
1258 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
1259 10bfe6cb Iustin Pop
          result.output)
1260 dcb93971 Michael Hanselmann
1261 dcb93971 Michael Hanselmann
  def parse_dev(dev):
1262 d0c8c01d Iustin Pop
    return dev.split("(")[0]
1263 89e5ab02 Iustin Pop
1264 89e5ab02 Iustin Pop
  def handle_dev(dev):
1265 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
1266 dcb93971 Michael Hanselmann
1267 dcb93971 Michael Hanselmann
  def map_line(line):
1268 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
1269 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
1270 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1271 89e5ab02 Iustin Pop
1272 89e5ab02 Iustin Pop
  all_devs = []
1273 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
1274 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
1275 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
1276 89e5ab02 Iustin Pop
    else:
1277 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
1278 89e5ab02 Iustin Pop
  return all_devs
1279 dcb93971 Michael Hanselmann
1280 dcb93971 Michael Hanselmann
1281 a8083063 Iustin Pop
def BridgesExist(bridges_list):
1282 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
1283 a8083063 Iustin Pop

1284 b1206984 Iustin Pop
  @rtype: boolean
1285 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
1286 a8083063 Iustin Pop

1287 a8083063 Iustin Pop
  """
1288 35c0c8da Iustin Pop
  missing = []
1289 a8083063 Iustin Pop
  for bridge in bridges_list:
1290 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
1291 35c0c8da Iustin Pop
      missing.append(bridge)
1292 a8083063 Iustin Pop
1293 35c0c8da Iustin Pop
  if missing:
1294 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1295 35c0c8da Iustin Pop
1296 a8083063 Iustin Pop
1297 2bff1928 Helga Velroyen
def GetInstanceListForHypervisor(hname, hvparams=None,
1298 2bff1928 Helga Velroyen
                                 get_hv_fn=hypervisor.GetHypervisor):
1299 2bff1928 Helga Velroyen
  """Provides a list of instances of the given hypervisor.
1300 2bff1928 Helga Velroyen

1301 2bff1928 Helga Velroyen
  @type hname: string
1302 2bff1928 Helga Velroyen
  @param hname: name of the hypervisor
1303 2bff1928 Helga Velroyen
  @type hvparams: dict of strings
1304 2bff1928 Helga Velroyen
  @param hvparams: hypervisor parameters for the given hypervisor
1305 2bff1928 Helga Velroyen
  @type get_hv_fn: function
1306 2bff1928 Helga Velroyen
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1307 2bff1928 Helga Velroyen
    name; optional parameter to increase testability
1308 2bff1928 Helga Velroyen

1309 2bff1928 Helga Velroyen
  @rtype: list
1310 2bff1928 Helga Velroyen
  @return: a list of all running instances on the current node
1311 2bff1928 Helga Velroyen
    - instance1.example.com
1312 2bff1928 Helga Velroyen
    - instance2.example.com
1313 2bff1928 Helga Velroyen

1314 2bff1928 Helga Velroyen
  """
1315 2bff1928 Helga Velroyen
  results = []
1316 2bff1928 Helga Velroyen
  try:
1317 2bff1928 Helga Velroyen
    hv = get_hv_fn(hname)
1318 5b0dfcef Helga Velroyen
    names = hv.ListInstances(hvparams=hvparams)
1319 2bff1928 Helga Velroyen
    results.extend(names)
1320 2bff1928 Helga Velroyen
  except errors.HypervisorError, err:
1321 2bff1928 Helga Velroyen
    _Fail("Error enumerating instances (hypervisor %s): %s",
1322 2bff1928 Helga Velroyen
          hname, err, exc=True)
1323 2bff1928 Helga Velroyen
  return results
1324 2bff1928 Helga Velroyen
1325 2bff1928 Helga Velroyen
1326 fac83f8a Helga Velroyen
def GetInstanceList(hypervisor_list, all_hvparams=None,
1327 fac83f8a Helga Velroyen
                    get_hv_fn=hypervisor.GetHypervisor):
1328 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
1329 a8083063 Iustin Pop

1330 e69d05fd Iustin Pop
  @type hypervisor_list: list
1331 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
1332 fac83f8a Helga Velroyen
  @type all_hvparams: dict of dict of strings
1333 fac83f8a Helga Velroyen
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1334 fac83f8a Helga Velroyen
    cluster-wide hypervisor parameters
1335 fac83f8a Helga Velroyen
  @type get_hv_fn: function
1336 fac83f8a Helga Velroyen
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1337 fac83f8a Helga Velroyen
    name; optional parameter to increase testability
1338 e69d05fd Iustin Pop

1339 e69d05fd Iustin Pop
  @rtype: list
1340 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
1341 10c2650b Iustin Pop
    - instance1.example.com
1342 10c2650b Iustin Pop
    - instance2.example.com
1343 a8083063 Iustin Pop

1344 098c0958 Michael Hanselmann
  """
1345 e69d05fd Iustin Pop
  results = []
1346 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1347 5b0dfcef Helga Velroyen
    hvparams = all_hvparams[hname]
1348 5b0dfcef Helga Velroyen
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1349 2bff1928 Helga Velroyen
                                                get_hv_fn=get_hv_fn))
1350 e69d05fd Iustin Pop
  return results
1351 a8083063 Iustin Pop
1352 a8083063 Iustin Pop
1353 0bbec3af Helga Velroyen
def GetInstanceInfo(instance, hname, hvparams=None):
1354 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
1355 a8083063 Iustin Pop

1356 e69d05fd Iustin Pop
  @type instance: string
1357 e69d05fd Iustin Pop
  @param instance: the instance name
1358 e69d05fd Iustin Pop
  @type hname: string
1359 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1360 0bbec3af Helga Velroyen
  @type hvparams: dict of strings
1361 0bbec3af Helga Velroyen
  @param hvparams: the instance's hvparams
1362 a8083063 Iustin Pop

1363 e69d05fd Iustin Pop
  @rtype: dict
1364 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1365 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1366 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1367 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1368 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1369 a8083063 Iustin Pop

1370 098c0958 Michael Hanselmann
  """
1371 a8083063 Iustin Pop
  output = {}
1372 a8083063 Iustin Pop
1373 0bbec3af Helga Velroyen
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1374 0bbec3af Helga Velroyen
                                                          hvparams=hvparams)
1375 a8083063 Iustin Pop
  if iinfo is not None:
1376 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1377 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1378 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1379 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1380 a8083063 Iustin Pop
1381 c26a6bd2 Iustin Pop
  return output
1382 a8083063 Iustin Pop
1383 a8083063 Iustin Pop
1384 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1385 3361ab37 Helga Velroyen
  """Computes whether an instance can be migrated.
1386 56e7640c Iustin Pop

1387 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1388 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1389 56e7640c Iustin Pop

1390 56e7640c Iustin Pop
  @rtype: tuple
1391 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1392 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1393 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1394 56e7640c Iustin Pop

1395 56e7640c Iustin Pop
  """
1396 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1397 afdc3985 Iustin Pop
  iname = instance.name
1398 3361ab37 Helga Velroyen
  if iname not in hyper.ListInstances(instance.hvparams):
1399 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1400 56e7640c Iustin Pop
1401 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1402 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1403 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1404 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1405 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1406 56e7640c Iustin Pop
1407 56e7640c Iustin Pop
1408 0200a1af Helga Velroyen
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1409 a8083063 Iustin Pop
  """Gather data about all instances.
1410 a8083063 Iustin Pop

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

1415 e69d05fd Iustin Pop
  @type hypervisor_list: list
1416 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1417 0200a1af Helga Velroyen
  @type all_hvparams: dict of dict of strings
1418 0200a1af Helga Velroyen
  @param all_hvparams: mapping of hypervisor names to hvparams
1419 e69d05fd Iustin Pop

1420 955db481 Guido Trotter
  @rtype: dict
1421 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1422 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1423 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1424 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1425 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1426 a8083063 Iustin Pop

1427 098c0958 Michael Hanselmann
  """
1428 a8083063 Iustin Pop
  output = {}
1429 a8083063 Iustin Pop
1430 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1431 0200a1af Helga Velroyen
    hvparams = all_hvparams[hname]
1432 0200a1af Helga Velroyen
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1433 e69d05fd Iustin Pop
    if iinfo:
1434 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1435 f23b5ae8 Iustin Pop
        value = {
1436 d0c8c01d Iustin Pop
          "memory": memory,
1437 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1438 d0c8c01d Iustin Pop
          "state": state,
1439 d0c8c01d Iustin Pop
          "time": times,
1440 e69d05fd Iustin Pop
          }
1441 b33b6f55 Iustin Pop
        if name in output:
1442 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1443 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1444 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1445 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1446 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1447 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1448 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1449 f23b5ae8 Iustin Pop
        output[name] = value
1450 a8083063 Iustin Pop
1451 c26a6bd2 Iustin Pop
  return output
1452 a8083063 Iustin Pop
1453 a8083063 Iustin Pop
1454 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1455 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1456 81a3406c Iustin Pop

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

1460 81a3406c Iustin Pop
  @type kind: string
1461 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1462 81a3406c Iustin Pop
  @type os_name: string
1463 81a3406c Iustin Pop
  @param os_name: the os name
1464 81a3406c Iustin Pop
  @type instance: string
1465 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1466 6aa7a354 Iustin Pop
  @type component: string or None
1467 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1468 6aa7a354 Iustin Pop
      transferred
1469 81a3406c Iustin Pop

1470 81a3406c Iustin Pop
  """
1471 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1472 6aa7a354 Iustin Pop
  if component:
1473 6aa7a354 Iustin Pop
    assert "/" not in component
1474 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1475 6aa7a354 Iustin Pop
  else:
1476 6aa7a354 Iustin Pop
    c_msg = ""
1477 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1478 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1479 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1480 81a3406c Iustin Pop
1481 81a3406c Iustin Pop
1482 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1483 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1484 a8083063 Iustin Pop

1485 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1486 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1487 e557bae9 Guido Trotter
  @type reinstall: boolean
1488 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1489 4a0e011f Iustin Pop
  @type debug: integer
1490 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1491 c26a6bd2 Iustin Pop
  @rtype: None
1492 a8083063 Iustin Pop

1493 a8083063 Iustin Pop
  """
1494 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1495 255dcebd Iustin Pop
1496 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1497 e557bae9 Guido Trotter
  if reinstall:
1498 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1499 a8083063 Iustin Pop
1500 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1501 decd5f45 Iustin Pop
1502 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1503 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1504 decd5f45 Iustin Pop
  if result.failed:
1505 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1506 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1507 18682bca Iustin Pop
                  result.output)
1508 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1509 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1510 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1511 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1512 decd5f45 Iustin Pop
1513 decd5f45 Iustin Pop
1514 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1515 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1516 decd5f45 Iustin Pop

1517 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1518 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1519 d15a9ad3 Guido Trotter
  @type old_name: string
1520 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1521 4a0e011f Iustin Pop
  @type debug: integer
1522 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1523 10c2650b Iustin Pop
  @rtype: boolean
1524 10c2650b Iustin Pop
  @return: the success of the operation
1525 decd5f45 Iustin Pop

1526 decd5f45 Iustin Pop
  """
1527 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1528 decd5f45 Iustin Pop
1529 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1530 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1531 decd5f45 Iustin Pop
1532 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1533 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1534 a8083063 Iustin Pop
1535 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1536 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1537 a8083063 Iustin Pop
1538 a8083063 Iustin Pop
  if result.failed:
1539 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1540 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1541 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1542 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1543 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1544 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1545 a8083063 Iustin Pop
1546 a8083063 Iustin Pop
1547 3b721842 Michael Hanselmann
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1548 3b721842 Michael Hanselmann
  """Returns symlink path for block device.
1549 3b721842 Michael Hanselmann

1550 3b721842 Michael Hanselmann
  """
1551 3b721842 Michael Hanselmann
  if _dir is None:
1552 3b721842 Michael Hanselmann
    _dir = pathutils.DISK_LINKS_DIR
1553 3b721842 Michael Hanselmann
1554 3b721842 Michael Hanselmann
  return utils.PathJoin(_dir,
1555 3b721842 Michael Hanselmann
                        ("%s%s%s" %
1556 3b721842 Michael Hanselmann
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1557 5282084b Iustin Pop
1558 5282084b Iustin Pop
1559 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1560 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1561 9332fd8a Iustin Pop

1562 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1563 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1564 9332fd8a Iustin Pop

1565 9332fd8a Iustin Pop

1566 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1567 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1568 5282084b Iustin Pop
  @param idx: the disk index
1569 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1570 9332fd8a Iustin Pop

1571 9332fd8a Iustin Pop
  """
1572 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1573 9332fd8a Iustin Pop
  try:
1574 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1575 5282084b Iustin Pop
  except OSError, err:
1576 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1577 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1578 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1579 9332fd8a Iustin Pop
        os.remove(link_name)
1580 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1581 9332fd8a Iustin Pop
    else:
1582 9332fd8a Iustin Pop
      raise
1583 9332fd8a Iustin Pop
1584 9332fd8a Iustin Pop
  return link_name
1585 9332fd8a Iustin Pop
1586 9332fd8a Iustin Pop
1587 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1588 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1589 3c9c571d Iustin Pop

1590 3c9c571d Iustin Pop
  """
1591 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1592 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1593 5282084b Iustin Pop
    if os.path.islink(link_name):
1594 3c9c571d Iustin Pop
      try:
1595 03dfa658 Iustin Pop
        os.remove(link_name)
1596 03dfa658 Iustin Pop
      except OSError:
1597 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1598 3c9c571d Iustin Pop
1599 3c9c571d Iustin Pop
1600 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1601 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1602 a8083063 Iustin Pop

1603 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1604 a8083063 Iustin Pop
  devices must be already assembled.
1605 a8083063 Iustin Pop

1606 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1607 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1608 069cfbf1 Iustin Pop
  @rtype: list
1609 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1610 10c2650b Iustin Pop

1611 a8083063 Iustin Pop
  """
1612 a8083063 Iustin Pop
  block_devices = []
1613 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1614 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1615 a8083063 Iustin Pop
    if device is None:
1616 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1617 a8083063 Iustin Pop
                                    str(disk))
1618 a8083063 Iustin Pop
    device.Open()
1619 9332fd8a Iustin Pop
    try:
1620 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1621 9332fd8a Iustin Pop
    except OSError, e:
1622 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1623 9332fd8a Iustin Pop
                                    e.strerror)
1624 9332fd8a Iustin Pop
1625 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1626 9332fd8a Iustin Pop
1627 a8083063 Iustin Pop
  return block_devices
1628 a8083063 Iustin Pop
1629 a8083063 Iustin Pop
1630 1fa6fcba Michele Tartara
def StartInstance(instance, startup_paused, reason, store_reason=True):
1631 a8083063 Iustin Pop
  """Start an instance.
1632 a8083063 Iustin Pop

1633 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1634 e69d05fd Iustin Pop
  @param instance: the instance object
1635 323f9095 Stephen Shirley
  @type startup_paused: bool
1636 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1637 1fa6fcba Michele Tartara
  @type reason: list of reasons
1638 1fa6fcba Michele Tartara
  @param reason: the reason trail for this startup
1639 1fa6fcba Michele Tartara
  @type store_reason: boolean
1640 1fa6fcba Michele Tartara
  @param store_reason: whether to store the shutdown reason trail on file
1641 c26a6bd2 Iustin Pop
  @rtype: None
1642 a8083063 Iustin Pop

1643 098c0958 Michael Hanselmann
  """
1644 3361ab37 Helga Velroyen
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1645 3361ab37 Helga Velroyen
                                                   instance.hvparams)
1646 a8083063 Iustin Pop
1647 a8083063 Iustin Pop
  if instance.name in running_instances:
1648 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1649 c26a6bd2 Iustin Pop
    return
1650 a8083063 Iustin Pop
1651 a8083063 Iustin Pop
  try:
1652 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1653 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1654 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1655 1fa6fcba Michele Tartara
    if store_reason:
1656 1fa6fcba Michele Tartara
      _StoreInstReasonTrail(instance.name, reason)
1657 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1658 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1659 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1660 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1661 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1662 a8083063 Iustin Pop
1663 a8083063 Iustin Pop
1664 1f350e0f Michele Tartara
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1665 a8083063 Iustin Pop
  """Shut an instance down.
1666 a8083063 Iustin Pop

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

1669 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1670 e69d05fd Iustin Pop
  @param instance: the instance object
1671 6263189c Guido Trotter
  @type timeout: integer
1672 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1673 1f350e0f Michele Tartara
  @type reason: list of reasons
1674 1f350e0f Michele Tartara
  @param reason: the reason trail for this shutdown
1675 1f350e0f Michele Tartara
  @type store_reason: boolean
1676 1f350e0f Michele Tartara
  @param store_reason: whether to store the shutdown reason trail on file
1677 c26a6bd2 Iustin Pop
  @rtype: None
1678 a8083063 Iustin Pop

1679 098c0958 Michael Hanselmann
  """
1680 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1681 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1682 c26a6bd2 Iustin Pop
  iname = instance.name
1683 a8083063 Iustin Pop
1684 3361ab37 Helga Velroyen
  if instance.name not in hyper.ListInstances(instance.hvparams):
1685 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1686 c26a6bd2 Iustin Pop
    return
1687 a8083063 Iustin Pop
1688 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1689 3c0cdc83 Michael Hanselmann
    def __init__(self):
1690 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1691 a8083063 Iustin Pop
1692 3c0cdc83 Michael Hanselmann
    def __call__(self):
1693 3361ab37 Helga Velroyen
      if iname not in hyper.ListInstances(instance.hvparams):
1694 3c0cdc83 Michael Hanselmann
        return
1695 3c0cdc83 Michael Hanselmann
1696 3c0cdc83 Michael Hanselmann
      try:
1697 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1698 1f350e0f Michele Tartara
        if store_reason:
1699 1f350e0f Michele Tartara
          _StoreInstReasonTrail(instance.name, reason)
1700 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1701 3361ab37 Helga Velroyen
        if iname not in hyper.ListInstances(instance.hvparams):
1702 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1703 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1704 3c0cdc83 Michael Hanselmann
          return
1705 3c0cdc83 Michael Hanselmann
1706 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1707 3c0cdc83 Michael Hanselmann
1708 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1709 3c0cdc83 Michael Hanselmann
1710 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1711 3c0cdc83 Michael Hanselmann
1712 3c0cdc83 Michael Hanselmann
  try:
1713 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1714 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1715 a8083063 Iustin Pop
    # the shutdown did not succeed
1716 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1717 a8083063 Iustin Pop
1718 a8083063 Iustin Pop
    try:
1719 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1720 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1721 3361ab37 Helga Velroyen
      if iname in hyper.ListInstances(instance.hvparams):
1722 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1723 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1724 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1725 a8083063 Iustin Pop
1726 a8083063 Iustin Pop
    time.sleep(1)
1727 3c0cdc83 Michael Hanselmann
1728 3361ab37 Helga Velroyen
    if iname in hyper.ListInstances(instance.hvparams):
1729 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1730 3c9c571d Iustin Pop
1731 f28ec899 Guido Trotter
  try:
1732 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1733 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1734 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1735 f28ec899 Guido Trotter
1736 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1737 a8083063 Iustin Pop
1738 a8083063 Iustin Pop
1739 55cec070 Michele Tartara
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1740 007a2f3e Alexander Schreiber
  """Reboot an instance.
1741 007a2f3e Alexander Schreiber

1742 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1743 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1744 10c2650b Iustin Pop
  @type reboot_type: str
1745 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1746 10c2650b Iustin Pop
    constants:
1747 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1748 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1749 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1750 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1751 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1752 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1753 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1754 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1755 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1756 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1757 55cec070 Michele Tartara
  @type reason: list of reasons
1758 55cec070 Michele Tartara
  @param reason: the reason trail for this reboot
1759 c26a6bd2 Iustin Pop
  @rtype: None
1760 007a2f3e Alexander Schreiber

1761 007a2f3e Alexander Schreiber
  """
1762 3361ab37 Helga Velroyen
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1763 3361ab37 Helga Velroyen
                                                   instance.hvparams)
1764 007a2f3e Alexander Schreiber
1765 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1766 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1767 007a2f3e Alexander Schreiber
1768 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1769 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1770 007a2f3e Alexander Schreiber
    try:
1771 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1772 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1773 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1774 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1775 007a2f3e Alexander Schreiber
    try:
1776 1f350e0f Michele Tartara
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1777 1fa6fcba Michele Tartara
      result = StartInstance(instance, False, reason, store_reason=False)
1778 55cec070 Michele Tartara
      _StoreInstReasonTrail(instance.name, reason)
1779 4a90bd4f Michele Tartara
      return result
1780 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1781 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1782 007a2f3e Alexander Schreiber
  else:
1783 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1784 007a2f3e Alexander Schreiber
1785 007a2f3e Alexander Schreiber
1786 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1787 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1788 ebe466d8 Guido Trotter

1789 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1790 ebe466d8 Guido Trotter
  @param instance: the instance object
1791 ebe466d8 Guido Trotter
  @type memory: int
1792 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1793 ebe466d8 Guido Trotter
  @rtype: None
1794 ebe466d8 Guido Trotter

1795 ebe466d8 Guido Trotter
  """
1796 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1797 3361ab37 Helga Velroyen
  running = hyper.ListInstances(instance.hvparams)
1798 ebe466d8 Guido Trotter
  if instance.name not in running:
1799 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1800 ebe466d8 Guido Trotter
    return
1801 ebe466d8 Guido Trotter
  try:
1802 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1803 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1804 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1805 ebe466d8 Guido Trotter
1806 ebe466d8 Guido Trotter
1807 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1808 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1809 6906a9d8 Guido Trotter

1810 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1811 6906a9d8 Guido Trotter
  @param instance: the instance definition
1812 6906a9d8 Guido Trotter

1813 6906a9d8 Guido Trotter
  """
1814 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1815 cd42d0ad Guido Trotter
  try:
1816 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1817 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1818 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1819 c26a6bd2 Iustin Pop
  return info
1820 6906a9d8 Guido Trotter
1821 6906a9d8 Guido Trotter
1822 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1823 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1824 6906a9d8 Guido Trotter

1825 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1826 6906a9d8 Guido Trotter
  @param instance: the instance definition
1827 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1828 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1829 6906a9d8 Guido Trotter
  @type target: string
1830 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1831 6906a9d8 Guido Trotter

1832 6906a9d8 Guido Trotter
  """
1833 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1834 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1835 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1836 77fcff4a Apollon Oikonomopoulos
    # in any way
1837 77fcff4a Apollon Oikonomopoulos
    try:
1838 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1839 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1840 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1841 77fcff4a Apollon Oikonomopoulos
1842 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1843 cd42d0ad Guido Trotter
  try:
1844 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1845 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1846 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1847 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1848 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1849 6906a9d8 Guido Trotter
1850 6906a9d8 Guido Trotter
1851 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1852 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1853 6906a9d8 Guido Trotter

1854 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1855 6906a9d8 Guido Trotter
  @param instance: the instance definition
1856 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1857 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1858 6906a9d8 Guido Trotter
  @type success: boolean
1859 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1860 6906a9d8 Guido Trotter

1861 6906a9d8 Guido Trotter
  """
1862 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1863 cd42d0ad Guido Trotter
  try:
1864 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1865 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1866 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1867 6906a9d8 Guido Trotter
1868 6906a9d8 Guido Trotter
1869 bc0a2284 Helga Velroyen
def MigrateInstance(cluster_name, instance, target, live):
1870 2a10865c Iustin Pop
  """Migrates an instance to another node.
1871 2a10865c Iustin Pop

1872 bc0a2284 Helga Velroyen
  @type cluster_name: string
1873 bc0a2284 Helga Velroyen
  @param cluster_name: name of the cluster
1874 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1875 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1876 9f0e6b37 Iustin Pop
  @type target: string
1877 9f0e6b37 Iustin Pop
  @param target: the target node name
1878 9f0e6b37 Iustin Pop
  @type live: boolean
1879 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1880 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1881 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1882 9f0e6b37 Iustin Pop

1883 2a10865c Iustin Pop
  """
1884 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1885 2a10865c Iustin Pop
1886 2a10865c Iustin Pop
  try:
1887 bc0a2284 Helga Velroyen
    hyper.MigrateInstance(cluster_name, instance, target, live)
1888 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1889 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1890 2a10865c Iustin Pop
1891 2a10865c Iustin Pop
1892 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1893 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1894 6a1434d7 Andrea Spadaccini

1895 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1896 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1897 6a1434d7 Andrea Spadaccini
  @type success: bool
1898 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1899 6a1434d7 Andrea Spadaccini
  @type live: bool
1900 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1901 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1902 6a1434d7 Andrea Spadaccini

1903 6a1434d7 Andrea Spadaccini
  """
1904 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1905 6a1434d7 Andrea Spadaccini
1906 6a1434d7 Andrea Spadaccini
  try:
1907 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1908 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1909 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1910 6a1434d7 Andrea Spadaccini
          exc=True)
1911 6a1434d7 Andrea Spadaccini
1912 6a1434d7 Andrea Spadaccini
1913 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1914 6a1434d7 Andrea Spadaccini
  """Get the migration status
1915 6a1434d7 Andrea Spadaccini

1916 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1917 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1918 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1919 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1920 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1921 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1922 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1923 6a1434d7 Andrea Spadaccini

1924 6a1434d7 Andrea Spadaccini
  """
1925 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1926 6a1434d7 Andrea Spadaccini
  try:
1927 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1928 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1929 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1930 6a1434d7 Andrea Spadaccini
1931 6a1434d7 Andrea Spadaccini
1932 ee1478e5 Bernardo Dal Seno
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1933 a8083063 Iustin Pop
  """Creates a block device for an instance.
1934 a8083063 Iustin Pop

1935 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1936 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1937 b1206984 Iustin Pop
  @type size: int
1938 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1939 b1206984 Iustin Pop
  @type owner: str
1940 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1941 b1206984 Iustin Pop
      used for device cache data
1942 b1206984 Iustin Pop
  @type on_primary: boolean
1943 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1944 b1206984 Iustin Pop
  @type info: string
1945 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1946 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1947 ee1478e5 Bernardo Dal Seno
  @type excl_stor: boolean
1948 ee1478e5 Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
1949 b1206984 Iustin Pop

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

1954 a8083063 Iustin Pop
  """
1955 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
1956 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
1957 a8083063 Iustin Pop
  clist = []
1958 a8083063 Iustin Pop
  if disk.children:
1959 a8083063 Iustin Pop
    for child in disk.children:
1960 1063abd1 Iustin Pop
      try:
1961 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1962 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1963 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1964 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1965 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1966 a8083063 Iustin Pop
        # be assembled
1967 1063abd1 Iustin Pop
        try:
1968 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
1969 1063abd1 Iustin Pop
          crdev.Open()
1970 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1971 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1972 a8083063 Iustin Pop
      clist.append(crdev)
1973 a8083063 Iustin Pop
1974 dab69e97 Iustin Pop
  try:
1975 ee1478e5 Bernardo Dal Seno
    device = bdev.Create(disk, clist, excl_stor)
1976 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1977 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1978 6c626518 Iustin Pop
1979 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1980 1063abd1 Iustin Pop
    try:
1981 1063abd1 Iustin Pop
      device.Assemble()
1982 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1983 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1984 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1985 1063abd1 Iustin Pop
      try:
1986 1063abd1 Iustin Pop
        device.Open(force=True)
1987 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1988 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1989 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1990 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1991 a0c3fea1 Michael Hanselmann
1992 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1993 a0c3fea1 Michael Hanselmann
1994 c26a6bd2 Iustin Pop
  return device.unique_id
1995 a8083063 Iustin Pop
1996 a8083063 Iustin Pop
1997 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1998 69dd363f René Nussbaumer
  """This function actually wipes the device.
1999 69dd363f René Nussbaumer

2000 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
2001 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
2002 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
2003 69dd363f René Nussbaumer

2004 69dd363f René Nussbaumer
  """
2005 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
2006 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
2007 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
2008 0188611b Michael Hanselmann
  block_size = 1024 * 1024
2009 0188611b Michael Hanselmann
2010 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2011 0188611b Michael Hanselmann
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2012 da63bb4e René Nussbaumer
         "count=%d" % size]
2013 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
2014 69dd363f René Nussbaumer
2015 69dd363f René Nussbaumer
  if result.failed:
2016 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2017 69dd363f René Nussbaumer
          result.fail_reason, result.output)
2018 69dd363f René Nussbaumer
2019 69dd363f René Nussbaumer
2020 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
2021 69dd363f René Nussbaumer
  """Wipes a block device.
2022 69dd363f René Nussbaumer

2023 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
2024 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
2025 da63bb4e René Nussbaumer
  @type offset: int
2026 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
2027 da63bb4e René Nussbaumer
  @type size: int
2028 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
2029 69dd363f René Nussbaumer

2030 69dd363f René Nussbaumer
  """
2031 69dd363f René Nussbaumer
  try:
2032 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
2033 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
2034 da63bb4e René Nussbaumer
    rdev = None
2035 da63bb4e René Nussbaumer
2036 da63bb4e René Nussbaumer
  if not rdev:
2037 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2038 da63bb4e René Nussbaumer
2039 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
2040 0188611b Michael Hanselmann
  if offset < 0:
2041 0188611b Michael Hanselmann
    _Fail("Negative offset")
2042 0188611b Michael Hanselmann
  if size < 0:
2043 0188611b Michael Hanselmann
    _Fail("Negative size")
2044 da63bb4e René Nussbaumer
  if offset > rdev.size:
2045 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
2046 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
2047 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
2048 69dd363f René Nussbaumer
2049 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
2050 69dd363f René Nussbaumer
2051 69dd363f René Nussbaumer
2052 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
2053 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
2054 5119c79e René Nussbaumer

2055 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
2056 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
2057 5119c79e René Nussbaumer
  @type pause: bool
2058 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
2059 5119c79e René Nussbaumer

2060 5119c79e René Nussbaumer
  """
2061 5119c79e René Nussbaumer
  success = []
2062 5119c79e René Nussbaumer
  for disk in disks:
2063 5119c79e René Nussbaumer
    try:
2064 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
2065 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
2066 5119c79e René Nussbaumer
      rdev = None
2067 5119c79e René Nussbaumer
2068 5119c79e René Nussbaumer
    if not rdev:
2069 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
2070 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
2071 5119c79e René Nussbaumer
      continue
2072 5119c79e René Nussbaumer
2073 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
2074 5119c79e René Nussbaumer
2075 5119c79e René Nussbaumer
    if result:
2076 5119c79e René Nussbaumer
      success.append((result, None))
2077 5119c79e René Nussbaumer
    else:
2078 5119c79e René Nussbaumer
      if pause:
2079 5119c79e René Nussbaumer
        msg = "Pause"
2080 5119c79e René Nussbaumer
      else:
2081 5119c79e René Nussbaumer
        msg = "Resume"
2082 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2083 5119c79e René Nussbaumer
2084 5119c79e René Nussbaumer
  return success
2085 5119c79e René Nussbaumer
2086 5119c79e René Nussbaumer
2087 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
2088 a8083063 Iustin Pop
  """Remove a block device.
2089 a8083063 Iustin Pop

2090 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
2091 10c2650b Iustin Pop

2092 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
2093 10c2650b Iustin Pop
  @param disk: the disk object we should remove
2094 10c2650b Iustin Pop
  @rtype: boolean
2095 10c2650b Iustin Pop
  @return: the success of the operation
2096 a8083063 Iustin Pop

2097 a8083063 Iustin Pop
  """
2098 e1bc0878 Iustin Pop
  msgs = []
2099 a8083063 Iustin Pop
  try:
2100 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
2101 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
2102 a8083063 Iustin Pop
    # probably can't attach
2103 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
2104 a8083063 Iustin Pop
    rdev = None
2105 a8083063 Iustin Pop
  if rdev is not None:
2106 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
2107 e1bc0878 Iustin Pop
    try:
2108 0c6c04ec Iustin Pop
      rdev.Remove()
2109 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
2110 e1bc0878 Iustin Pop
      msgs.append(str(err))
2111 c26a6bd2 Iustin Pop
    if not msgs:
2112 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
2113 e1bc0878 Iustin Pop
2114 a8083063 Iustin Pop
  if disk.children:
2115 a8083063 Iustin Pop
    for child in disk.children:
2116 c26a6bd2 Iustin Pop
      try:
2117 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
2118 c26a6bd2 Iustin Pop
      except RPCFail, err:
2119 c26a6bd2 Iustin Pop
        msgs.append(str(err))
2120 e1bc0878 Iustin Pop
2121 c26a6bd2 Iustin Pop
  if msgs:
2122 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2123 afdc3985 Iustin Pop
2124 a8083063 Iustin Pop
2125 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
2126 a8083063 Iustin Pop
  """Activate a block device for an instance.
2127 a8083063 Iustin Pop

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

2130 10c2650b Iustin Pop
  @note: this function is called recursively.
2131 a8083063 Iustin Pop

2132 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2133 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
2134 10c2650b Iustin Pop
  @type owner: str
2135 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
2136 10c2650b Iustin Pop
  @type as_primary: boolean
2137 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
2138 10c2650b Iustin Pop
      read/write
2139 a8083063 Iustin Pop

2140 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
2141 10c2650b Iustin Pop
      was assembled)
2142 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
2143 10c2650b Iustin Pop
      during the activation of the children or the device
2144 10c2650b Iustin Pop
      itself
2145 a8083063 Iustin Pop

2146 a8083063 Iustin Pop
  """
2147 a8083063 Iustin Pop
  children = []
2148 a8083063 Iustin Pop
  if disk.children:
2149 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
2150 fc1dc9d7 Iustin Pop
    if mcn == -1:
2151 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
2152 fc1dc9d7 Iustin Pop
    else:
2153 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
2154 a8083063 Iustin Pop
    for chld_disk in disk.children:
2155 fc1dc9d7 Iustin Pop
      try:
2156 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2157 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
2158 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
2159 fc1dc9d7 Iustin Pop
          raise
2160 fc1dc9d7 Iustin Pop
        cdev = None
2161 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
2162 1063abd1 Iustin Pop
                      str(err))
2163 fc1dc9d7 Iustin Pop
      children.append(cdev)
2164 a8083063 Iustin Pop
2165 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
2166 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
2167 a8083063 Iustin Pop
    result = r_dev
2168 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
2169 a8083063 Iustin Pop
      r_dev.Open()
2170 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2171 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
2172 3f78eef2 Iustin Pop
2173 a8083063 Iustin Pop
  else:
2174 a8083063 Iustin Pop
    result = True
2175 a8083063 Iustin Pop
  return result
2176 a8083063 Iustin Pop
2177 a8083063 Iustin Pop
2178 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
2179 a8083063 Iustin Pop
  """Activate a block device for an instance.
2180 a8083063 Iustin Pop

2181 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
2182 a8083063 Iustin Pop

2183 b1206984 Iustin Pop
  @rtype: str or boolean
2184 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
2185 b1206984 Iustin Pop
      C{True} for secondary nodes
2186 a8083063 Iustin Pop

2187 a8083063 Iustin Pop
  """
2188 53c14ef1 Iustin Pop
  try:
2189 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2190 89ff748d Thomas Thrainer
    if isinstance(result, BlockDev):
2191 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
2192 53c14ef1 Iustin Pop
      result = result.dev_path
2193 c417e115 Iustin Pop
      if as_primary:
2194 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
2195 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
2196 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
2197 c417e115 Iustin Pop
  except OSError, err:
2198 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
2199 afdc3985 Iustin Pop
2200 c26a6bd2 Iustin Pop
  return result
2201 a8083063 Iustin Pop
2202 a8083063 Iustin Pop
2203 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
2204 a8083063 Iustin Pop
  """Shut down a block device.
2205 a8083063 Iustin Pop

2206 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
2207 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
2208 c41eea6e Iustin Pop
  shutdown.
2209 a8083063 Iustin Pop

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

2214 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2215 10c2650b Iustin Pop
  @param disk: the description of the disk we should
2216 10c2650b Iustin Pop
      shutdown
2217 c26a6bd2 Iustin Pop
  @rtype: None
2218 10c2650b Iustin Pop

2219 a8083063 Iustin Pop
  """
2220 cacfd1fd Iustin Pop
  msgs = []
2221 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2222 a8083063 Iustin Pop
  if r_dev is not None:
2223 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
2224 cacfd1fd Iustin Pop
    try:
2225 746f7476 Iustin Pop
      r_dev.Shutdown()
2226 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
2227 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
2228 cacfd1fd Iustin Pop
      msgs.append(str(err))
2229 746f7476 Iustin Pop
2230 a8083063 Iustin Pop
  if disk.children:
2231 a8083063 Iustin Pop
    for child in disk.children:
2232 c26a6bd2 Iustin Pop
      try:
2233 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
2234 c26a6bd2 Iustin Pop
      except RPCFail, err:
2235 c26a6bd2 Iustin Pop
        msgs.append(str(err))
2236 746f7476 Iustin Pop
2237 c26a6bd2 Iustin Pop
  if msgs:
2238 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2239 a8083063 Iustin Pop
2240 a8083063 Iustin Pop
2241 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
2242 153d9724 Iustin Pop
  """Extend a mirrored block device.
2243 a8083063 Iustin Pop

2244 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
2245 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
2246 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
2247 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
2248 c26a6bd2 Iustin Pop
  @rtype: None
2249 10c2650b Iustin Pop

2250 a8083063 Iustin Pop
  """
2251 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
2252 153d9724 Iustin Pop
  if parent_bdev is None:
2253 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2254 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2255 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
2256 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2257 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
2258 a8083063 Iustin Pop
2259 a8083063 Iustin Pop
2260 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2261 153d9724 Iustin Pop
  """Shrink a mirrored block device.
2262 a8083063 Iustin Pop

2263 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
2264 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
2265 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
2266 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
2267 c26a6bd2 Iustin Pop
  @rtype: None
2268 10c2650b Iustin Pop

2269 a8083063 Iustin Pop
  """
2270 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
2271 153d9724 Iustin Pop
  if parent_bdev is None:
2272 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2273 e739bd57 Iustin Pop
  devs = []
2274 e739bd57 Iustin Pop
  for disk in new_cdevs:
2275 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
2276 e739bd57 Iustin Pop
    if rpath is None:
2277 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
2278 e739bd57 Iustin Pop
      if bd is None:
2279 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
2280 e739bd57 Iustin Pop
      else:
2281 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
2282 e739bd57 Iustin Pop
    else:
2283 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
2284 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2285 e739bd57 Iustin Pop
      devs.append(rpath)
2286 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
2287 a8083063 Iustin Pop
2288 a8083063 Iustin Pop
2289 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
2290 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
2291 a8083063 Iustin Pop

2292 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2293 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
2294 10c2650b Iustin Pop
  @rtype: disk
2295 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
2296 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
2297 10c2650b Iustin Pop
      found
2298 a8083063 Iustin Pop

2299 a8083063 Iustin Pop
  """
2300 a8083063 Iustin Pop
  stats = []
2301 a8083063 Iustin Pop
  for dsk in disks:
2302 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
2303 a8083063 Iustin Pop
    if rbd is None:
2304 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
2305 96acbc09 Michael Hanselmann
2306 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
2307 96acbc09 Michael Hanselmann
2308 c26a6bd2 Iustin Pop
  return stats
2309 a8083063 Iustin Pop
2310 a8083063 Iustin Pop
2311 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
2312 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
2313 c6a9dffa Michael Hanselmann

2314 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
2315 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
2316 c6a9dffa Michael Hanselmann
  @rtype: disk
2317 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2318 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
2319 c6a9dffa Michael Hanselmann
    otherwise
2320 c6a9dffa Michael Hanselmann

2321 c6a9dffa Michael Hanselmann
  """
2322 c6a9dffa Michael Hanselmann
  result = []
2323 c6a9dffa Michael Hanselmann
  for disk in disks:
2324 c6a9dffa Michael Hanselmann
    try:
2325 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
2326 c6a9dffa Michael Hanselmann
      if rbd is None:
2327 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
2328 c6a9dffa Michael Hanselmann
        continue
2329 c6a9dffa Michael Hanselmann
2330 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
2331 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
2332 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
2333 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
2334 c6a9dffa Michael Hanselmann
    else:
2335 c6a9dffa Michael Hanselmann
      result.append((True, status))
2336 c6a9dffa Michael Hanselmann
2337 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
2338 c6a9dffa Michael Hanselmann
2339 c6a9dffa Michael Hanselmann
  return result
2340 c6a9dffa Michael Hanselmann
2341 c6a9dffa Michael Hanselmann
2342 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
2343 a8083063 Iustin Pop
  """Check if a device is activated.
2344 a8083063 Iustin Pop

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

2347 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2348 10c2650b Iustin Pop
  @param disk: the disk object we need to find
2349 a8083063 Iustin Pop

2350 10c2650b Iustin Pop
  @return: None if the device can't be found,
2351 10c2650b Iustin Pop
      otherwise the device instance
2352 a8083063 Iustin Pop

2353 a8083063 Iustin Pop
  """
2354 a8083063 Iustin Pop
  children = []
2355 a8083063 Iustin Pop
  if disk.children:
2356 a8083063 Iustin Pop
    for chdisk in disk.children:
2357 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
2358 a8083063 Iustin Pop
2359 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
2360 a8083063 Iustin Pop
2361 a8083063 Iustin Pop
2362 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
2363 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
2364 f2e07bb4 Michael Hanselmann

2365 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
2366 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
2367 f2e07bb4 Michael Hanselmann

2368 f2e07bb4 Michael Hanselmann
  """
2369 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
2370 f2e07bb4 Michael Hanselmann
  if real_disk is None:
2371 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
2372 f2e07bb4 Michael Hanselmann
2373 f2e07bb4 Michael Hanselmann
  real_disk.Open()
2374 f2e07bb4 Michael Hanselmann
2375 f2e07bb4 Michael Hanselmann
  return real_disk
2376 f2e07bb4 Michael Hanselmann
2377 f2e07bb4 Michael Hanselmann
2378 821d1bd1 Iustin Pop
def BlockdevFind(disk):
2379 a8083063 Iustin Pop
  """Check if a device is activated.
2380 a8083063 Iustin Pop

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

2383 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2384 10c2650b Iustin Pop
  @param disk: the disk to find
2385 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2386 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2387 96acbc09 Michael Hanselmann
           information
2388 a8083063 Iustin Pop

2389 a8083063 Iustin Pop
  """
2390 23829f6f Iustin Pop
  try:
2391 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
2392 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
2393 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
2394 96acbc09 Michael Hanselmann
2395 a8083063 Iustin Pop
  if rbd is None:
2396 c26a6bd2 Iustin Pop
    return None
2397 96acbc09 Michael Hanselmann
2398 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2399 a8083063 Iustin Pop
2400 a8083063 Iustin Pop
2401 6ef8077e Bernardo Dal Seno
def BlockdevGetdimensions(disks):
2402 968a7623 Iustin Pop
  """Computes the size of the given disks.
2403 968a7623 Iustin Pop

2404 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2405 968a7623 Iustin Pop

2406 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2407 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2408 968a7623 Iustin Pop
  @rtype: list
2409 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2410 6ef8077e Bernardo Dal Seno
      otherwise the pair (size, spindles), where spindles is None if the
2411 6ef8077e Bernardo Dal Seno
      device doesn't support that
2412 968a7623 Iustin Pop

2413 968a7623 Iustin Pop
  """
2414 968a7623 Iustin Pop
  result = []
2415 968a7623 Iustin Pop
  for cf in disks:
2416 968a7623 Iustin Pop
    try:
2417 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2418 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2419 968a7623 Iustin Pop
      result.append(None)
2420 968a7623 Iustin Pop
      continue
2421 968a7623 Iustin Pop
    if rbd is None:
2422 968a7623 Iustin Pop
      result.append(None)
2423 968a7623 Iustin Pop
    else:
2424 6ef8077e Bernardo Dal Seno
      result.append(rbd.GetActualDimensions())
2425 968a7623 Iustin Pop
  return result
2426 968a7623 Iustin Pop
2427 968a7623 Iustin Pop
2428 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2429 858f3d18 Iustin Pop
  """Export a block device to a remote node.
2430 858f3d18 Iustin Pop

2431 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
2432 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
2433 858f3d18 Iustin Pop
  @type dest_node: str
2434 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
2435 858f3d18 Iustin Pop
  @type dest_path: str
2436 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
2437 858f3d18 Iustin Pop
  @type cluster_name: str
2438 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2439 858f3d18 Iustin Pop
  @rtype: None
2440 858f3d18 Iustin Pop

2441 858f3d18 Iustin Pop
  """
2442 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
2443 858f3d18 Iustin Pop
2444 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
2445 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2446 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
2447 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
2448 858f3d18 Iustin Pop
2449 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
2450 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
2451 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
2452 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2453 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
2454 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
2455 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2456 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
2457 858f3d18 Iustin Pop
2458 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2459 052783ff Michael Hanselmann
                                                   constants.SSH_LOGIN_USER,
2460 858f3d18 Iustin Pop
                                                   destcmd)
2461 858f3d18 Iustin Pop
2462 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
2463 d0c8c01d Iustin Pop
  command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2464 858f3d18 Iustin Pop
2465 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
2466 858f3d18 Iustin Pop
2467 858f3d18 Iustin Pop
  if result.failed:
2468 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
2469 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
2470 858f3d18 Iustin Pop
2471 858f3d18 Iustin Pop
2472 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2473 a8083063 Iustin Pop
  """Write a file to the filesystem.
2474 a8083063 Iustin Pop

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

2478 10c2650b Iustin Pop
  @type file_name: str
2479 10c2650b Iustin Pop
  @param file_name: the target file name
2480 10c2650b Iustin Pop
  @type data: str
2481 10c2650b Iustin Pop
  @param data: the new contents of the file
2482 10c2650b Iustin Pop
  @type mode: int
2483 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2484 9a914f7a René Nussbaumer
  @type uid: string
2485 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2486 9a914f7a René Nussbaumer
  @type gid: string
2487 9a914f7a René Nussbaumer
  @param gid: the group of the file
2488 10c2650b Iustin Pop
  @type atime: float
2489 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2490 10c2650b Iustin Pop
  @type mtime: float
2491 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2492 c26a6bd2 Iustin Pop
  @rtype: None
2493 10c2650b Iustin Pop

2494 a8083063 Iustin Pop
  """
2495 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2496 cffbbae7 Michael Hanselmann
2497 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2498 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2499 a8083063 Iustin Pop
2500 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2501 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2502 2cc6781a Iustin Pop
          file_name)
2503 a8083063 Iustin Pop
2504 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2505 12bce260 Michael Hanselmann
2506 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2507 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2508 9a914f7a René Nussbaumer
2509 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2510 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2511 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2512 9a914f7a René Nussbaumer
2513 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2514 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2515 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2516 a8083063 Iustin Pop
2517 386b57af Iustin Pop
2518 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2519 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2520 b2f29800 René Nussbaumer

2521 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2522 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2523 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2524 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2525 b2f29800 René Nussbaumer

2526 b2f29800 René Nussbaumer
  @return: stdout
2527 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2528 b2f29800 René Nussbaumer

2529 b2f29800 René Nussbaumer
  """
2530 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2531 b2f29800 René Nussbaumer
2532 b2f29800 René Nussbaumer
  if result.failed:
2533 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2534 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2535 b2f29800 René Nussbaumer
2536 b2f29800 René Nussbaumer
  return result.stdout
2537 b2f29800 René Nussbaumer
2538 b2f29800 René Nussbaumer
2539 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2540 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2541 a8083063 Iustin Pop

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

2545 10c2650b Iustin Pop
  @type os_dir: str
2546 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2547 8e70b181 Iustin Pop
  @rtype: tuple
2548 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2549 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2550 a8083063 Iustin Pop

2551 a8083063 Iustin Pop
  """
2552 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2553 a8083063 Iustin Pop
2554 a8083063 Iustin Pop
  try:
2555 a8083063 Iustin Pop
    st = os.stat(api_file)
2556 a8083063 Iustin Pop
  except EnvironmentError, err:
2557 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2558 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2559 a8083063 Iustin Pop
2560 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2561 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2562 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2563 a8083063 Iustin Pop
2564 a8083063 Iustin Pop
  try:
2565 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2566 a8083063 Iustin Pop
  except EnvironmentError, err:
2567 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2568 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2569 a8083063 Iustin Pop
2570 a8083063 Iustin Pop
  try:
2571 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2572 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2573 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2574 255dcebd Iustin Pop
                   str(err))
2575 a8083063 Iustin Pop
2576 255dcebd Iustin Pop
  return True, api_versions
2577 a8083063 Iustin Pop
2578 386b57af Iustin Pop
2579 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2580 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2581 a8083063 Iustin Pop

2582 10c2650b Iustin Pop
  @type top_dirs: list
2583 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2584 10c2650b Iustin Pop
      search (if not given defaults to
2585 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2586 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2587 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2588 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2589 bad78e66 Iustin Pop
      search paths, where:
2590 255dcebd Iustin Pop
          - name is the (potential) OS name
2591 255dcebd Iustin Pop
          - path is the full path to the OS
2592 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2593 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2594 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2595 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2596 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2597 a8083063 Iustin Pop

2598 a8083063 Iustin Pop
  """
2599 7c3d51d4 Guido Trotter
  if top_dirs is None:
2600 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2601 a8083063 Iustin Pop
2602 a8083063 Iustin Pop
  result = []
2603 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2604 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2605 7c3d51d4 Guido Trotter
      try:
2606 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2607 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2608 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2609 7c3d51d4 Guido Trotter
        break
2610 7c3d51d4 Guido Trotter
      for name in f_names:
2611 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2612 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2613 255dcebd Iustin Pop
        if status:
2614 255dcebd Iustin Pop
          diagnose = ""
2615 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2616 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2617 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2618 255dcebd Iustin Pop
        else:
2619 255dcebd Iustin Pop
          diagnose = os_inst
2620 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2621 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2622 bad78e66 Iustin Pop
                       parameters, api_versions))
2623 a8083063 Iustin Pop
2624 c26a6bd2 Iustin Pop
  return result
2625 a8083063 Iustin Pop
2626 a8083063 Iustin Pop
2627 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2628 a8083063 Iustin Pop
  """Create an OS instance from disk.
2629 a8083063 Iustin Pop

2630 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2631 8e70b181 Iustin Pop
  valid OS name.
2632 a8083063 Iustin Pop

2633 8ee4dc80 Guido Trotter
  @type base_dir: string
2634 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2635 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2636 255dcebd Iustin Pop
  @rtype: tuple
2637 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2638 255dcebd Iustin Pop
      or error message
2639 7c3d51d4 Guido Trotter

2640 a8083063 Iustin Pop
  """
2641 56bcd3f4 Guido Trotter
  if base_dir is None:
2642 710f30ec Michael Hanselmann
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2643 c34c0cfd Iustin Pop
  else:
2644 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2645 f95c81bf Iustin Pop
2646 f95c81bf Iustin Pop
  if os_dir is None:
2647 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
2648 a8083063 Iustin Pop
2649 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2650 255dcebd Iustin Pop
  if not status:
2651 255dcebd Iustin Pop
    # push the error up
2652 255dcebd Iustin Pop
    return status, api_versions
2653 a8083063 Iustin Pop
2654 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2655 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2656 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2657 a8083063 Iustin Pop
2658 35007011 Iustin Pop
  # OS Files dictionary, we will populate it with the absolute path
2659 35007011 Iustin Pop
  # names; if the value is True, then it is a required file, otherwise
2660 35007011 Iustin Pop
  # an optional one
2661 35007011 Iustin Pop
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2662 a8083063 Iustin Pop
2663 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
2664 35007011 Iustin Pop
    os_files[constants.OS_VARIANTS_FILE] = False
2665 95075fba Guido Trotter
2666 c7d04a6b Iustin Pop
  if max(api_versions) >= constants.OS_API_V20:
2667 35007011 Iustin Pop
    os_files[constants.OS_PARAMETERS_FILE] = True
2668 c7d04a6b Iustin Pop
  else:
2669 c7d04a6b Iustin Pop
    del os_files[constants.OS_SCRIPT_VERIFY]
2670 c7d04a6b Iustin Pop
2671 35007011 Iustin Pop
  for (filename, required) in os_files.items():
2672 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
2673 a8083063 Iustin Pop
2674 a8083063 Iustin Pop
    try:
2675 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
2676 a8083063 Iustin Pop
    except EnvironmentError, err:
2677 35007011 Iustin Pop
      if err.errno == errno.ENOENT and not required:
2678 35007011 Iustin Pop
        del os_files[filename]
2679 35007011 Iustin Pop
        continue
2680 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
2681 eb93b673 Guido Trotter
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2682 a8083063 Iustin Pop
2683 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2684 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
2685 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
2686 255dcebd Iustin Pop
2687 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
2688 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2689 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
2690 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
2691 0757c107 Guido Trotter
2692 845da3e8 Iustin Pop
  variants = []
2693 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
2694 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2695 95075fba Guido Trotter
    try:
2696 5a7cb9d3 Iustin Pop
      variants = \
2697 5a7cb9d3 Iustin Pop
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2698 95075fba Guido Trotter
    except EnvironmentError, err:
2699 35007011 Iustin Pop
      # we accept missing files, but not other errors
2700 35007011 Iustin Pop
      if err.errno != errno.ENOENT:
2701 35007011 Iustin Pop
        return False, ("Error while reading the OS variants file at %s: %s" %
2702 eb93b673 Guido Trotter
                       (variants_file, utils.ErrnoOrStr(err)))
2703 0757c107 Guido Trotter
2704 c7d04a6b Iustin Pop
  parameters = []
2705 c7d04a6b Iustin Pop
  if constants.OS_PARAMETERS_FILE in os_files:
2706 c7d04a6b Iustin Pop
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2707 c7d04a6b Iustin Pop
    try:
2708 c7d04a6b Iustin Pop
      parameters = utils.ReadFile(parameters_file).splitlines()
2709 c7d04a6b Iustin Pop
    except EnvironmentError, err:
2710 c7d04a6b Iustin Pop
      return False, ("Error while reading the OS parameters file at %s: %s" %
2711 eb93b673 Guido Trotter
                     (parameters_file, utils.ErrnoOrStr(err)))
2712 c7d04a6b Iustin Pop
    parameters = [v.split(None, 1) for v in parameters]
2713 c7d04a6b Iustin Pop
2714 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
2715 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2716 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2717 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2718 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2719 40684c3a Iustin Pop
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2720 40684c3a Iustin Pop
                                                 None),
2721 95075fba Guido Trotter
                      supported_variants=variants,
2722 c7d04a6b Iustin Pop
                      supported_parameters=parameters,
2723 255dcebd Iustin Pop
                      api_versions=api_versions)
2724 255dcebd Iustin Pop
  return True, os_obj
2725 255dcebd Iustin Pop
2726 255dcebd Iustin Pop
2727 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
2728 255dcebd Iustin Pop
  """Create an OS instance from disk.
2729 255dcebd Iustin Pop

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

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

2737 255dcebd Iustin Pop
  @type base_dir: string
2738 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2739 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2740 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2741 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2742 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2743 255dcebd Iustin Pop

2744 255dcebd Iustin Pop
  """
2745 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2746 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2747 255dcebd Iustin Pop
2748 255dcebd Iustin Pop
  if not status:
2749 255dcebd Iustin Pop
    _Fail(payload)
2750 a8083063 Iustin Pop
2751 255dcebd Iustin Pop
  return payload
2752 a8083063 Iustin Pop
2753 a8083063 Iustin Pop
2754 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2755 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2756 2266edb2 Guido Trotter

2757 a025e535 Vitaly Kuznetsov
  @type os_name: str
2758 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2759 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2760 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2761 1bdcbbab Iustin Pop
  @type os_params: dict
2762 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2763 2266edb2 Guido Trotter
  @type debug: integer
2764 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2765 2266edb2 Guido Trotter
  @rtype: dict
2766 2266edb2 Guido Trotter
  @return: dict of environment variables
2767 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2768 10c2650b Iustin Pop
      cannot be found
2769 2266edb2 Guido Trotter

2770 2266edb2 Guido Trotter
  """
2771 2266edb2 Guido Trotter
  result = {}
2772 099c52ad Iustin Pop
  api_version = \
2773 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2774 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2775 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2776 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2777 efaa9b06 Iustin Pop
2778 efaa9b06 Iustin Pop
  # OS variants
2779 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2780 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2781 870dc44c Iustin Pop
    if not variant:
2782 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2783 35007011 Iustin Pop
  else:
2784 35007011 Iustin Pop
    variant = ""
2785 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2786 efaa9b06 Iustin Pop
2787 1bdcbbab Iustin Pop
  # OS params
2788 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2789 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2790 1bdcbbab Iustin Pop
2791 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
2792 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
2793 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
2794 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
2795 9a6ade06 Iustin Pop
2796 efaa9b06 Iustin Pop
  return result
2797 efaa9b06 Iustin Pop
2798 efaa9b06 Iustin Pop
2799 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2800 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2801 efaa9b06 Iustin Pop

2802 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2803 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2804 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2805 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2806 efaa9b06 Iustin Pop
  @type debug: integer
2807 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2808 efaa9b06 Iustin Pop
  @rtype: dict
2809 efaa9b06 Iustin Pop
  @return: dict of environment variables
2810 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2811 efaa9b06 Iustin Pop
      cannot be found
2812 efaa9b06 Iustin Pop

2813 efaa9b06 Iustin Pop
  """
2814 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2815 efaa9b06 Iustin Pop
2816 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2817 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2818 f2165b8a Iustin Pop
2819 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2820 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2821 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2822 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2823 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2824 efaa9b06 Iustin Pop
2825 efaa9b06 Iustin Pop
  # Disks
2826 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2827 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2828 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2829 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2830 8a348b15 Christos Stavrakakis
    result["DISK_%d_UUID" % idx] = disk.uuid
2831 8a348b15 Christos Stavrakakis
    if disk.name:
2832 8a348b15 Christos Stavrakakis
      result["DISK_%d_NAME" % idx] = disk.name
2833 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2834 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2835 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2836 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2837 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2838 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2839 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2840 d0c8c01d Iustin Pop
        "file:%s" % disk.physical_id[0]
2841 efaa9b06 Iustin Pop
2842 efaa9b06 Iustin Pop
  # NICs
2843 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2844 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2845 8a348b15 Christos Stavrakakis
    result["NIC_%d_UUID" % idx] = nic.uuid
2846 8a348b15 Christos Stavrakakis
    if nic.name:
2847 8a348b15 Christos Stavrakakis
      result["NIC_%d_NAME" % idx] = nic.name
2848 2266edb2 Guido Trotter
    if nic.ip:
2849 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2850 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2851 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2852 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2853 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2854 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2855 d89168ff Guido Trotter
    if nic.netinfo:
2856 d89168ff Guido Trotter
      nobj = objects.Network.FromDict(nic.netinfo)
2857 d89168ff Guido Trotter
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2858 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2859 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2860 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2861 2266edb2 Guido Trotter
2862 efaa9b06 Iustin Pop
  # HV/BE params
2863 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2864 67fc3042 Iustin Pop
    for key, value in source.items():
2865 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2866 67fc3042 Iustin Pop
2867 2266edb2 Guido Trotter
  return result
2868 a8083063 Iustin Pop
2869 f2e07bb4 Michael Hanselmann
2870 b954f097 Constantinos Venetsanopoulos
def DiagnoseExtStorage(top_dirs=None):
2871 b954f097 Constantinos Venetsanopoulos
  """Compute the validity for all ExtStorage Providers.
2872 b954f097 Constantinos Venetsanopoulos

2873 b954f097 Constantinos Venetsanopoulos
  @type top_dirs: list
2874 b954f097 Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
2875 b954f097 Constantinos Venetsanopoulos
      search (if not given defaults to
2876 b954f097 Constantinos Venetsanopoulos
      L{pathutils.ES_SEARCH_PATH})
2877 b954f097 Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
2878 b954f097 Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
2879 b954f097 Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
2880 b954f097 Constantinos Venetsanopoulos
      search paths, where:
2881 b954f097 Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
2882 b954f097 Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
2883 b954f097 Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
2884 b954f097 Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
2885 b954f097 Constantinos Venetsanopoulos
            otherwise empty
2886 b954f097 Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
2887 b954f097 Constantinos Venetsanopoulos

2888 b954f097 Constantinos Venetsanopoulos
  """
2889 b954f097 Constantinos Venetsanopoulos
  if top_dirs is None:
2890 b954f097 Constantinos Venetsanopoulos
    top_dirs = pathutils.ES_SEARCH_PATH
2891 b954f097 Constantinos Venetsanopoulos
2892 b954f097 Constantinos Venetsanopoulos
  result = []
2893 b954f097 Constantinos Venetsanopoulos
  for dir_name in top_dirs:
2894 b954f097 Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
2895 b954f097 Constantinos Venetsanopoulos
      try:
2896 b954f097 Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
2897 b954f097 Constantinos Venetsanopoulos
      except EnvironmentError, err:
2898 b954f097 Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
2899 b954f097 Constantinos Venetsanopoulos
                          dir_name, err)
2900 b954f097 Constantinos Venetsanopoulos
        break
2901 b954f097 Constantinos Venetsanopoulos
      for name in f_names:
2902 b954f097 Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
2903 b954f097 Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2904 b954f097 Constantinos Venetsanopoulos
        if status:
2905 b954f097 Constantinos Venetsanopoulos
          diagnose = ""
2906 b954f097 Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
2907 b954f097 Constantinos Venetsanopoulos
        else:
2908 b954f097 Constantinos Venetsanopoulos
          diagnose = es_inst
2909 b954f097 Constantinos Venetsanopoulos
          parameters = []
2910 b954f097 Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
2911 b954f097 Constantinos Venetsanopoulos
2912 b954f097 Constantinos Venetsanopoulos
  return result
2913 b954f097 Constantinos Venetsanopoulos
2914 b954f097 Constantinos Venetsanopoulos
2915 be9150ea Bernardo Dal Seno
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2916 594609c0 Iustin Pop
  """Grow a stack of block devices.
2917 594609c0 Iustin Pop

2918 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2919 10c2650b Iustin Pop
  first ones to resize.
2920 594609c0 Iustin Pop

2921 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2922 10c2650b Iustin Pop
  @param disk: the disk to be grown
2923 a59faf4b Iustin Pop
  @type amount: integer
2924 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2925 a59faf4b Iustin Pop
  @type dryrun: boolean
2926 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2927 a59faf4b Iustin Pop
      only, without actually increasing the size
2928 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
2929 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2930 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
2931 10c2650b Iustin Pop
  @rtype: (status, result)
2932 be9150ea Bernardo Dal Seno
  @type excl_stor: boolean
2933 be9150ea Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
2934 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2935 a59faf4b Iustin Pop
      the errors message if status is False
2936 594609c0 Iustin Pop

2937 594609c0 Iustin Pop
  """
2938 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2939 594609c0 Iustin Pop
  if r_dev is None:
2940 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2941 594609c0 Iustin Pop
2942 594609c0 Iustin Pop
  try:
2943 be9150ea Bernardo Dal Seno
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2944 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2945 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2946 594609c0 Iustin Pop
2947 594609c0 Iustin Pop
2948 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2949 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2950 a8083063 Iustin Pop

2951 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2952 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2953 a8083063 Iustin Pop

2954 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2955 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2956 e9e9263d Guido Trotter
  @rtype: string
2957 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2958 a8083063 Iustin Pop

2959 098c0958 Michael Hanselmann
  """
2960 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2961 433c63aa Iustin Pop
    if not disk.children:
2962 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2963 433c63aa Iustin Pop
            disk.unique_id)
2964 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2965 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2966 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2967 a8083063 Iustin Pop
    if r_dev is not None:
2968 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2969 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2970 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2971 a8083063 Iustin Pop
    else:
2972 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2973 a8083063 Iustin Pop
  else:
2974 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2975 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2976 a8083063 Iustin Pop
2977 a8083063 Iustin Pop
2978 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
2979 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
2980 48e175a2 Iustin Pop

2981 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
2982 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
2983 48e175a2 Iustin Pop
  for example after renames.
2984 48e175a2 Iustin Pop

2985 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
2986 48e175a2 Iustin Pop
  @param disk: the disk to be grown
2987 48e175a2 Iustin Pop
  @type info: string
2988 48e175a2 Iustin Pop
  @param info: new 'info' metadata
2989 48e175a2 Iustin Pop
  @rtype: (status, result)
2990 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2991 48e175a2 Iustin Pop
      the errors message if status is False
2992 48e175a2 Iustin Pop

2993 48e175a2 Iustin Pop
  """
2994 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2995 48e175a2 Iustin Pop
  if r_dev is None:
2996 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2997 48e175a2 Iustin Pop
2998 48e175a2 Iustin Pop
  try:
2999 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
3000 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
3001 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
3002 48e175a2 Iustin Pop
3003 48e175a2 Iustin Pop
3004 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
3005 a8083063 Iustin Pop
  """Write out the export configuration information.
3006 a8083063 Iustin Pop

3007 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
3008 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
3009 10c2650b Iustin Pop
      saving configuration
3010 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
3011 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
3012 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
3013 a8083063 Iustin Pop

3014 c26a6bd2 Iustin Pop
  @rtype: None
3015 a8083063 Iustin Pop

3016 098c0958 Michael Hanselmann
  """
3017 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3018 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3019 a8083063 Iustin Pop
3020 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
3021 a8083063 Iustin Pop
3022 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
3023 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
3024 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3025 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3026 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
3027 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
3028 a8083063 Iustin Pop
3029 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
3030 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
3031 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3032 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
3033 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
3034 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
3035 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3036 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
3037 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
3038 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3039 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
3040 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3041 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3042 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3043 66f93869 Manuel Franceschini
3044 95268cc3 Iustin Pop
  nic_total = 0
3045 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
3046 95268cc3 Iustin Pop
    nic_total += 1
3047 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
3048 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
3049 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3050 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3051 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
3052 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
3053 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3054 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
3055 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
3056 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3057 a8083063 Iustin Pop
3058 726d7d68 Iustin Pop
  disk_total = 0
3059 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
3060 19d7f90a Guido Trotter
    if disk:
3061 726d7d68 Iustin Pop
      disk_total += 1
3062 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3063 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
3064 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3065 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
3066 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3067 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
3068 d0c8c01d Iustin Pop
3069 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3070 a8083063 Iustin Pop
3071 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
3072 3c8954ad Iustin Pop
3073 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
3074 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
3075 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
3076 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
3077 3c8954ad Iustin Pop
3078 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
3079 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
3080 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
3081 3c8954ad Iustin Pop
3082 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
3083 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
3084 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
3085 535b49cb Iustin Pop
3086 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3087 726d7d68 Iustin Pop
                  data=config.Dumps())
3088 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
3089 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
3090 a8083063 Iustin Pop
3091 a8083063 Iustin Pop
3092 a8083063 Iustin Pop
def ExportInfo(dest):
3093 a8083063 Iustin Pop
  """Get export configuration information.
3094 a8083063 Iustin Pop

3095 10c2650b Iustin Pop
  @type dest: str
3096 10c2650b Iustin Pop
  @param dest: directory containing the export
3097 a8083063 Iustin Pop

3098 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
3099 10c2650b Iustin Pop
  @return: a serializable config file containing the
3100 10c2650b Iustin Pop
      export info
3101 a8083063 Iustin Pop

3102 a8083063 Iustin Pop
  """
3103 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3104 a8083063 Iustin Pop
3105 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
3106 a8083063 Iustin Pop
  config.read(cff)
3107 a8083063 Iustin Pop
3108 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
3109 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
3110 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
3111 a8083063 Iustin Pop
3112 c26a6bd2 Iustin Pop
  return config.Dumps()
3113 a8083063 Iustin Pop
3114 a8083063 Iustin Pop
3115 a8083063 Iustin Pop
def ListExports():
3116 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
3117 098c0958 Michael Hanselmann

3118 10c2650b Iustin Pop
  @rtype: list
3119 10c2650b Iustin Pop
  @return: list of the exports
3120 10c2650b Iustin Pop

3121 a8083063 Iustin Pop
  """
3122 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
3123 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3124 a8083063 Iustin Pop
  else:
3125 afdc3985 Iustin Pop
    _Fail("No exports directory")
3126 a8083063 Iustin Pop
3127 a8083063 Iustin Pop
3128 a8083063 Iustin Pop
def RemoveExport(export):
3129 a8083063 Iustin Pop
  """Remove an existing export from the node.
3130 a8083063 Iustin Pop

3131 10c2650b Iustin Pop
  @type export: str
3132 10c2650b Iustin Pop
  @param export: the name of the export to remove
3133 c26a6bd2 Iustin Pop
  @rtype: None
3134 a8083063 Iustin Pop

3135 098c0958 Michael Hanselmann
  """
3136 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3137 a8083063 Iustin Pop
3138 35fbcd11 Iustin Pop
  try:
3139 35fbcd11 Iustin Pop
    shutil.rmtree(target)
3140 35fbcd11 Iustin Pop
  except EnvironmentError, err:
3141 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
3142 a8083063 Iustin Pop
3143 a8083063 Iustin Pop
3144 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
3145 f3e513ad Iustin Pop
  """Rename a list of block devices.
3146 f3e513ad Iustin Pop

3147 10c2650b Iustin Pop
  @type devlist: list of tuples
3148 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
3149 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
3150 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
3151 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
3152 10c2650b Iustin Pop
      rename it to
3153 10c2650b Iustin Pop
  @rtype: boolean
3154 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
3155 f3e513ad Iustin Pop

3156 f3e513ad Iustin Pop
  """
3157 6b5e3f70 Iustin Pop
  msgs = []
3158 f3e513ad Iustin Pop
  result = True
3159 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
3160 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
3161 f3e513ad Iustin Pop
    if dev is None:
3162 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
3163 f3e513ad Iustin Pop
      result = False
3164 f3e513ad Iustin Pop
      continue
3165 f3e513ad Iustin Pop
    try:
3166 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
3167 f3e513ad Iustin Pop
      dev.Rename(unique_id)
3168 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
3169 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
3170 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
3171 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
3172 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3173 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
3174 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
3175 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
3176 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
3177 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
3178 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
3179 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3180 f3e513ad Iustin Pop
      result = False
3181 afdc3985 Iustin Pop
  if not result:
3182 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
3183 f3e513ad Iustin Pop
3184 f3e513ad Iustin Pop
3185 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
3186 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
3187 778b75bb Manuel Franceschini

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

3192 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
3193 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
3194 d61cbe76 Iustin Pop

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

3197 778b75bb Manuel Franceschini
  """
3198 5e09a309 Michael Hanselmann
  bdev.CheckFileStoragePath(fs_dir)
3199 5e09a309 Michael Hanselmann
3200 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
3201 778b75bb Manuel Franceschini
3202 778b75bb Manuel Franceschini
3203 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
3204 778b75bb Manuel Franceschini
  """Create file storage directory.
3205 778b75bb Manuel Franceschini

3206 b1206984 Iustin Pop
  @type file_storage_dir: str
3207 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
3208 778b75bb Manuel Franceschini

3209 b1206984 Iustin Pop
  @rtype: tuple
3210 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
3211 b1206984 Iustin Pop
      creation was successful or not
3212 778b75bb Manuel Franceschini

3213 778b75bb Manuel Franceschini
  """
3214 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3215 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
3216 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
3217 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
3218 b2b8bcce Iustin Pop
            file_storage_dir)
3219 778b75bb Manuel Franceschini
  else:
3220 b2b8bcce Iustin Pop
    try:
3221 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
3222 b2b8bcce Iustin Pop
    except OSError, err:
3223 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
3224 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
3225 778b75bb Manuel Franceschini
3226 778b75bb Manuel Franceschini
3227 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
3228 778b75bb Manuel Franceschini
  """Remove file storage directory.
3229 778b75bb Manuel Franceschini

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

3232 10c2650b Iustin Pop
  @type file_storage_dir: str
3233 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
3234 10c2650b Iustin Pop
  @rtype: tuple (success,)
3235 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
3236 5bbd3f7f Michael Hanselmann
      whether the operation was successful
3237 778b75bb Manuel Franceschini

3238 778b75bb Manuel Franceschini
  """
3239 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3240 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
3241 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
3242 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
3243 b2b8bcce Iustin Pop
            file_storage_dir)
3244 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
3245 b2b8bcce Iustin Pop
    try:
3246 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
3247 b2b8bcce Iustin Pop
    except OSError, err:
3248 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
3249 b2b8bcce Iustin Pop
            file_storage_dir, err)
3250 b2b8bcce Iustin Pop
3251 778b75bb Manuel Franceschini
3252 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3253 778b75bb Manuel Franceschini
  """Rename the file storage directory.
3254 778b75bb Manuel Franceschini

3255 10c2650b Iustin Pop
  @type old_file_storage_dir: str
3256 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
3257 10c2650b Iustin Pop
  @type new_file_storage_dir: str
3258 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
3259 10c2650b Iustin Pop
  @rtype: tuple (success,)
3260 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
3261 10c2650b Iustin Pop
      whether the operation was successful
3262 778b75bb Manuel Franceschini

3263 778b75bb Manuel Franceschini
  """
3264 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3265 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3266 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
3267 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
3268 b2b8bcce Iustin Pop
      try:
3269 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
3270 b2b8bcce Iustin Pop
      except OSError, err:
3271 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
3272 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
3273 778b75bb Manuel Franceschini
    else:
3274 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
3275 b2b8bcce Iustin Pop
            old_file_storage_dir)
3276 b2b8bcce Iustin Pop
  else:
3277 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
3278 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3279 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
3280 778b75bb Manuel Franceschini
3281 778b75bb Manuel Franceschini
3282 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
3283 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
3284 ca52cdeb Michael Hanselmann

3285 10c2650b Iustin Pop
  @type file_name: str
3286 10c2650b Iustin Pop
  @param file_name: the file name we should check
3287 c8457ce7 Iustin Pop
  @rtype: None
3288 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
3289 10c2650b Iustin Pop

3290 ca52cdeb Michael Hanselmann
  """
3291 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3292 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
3293 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3294 dc31eae3 Michael Hanselmann
3295 dc31eae3 Michael Hanselmann
3296 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
3297 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
3298 dc31eae3 Michael Hanselmann

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

3302 10c2650b Iustin Pop
  @type file_name: str
3303 10c2650b Iustin Pop
  @param file_name: the job file name
3304 10c2650b Iustin Pop
  @type content: str
3305 10c2650b Iustin Pop
  @param content: the new job contents
3306 10c2650b Iustin Pop
  @rtype: boolean
3307 10c2650b Iustin Pop
  @return: the success of the operation
3308 10c2650b Iustin Pop

3309 dc31eae3 Michael Hanselmann
  """
3310 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
3311 cffbbae7 Michael Hanselmann
3312 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
3313 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
3314 ca52cdeb Michael Hanselmann
3315 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
3316 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3317 fe05a931 Michele Tartara
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3318 ca52cdeb Michael Hanselmann
3319 ca52cdeb Michael Hanselmann
3320 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
3321 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
3322 af5ebcb1 Michael Hanselmann

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

3325 10c2650b Iustin Pop
  @type old: str
3326 10c2650b Iustin Pop
  @param old: the old (actual) file name
3327 10c2650b Iustin Pop
  @type new: str
3328 10c2650b Iustin Pop
  @param new: the desired file name
3329 c8457ce7 Iustin Pop
  @rtype: tuple
3330 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
3331 10c2650b Iustin Pop

3332 af5ebcb1 Michael Hanselmann
  """
3333 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
3334 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
3335 cffbbae7 Michael Hanselmann
3336 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
3337 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
3338 af5ebcb1 Michael Hanselmann
3339 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
3340 8e5a705d René Nussbaumer
3341 fe05a931 Michele Tartara
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3342 fe05a931 Michele Tartara
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3343 af5ebcb1 Michael Hanselmann
3344 af5ebcb1 Michael Hanselmann
3345 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
3346 d61cbe76 Iustin Pop
  """Closes the given block devices.
3347 d61cbe76 Iustin Pop

3348 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
3349 10c2650b Iustin Pop
  DRBD).
3350 10c2650b Iustin Pop

3351 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
3352 b2e7666a Iustin Pop
      of this instance will be removed
3353 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
3354 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
3355 10c2650b Iustin Pop
  @rtype: tuple (success, message)
3356 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
3357 10c2650b Iustin Pop
      indicates the succes of the operation, and message
3358 10c2650b Iustin Pop
      which will contain the error details in case we
3359 10c2650b Iustin Pop
      failed
3360 d61cbe76 Iustin Pop

3361 d61cbe76 Iustin Pop
  """
3362 d61cbe76 Iustin Pop
  bdevs = []
3363 d61cbe76 Iustin Pop
  for cf in disks:
3364 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
3365 d61cbe76 Iustin Pop
    if rd is None:
3366 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
3367 d61cbe76 Iustin Pop
    bdevs.append(rd)
3368 d61cbe76 Iustin Pop
3369 d61cbe76 Iustin Pop
  msg = []
3370 d61cbe76 Iustin Pop
  for rd in bdevs:
3371 d61cbe76 Iustin Pop
    try:
3372 d61cbe76 Iustin Pop
      rd.Close()
3373 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
3374 d61cbe76 Iustin Pop
      msg.append(str(err))
3375 d61cbe76 Iustin Pop
  if msg:
3376 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3377 d61cbe76 Iustin Pop
  else:
3378 b2e7666a Iustin Pop
    if instance_name:
3379 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
3380 d61cbe76 Iustin Pop
3381 d61cbe76 Iustin Pop
3382 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
3383 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
3384 6217e295 Iustin Pop

3385 6217e295 Iustin Pop
  @type hvname: string
3386 6217e295 Iustin Pop
  @param hvname: the hypervisor name
3387 6217e295 Iustin Pop
  @type hvparams: dict
3388 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
3389 c26a6bd2 Iustin Pop
  @rtype: None
3390 6217e295 Iustin Pop

3391 6217e295 Iustin Pop
  """
3392 6217e295 Iustin Pop
  try:
3393 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
3394 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
3395 6217e295 Iustin Pop
  except errors.HypervisorError, err:
3396 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
3397 6217e295 Iustin Pop
3398 6217e295 Iustin Pop
3399 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
3400 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
3401 acd9ff9e Iustin Pop

3402 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
3403 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
3404 acd9ff9e Iustin Pop
  @type parameters: list
3405 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
3406 acd9ff9e Iustin Pop

3407 acd9ff9e Iustin Pop
  """
3408 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
3409 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
3410 acd9ff9e Iustin Pop
  if delta:
3411 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
3412 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3413 acd9ff9e Iustin Pop
3414 acd9ff9e Iustin Pop
3415 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
3416 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
3417 acd9ff9e Iustin Pop

3418 acd9ff9e Iustin Pop
  @type required: boolean
3419 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3420 acd9ff9e Iustin Pop
      failure or not
3421 acd9ff9e Iustin Pop
  @type osname: string
3422 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3423 acd9ff9e Iustin Pop
  @type checks: list
3424 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3425 acd9ff9e Iustin Pop
  @type osparams: dict
3426 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
3427 acd9ff9e Iustin Pop
  @rtype: boolean
3428 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3429 acd9ff9e Iustin Pop
      found and L{required} was false
3430 acd9ff9e Iustin Pop

3431 acd9ff9e Iustin Pop
  """
3432 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3433 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3434 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3435 acd9ff9e Iustin Pop
3436 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3437 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3438 acd9ff9e Iustin Pop
3439 acd9ff9e Iustin Pop
  if not status:
3440 acd9ff9e Iustin Pop
    if required:
3441 acd9ff9e Iustin Pop
      _Fail(tbv)
3442 acd9ff9e Iustin Pop
    else:
3443 acd9ff9e Iustin Pop
      return False
3444 acd9ff9e Iustin Pop
3445 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3446 72db3fd7 Iustin Pop
    return True
3447 72db3fd7 Iustin Pop
3448 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3449 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3450 acd9ff9e Iustin Pop
3451 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3452 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3453 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3454 acd9ff9e Iustin Pop
  if result.failed:
3455 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3456 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3457 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3458 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3459 acd9ff9e Iustin Pop
3460 acd9ff9e Iustin Pop
  return True
3461 acd9ff9e Iustin Pop
3462 acd9ff9e Iustin Pop
3463 56aa9fd5 Iustin Pop
def DemoteFromMC():
3464 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3465 56aa9fd5 Iustin Pop

3466 56aa9fd5 Iustin Pop
  """
3467 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3468 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3469 56aa9fd5 Iustin Pop
  if master == myself:
3470 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3471 f154a7a3 Michael Hanselmann
3472 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3473 f154a7a3 Michael Hanselmann
  if not result.failed:
3474 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3475 f154a7a3 Michael Hanselmann
3476 56aa9fd5 Iustin Pop
  try:
3477 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3478 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3479 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3480 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3481 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3482 f154a7a3 Michael Hanselmann
3483 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3484 56aa9fd5 Iustin Pop
3485 56aa9fd5 Iustin Pop
3486 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3487 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3488 f942a838 Michael Hanselmann

3489 f942a838 Michael Hanselmann
  """
3490 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3491 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3492 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3493 f942a838 Michael Hanselmann
3494 f942a838 Michael Hanselmann
3495 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3496 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3497 f942a838 Michael Hanselmann

3498 f942a838 Michael Hanselmann
  @type validity: int
3499 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3500 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3501 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3502 f942a838 Michael Hanselmann

3503 f942a838 Michael Hanselmann
  """
3504 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3505 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3506 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3507 f942a838 Michael Hanselmann
3508 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3509 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3510 f942a838 Michael Hanselmann
  try:
3511 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3512 f942a838 Michael Hanselmann
    assert len(name) > 5
3513 f942a838 Michael Hanselmann
3514 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3515 f942a838 Michael Hanselmann
3516 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3517 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3518 f942a838 Michael Hanselmann
3519 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3520 f942a838 Michael Hanselmann
    return (name, cert_pem)
3521 f942a838 Michael Hanselmann
  except Exception:
3522 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3523 f942a838 Michael Hanselmann
    raise
3524 f942a838 Michael Hanselmann
3525 f942a838 Michael Hanselmann
3526 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3527 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3528 f942a838 Michael Hanselmann

3529 f942a838 Michael Hanselmann
  @type name: string
3530 f942a838 Michael Hanselmann
  @param name: Certificate name
3531 f942a838 Michael Hanselmann

3532 f942a838 Michael Hanselmann
  """
3533 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3534 f942a838 Michael Hanselmann
3535 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3536 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3537 f942a838 Michael Hanselmann
3538 f942a838 Michael Hanselmann
  try:
3539 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3540 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3541 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3542 f942a838 Michael Hanselmann
          cert_dir, err)
3543 f942a838 Michael Hanselmann
3544 f942a838 Michael Hanselmann
3545 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3546 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3547 1651d116 Michael Hanselmann

3548 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3549 1651d116 Michael Hanselmann
  @param instance: The instance object
3550 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3551 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3552 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3553 1651d116 Michael Hanselmann

3554 1651d116 Michael Hanselmann
  """
3555 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3556 1651d116 Michael Hanselmann
3557 1651d116 Michael Hanselmann
  env = None
3558 1651d116 Michael Hanselmann
  prefix = None
3559 1651d116 Michael Hanselmann
  suffix = None
3560 2ad5550d Michael Hanselmann
  exp_size = None
3561 1651d116 Michael Hanselmann
3562 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
3563 1651d116 Michael Hanselmann
    (filename, ) = ieargs
3564 1651d116 Michael Hanselmann
3565 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
3566 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
3567 1651d116 Michael Hanselmann
3568 748c9884 René Nussbaumer
    real_filename = os.path.realpath(filename)
3569 748c9884 René Nussbaumer
    directory = os.path.dirname(real_filename)
3570 1651d116 Michael Hanselmann
3571 710f30ec Michael Hanselmann
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3572 748c9884 René Nussbaumer
      _Fail("File '%s' is not under exports directory '%s': %s",
3573 710f30ec Michael Hanselmann
            filename, pathutils.EXPORT_DIR, real_filename)
3574 1651d116 Michael Hanselmann
3575 1651d116 Michael Hanselmann
    # Create directory
3576 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
3577 1651d116 Michael Hanselmann
3578 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
3579 1651d116 Michael Hanselmann
3580 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3581 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
3582 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3583 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
3584 1651d116 Michael Hanselmann
3585 2ad5550d Michael Hanselmann
      # Retrieve file size
3586 2ad5550d Michael Hanselmann
      try:
3587 2ad5550d Michael Hanselmann
        st = os.stat(filename)
3588 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
3589 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
3590 2ad5550d Michael Hanselmann
      else:
3591 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
3592 2ad5550d Michael Hanselmann
3593 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
3594 1651d116 Michael Hanselmann
    (disk, ) = ieargs
3595 1651d116 Michael Hanselmann
3596 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3597 1651d116 Michael Hanselmann
3598 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3599 1651d116 Michael Hanselmann
      # we set here a smaller block size as, due to transport buffering, more
3600 1651d116 Michael Hanselmann
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3601 1651d116 Michael Hanselmann
      # is not already there or we pass a wrong path; we use notrunc to no
3602 1651d116 Michael Hanselmann
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3603 1651d116 Michael Hanselmann
      # much memory; this means that at best, we flush every 64k, which will
3604 1651d116 Michael Hanselmann
      # not be very fast
3605 1651d116 Michael Hanselmann
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3606 1651d116 Michael Hanselmann
                                    " bs=%s oflag=dsync"),
3607 1651d116 Michael Hanselmann
                                    real_disk.dev_path,
3608 1651d116 Michael Hanselmann
                                    str(64 * 1024))
3609 1651d116 Michael Hanselmann
3610 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3611 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
3612 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3613 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
3614 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
3615 1651d116 Michael Hanselmann
                                   str(disk.size))
3616 2ad5550d Michael Hanselmann
      exp_size = disk.size
3617 1651d116 Michael Hanselmann
3618 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
3619 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
3620 1651d116 Michael Hanselmann
3621 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
3622 1651d116 Michael Hanselmann
3623 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3624 1651d116 Michael Hanselmann
3625 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
3626 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
3627 1651d116 Michael Hanselmann
3628 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3629 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3630 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
3631 1651d116 Michael Hanselmann
      script = inst_os.import_script
3632 1651d116 Michael Hanselmann
3633 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3634 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
3635 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
3636 1651d116 Michael Hanselmann
      script = inst_os.export_script
3637 1651d116 Michael Hanselmann
3638 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
3639 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3640 1651d116 Michael Hanselmann
3641 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3642 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
3643 1651d116 Michael Hanselmann
3644 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3645 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
3646 1651d116 Michael Hanselmann
3647 2ad5550d Michael Hanselmann
    # Let script predict size
3648 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
3649 2ad5550d Michael Hanselmann
3650 1651d116 Michael Hanselmann
  else:
3651 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3652 1651d116 Michael Hanselmann
3653 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
3654 1651d116 Michael Hanselmann
3655 1651d116 Michael Hanselmann
3656 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
3657 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
3658 1651d116 Michael Hanselmann

3659 1651d116 Michael Hanselmann
  """
3660 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3661 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3662 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3663 1651d116 Michael Hanselmann
3664 1651d116 Michael Hanselmann
3665 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3666 6613661a Iustin Pop
                            ieio, ieioargs):
3667 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3668 1651d116 Michael Hanselmann

3669 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3670 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3671 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3672 1651d116 Michael Hanselmann
  @type host: string
3673 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3674 1651d116 Michael Hanselmann
  @type port: int
3675 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3676 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3677 1651d116 Michael Hanselmann
  @param instance: Instance object
3678 6613661a Iustin Pop
  @type component: string
3679 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3680 6613661a Iustin Pop
      e.g. 'disk/0'
3681 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3682 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3683 1651d116 Michael Hanselmann

3684 1651d116 Michael Hanselmann
  """
3685 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
3686 1651d116 Michael Hanselmann
    prefix = "import"
3687 1651d116 Michael Hanselmann
3688 1651d116 Michael Hanselmann
    if not (host is None and port is None):
3689 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
3690 1651d116 Michael Hanselmann
3691 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
3692 1651d116 Michael Hanselmann
    prefix = "export"
3693 1651d116 Michael Hanselmann
3694 1651d116 Michael Hanselmann
    if host is None or port is None:
3695 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
3696 1651d116 Michael Hanselmann
3697 1651d116 Michael Hanselmann
  else:
3698 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
3699 1651d116 Michael Hanselmann
3700 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
3701 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
3702 1651d116 Michael Hanselmann
3703 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3704 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3705 1651d116 Michael Hanselmann
3706 eb630f50 Michael Hanselmann
  if opts.key_name is None:
3707 1651d116 Michael Hanselmann
    # Use server.pem
3708 710f30ec Michael Hanselmann
    key_path = pathutils.NODED_CERT_FILE
3709 710f30ec Michael Hanselmann
    cert_path = pathutils.NODED_CERT_FILE
3710 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
3711 1651d116 Michael Hanselmann
  else:
3712 710f30ec Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3713 eb630f50 Michael Hanselmann
                                                 opts.key_name)
3714 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
3715 1651d116 Michael Hanselmann
3716 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
3717 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
3718 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
3719 63bcea2a Michael Hanselmann
3720 6613661a Iustin Pop
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3721 1651d116 Michael Hanselmann
  try:
3722 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3723 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3724 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3725 1651d116 Michael Hanselmann
3726 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
3727 1651d116 Michael Hanselmann
      # Use server.pem
3728 710f30ec Michael Hanselmann
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3729 eb630f50 Michael Hanselmann
    else:
3730 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
3731 63bcea2a Michael Hanselmann
3732 eb630f50 Michael Hanselmann
    # Write CA file
3733 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
3734 1651d116 Michael Hanselmann
3735 1651d116 Michael Hanselmann
    cmd = [
3736 710f30ec Michael Hanselmann
      pathutils.IMPORT_EXPORT_DAEMON,
3737 1651d116 Michael Hanselmann
      status_file, mode,
3738 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
3739 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
3740 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
3741 1651d116 Michael Hanselmann
      ]
3742 1651d116 Michael Hanselmann
3743 1651d116 Michael Hanselmann
    if host:
3744 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
3745 1651d116 Michael Hanselmann
3746 1651d116 Michael Hanselmann
    if port:
3747 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
3748 1651d116 Michael Hanselmann
3749 855d2fc7 Michael Hanselmann
    if opts.ipv6:
3750 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
3751 855d2fc7 Michael Hanselmann
    else:
3752 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
3753 855d2fc7 Michael Hanselmann
3754 a5310c2a Michael Hanselmann
    if opts.compress:
3755 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
3756 a5310c2a Michael Hanselmann
3757 af1d39b1 Michael Hanselmann
    if opts.magic:
3758 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
3759 af1d39b1 Michael Hanselmann
3760 2ad5550d Michael Hanselmann
    if exp_size is not None:
3761 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
3762 2ad5550d Michael Hanselmann
3763 1651d116 Michael Hanselmann
    if cmd_prefix:
3764 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3765 1651d116 Michael Hanselmann
3766 1651d116 Michael Hanselmann
    if cmd_suffix:
3767 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3768 1651d116 Michael Hanselmann
3769 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
3770 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
3771 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3772 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3773 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
3774 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
3775 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
3776 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3777 4478301b Michael Hanselmann
3778 6aa7a354 Iustin Pop
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3779 1651d116 Michael Hanselmann
3780 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3781 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
3782 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3783 1651d116 Michael Hanselmann
                      output=logfile)
3784 1651d116 Michael Hanselmann
3785 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
3786 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
3787 1651d116 Michael Hanselmann
3788 1651d116 Michael Hanselmann
  except Exception:
3789 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
3790 1651d116 Michael Hanselmann
    raise
3791 1651d116 Michael Hanselmann
3792 1651d116 Michael Hanselmann
3793 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
3794 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
3795 1651d116 Michael Hanselmann

3796 1651d116 Michael Hanselmann
  @type names: sequence
3797 1651d116 Michael Hanselmann
  @param names: List of names
3798 1651d116 Michael Hanselmann
  @rtype: List of dicts
3799 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3800 1651d116 Michael Hanselmann
           status couldn't be read
3801 1651d116 Michael Hanselmann

3802 1651d116 Michael Hanselmann
  """
3803 1651d116 Michael Hanselmann
  result = []
3804 1651d116 Michael Hanselmann
3805 1651d116 Michael Hanselmann
  for name in names:
3806 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3807 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3808 1651d116 Michael Hanselmann
3809 1651d116 Michael Hanselmann
    try:
3810 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3811 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3812 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3813 1651d116 Michael Hanselmann
        raise
3814 1651d116 Michael Hanselmann
      data = None
3815 1651d116 Michael Hanselmann
3816 1651d116 Michael Hanselmann
    if not data:
3817 1651d116 Michael Hanselmann
      result.append(None)
3818 1651d116 Michael Hanselmann
      continue
3819 1651d116 Michael Hanselmann
3820 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3821 1651d116 Michael Hanselmann
3822 1651d116 Michael Hanselmann
  return result
3823 1651d116 Michael Hanselmann
3824 1651d116 Michael Hanselmann
3825 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3826 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3827 f81c4737 Michael Hanselmann

3828 f81c4737 Michael Hanselmann
  """
3829 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3830 f81c4737 Michael Hanselmann
3831 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3832 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3833 f81c4737 Michael Hanselmann
3834 f81c4737 Michael Hanselmann
  if pid:
3835 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3836 f81c4737 Michael Hanselmann
                 name, pid)
3837 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3838 f81c4737 Michael Hanselmann
3839 f81c4737 Michael Hanselmann
3840 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3841 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3842 1651d116 Michael Hanselmann

3843 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3844 1651d116 Michael Hanselmann
  whole status directory is removed.
3845 1651d116 Michael Hanselmann

3846 1651d116 Michael Hanselmann
  """
3847 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3848 1651d116 Michael Hanselmann
3849 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3850 1651d116 Michael Hanselmann
3851 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3852 1651d116 Michael Hanselmann
3853 1651d116 Michael Hanselmann
  if pid:
3854 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3855 1651d116 Michael Hanselmann
                 name, pid)
3856 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3857 1651d116 Michael Hanselmann
3858 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3859 1651d116 Michael Hanselmann
3860 1651d116 Michael Hanselmann
3861 235a6b29 Thomas Thrainer
def _SetPhysicalId(target_node_uuid, nodes_ip, disks):
3862 235a6b29 Thomas Thrainer
  """Sets the correct physical ID on all passed disks.
3863 6b93ec9d Iustin Pop

3864 6b93ec9d Iustin Pop
  """
3865 6b93ec9d Iustin Pop
  for cf in disks:
3866 1c3231aa Thomas Thrainer
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3867 6b93ec9d Iustin Pop
3868 235a6b29 Thomas Thrainer
3869 235a6b29 Thomas Thrainer
def _FindDisks(target_node_uuid, nodes_ip, disks):
3870 235a6b29 Thomas Thrainer
  """Sets the physical ID on disks and returns the block devices.
3871 235a6b29 Thomas Thrainer

3872 235a6b29 Thomas Thrainer
  """
3873 235a6b29 Thomas Thrainer
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3874 235a6b29 Thomas Thrainer
3875 6b93ec9d Iustin Pop
  bdevs = []
3876 6b93ec9d Iustin Pop
3877 6b93ec9d Iustin Pop
  for cf in disks:
3878 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3879 6b93ec9d Iustin Pop
    if rd is None:
3880 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3881 6b93ec9d Iustin Pop
    bdevs.append(rd)
3882 5a533f8a Iustin Pop
  return bdevs
3883 6b93ec9d Iustin Pop
3884 6b93ec9d Iustin Pop
3885 1c3231aa Thomas Thrainer
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3886 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3887 6b93ec9d Iustin Pop

3888 6b93ec9d Iustin Pop
  """
3889 1c3231aa Thomas Thrainer
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3890 6b93ec9d Iustin Pop
3891 6b93ec9d Iustin Pop
  # disconnect disks
3892 6b93ec9d Iustin Pop
  for rd in bdevs:
3893 6b93ec9d Iustin Pop
    try:
3894 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3895 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3896 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3897 2cc6781a Iustin Pop
            err, exc=True)
3898 6b93ec9d Iustin Pop
3899 6b93ec9d Iustin Pop
3900 1c3231aa Thomas Thrainer
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3901 1c3231aa Thomas Thrainer
                  multimaster):
3902 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3903 6b93ec9d Iustin Pop

3904 6b93ec9d Iustin Pop
  """
3905 1c3231aa Thomas Thrainer
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3906 6b93ec9d Iustin Pop
3907 6b93ec9d Iustin Pop
  if multimaster:
3908 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3909 6b93ec9d Iustin Pop
      try:
3910 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3911 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3912 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3913 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3914 6b93ec9d Iustin Pop
  # needed primary mode
3915 6b93ec9d Iustin Pop
  for rd in bdevs:
3916 6b93ec9d Iustin Pop
    try:
3917 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3918 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3919 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3920 3c0cdc83 Michael Hanselmann
3921 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3922 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3923 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3924 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3925 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3926 3c0cdc83 Michael Hanselmann
3927 3c0cdc83 Michael Hanselmann
  def _Attach():
3928 6b93ec9d Iustin Pop
    all_connected = True
3929 3c0cdc83 Michael Hanselmann
3930 6b93ec9d Iustin Pop
    for rd in bdevs:
3931 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3932 3c0cdc83 Michael Hanselmann
3933 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3934 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3935 3c0cdc83 Michael Hanselmann
3936 6b93ec9d Iustin Pop
      if stats.is_standalone:
3937 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3938 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3939 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3940 6b93ec9d Iustin Pop
        try:
3941 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3942 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3943 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3944 3c0cdc83 Michael Hanselmann
3945 3c0cdc83 Michael Hanselmann
    if not all_connected:
3946 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3947 3c0cdc83 Michael Hanselmann
3948 3c0cdc83 Michael Hanselmann
  try:
3949 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3950 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3951 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3952 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3953 3c0cdc83 Michael Hanselmann
3954 6b93ec9d Iustin Pop
  if multimaster:
3955 6b93ec9d Iustin Pop
    # change to primary mode
3956 6b93ec9d Iustin Pop
    for rd in bdevs:
3957 d3da87b8 Iustin Pop
      try:
3958 d3da87b8 Iustin Pop
        rd.Open()
3959 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3960 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3961 6b93ec9d Iustin Pop
3962 6b93ec9d Iustin Pop
3963 1c3231aa Thomas Thrainer
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3964 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3965 6b93ec9d Iustin Pop

3966 6b93ec9d Iustin Pop
  """
3967 db8667b7 Iustin Pop
  def _helper(rd):
3968 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3969 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3970 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3971 db8667b7 Iustin Pop
    return stats
3972 db8667b7 Iustin Pop
3973 1c3231aa Thomas Thrainer
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3974 6b93ec9d Iustin Pop
3975 6b93ec9d Iustin Pop
  min_resync = 100
3976 6b93ec9d Iustin Pop
  alldone = True
3977 6b93ec9d Iustin Pop
  for rd in bdevs:
3978 db8667b7 Iustin Pop
    try:
3979 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3980 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3981 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3982 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3983 db8667b7 Iustin Pop
      # last check
3984 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3985 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3986 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3987 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3988 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3989 afdc3985 Iustin Pop
3990 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3991 6b93ec9d Iustin Pop
3992 6b93ec9d Iustin Pop
3993 235a6b29 Thomas Thrainer
def DrbdNeedsActivation(target_node_uuid, nodes_ip, disks):
3994 235a6b29 Thomas Thrainer
  """Checks which of the passed disks needs activation and returns their UUIDs.
3995 235a6b29 Thomas Thrainer

3996 235a6b29 Thomas Thrainer
  """
3997 235a6b29 Thomas Thrainer
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3998 235a6b29 Thomas Thrainer
  faulty_disks = []
3999 235a6b29 Thomas Thrainer
4000 235a6b29 Thomas Thrainer
  for disk in disks:
4001 235a6b29 Thomas Thrainer
    rd = _RecursiveFindBD(disk)
4002 235a6b29 Thomas Thrainer
    if rd is None:
4003 235a6b29 Thomas Thrainer
      faulty_disks.append(disk)
4004 235a6b29 Thomas Thrainer
      continue
4005 235a6b29 Thomas Thrainer
4006 235a6b29 Thomas Thrainer
    stats = rd.GetProcStatus()
4007 235a6b29 Thomas Thrainer
    if stats.is_standalone or stats.is_diskless:
4008 235a6b29 Thomas Thrainer
      faulty_disks.append(disk)
4009 235a6b29 Thomas Thrainer
4010 235a6b29 Thomas Thrainer
  return [disk.uuid for disk in faulty_disks]
4011 235a6b29 Thomas Thrainer
4012 235a6b29 Thomas Thrainer
4013 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
4014 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
4015 c46b9782 Luca Bigliardi

4016 c46b9782 Luca Bigliardi
  """
4017 c46b9782 Luca Bigliardi
  try:
4018 47e0abee Thomas Thrainer
    return drbd.DRBD8.GetUsermodeHelper()
4019 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
4020 c46b9782 Luca Bigliardi
    _Fail(str(err))
4021 c46b9782 Luca Bigliardi
4022 c46b9782 Luca Bigliardi
4023 8ef418bb Helga Velroyen
def PowercycleNode(hypervisor_type, hvparams=None):
4024 f5118ade Iustin Pop
  """Hard-powercycle the node.
4025 f5118ade Iustin Pop

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

4029 f5118ade Iustin Pop
  """
4030 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4031 f5118ade Iustin Pop
  try:
4032 f5118ade Iustin Pop
    pid = os.fork()
4033 29921401 Iustin Pop
  except OSError:
4034 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
4035 f5118ade Iustin Pop
    pid = 0
4036 f5118ade Iustin Pop
  if pid > 0:
4037 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
4038 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
4039 1af6ac0f Luca Bigliardi
  try:
4040 1af6ac0f Luca Bigliardi
    utils.Mlockall()
4041 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
4042 1af6ac0f Luca Bigliardi
    pass
4043 f5118ade Iustin Pop
  time.sleep(5)
4044 8ef418bb Helga Velroyen
  hyper.PowercycleNode(hvparams=hvparams)
4045 f5118ade Iustin Pop
4046 f5118ade Iustin Pop
4047 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
4048 45bc4635 Iustin Pop
  """Verifies a restricted command name.
4049 1a2eb2dc Michael Hanselmann

4050 1a2eb2dc Michael Hanselmann
  @type cmd: string
4051 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4052 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
4053 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4054 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
4055 1a2eb2dc Michael Hanselmann

4056 1a2eb2dc Michael Hanselmann
  """
4057 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
4058 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
4059 1a2eb2dc Michael Hanselmann
4060 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
4061 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
4062 1a2eb2dc Michael Hanselmann
4063 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4064 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
4065 1a2eb2dc Michael Hanselmann
4066 1a2eb2dc Michael Hanselmann
  return (True, None)
4067 1a2eb2dc Michael Hanselmann
4068 1a2eb2dc Michael Hanselmann
4069 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
4070 45bc4635 Iustin Pop
  """Common checks for restricted command file system directories and files.
4071 1a2eb2dc Michael Hanselmann

4072 1a2eb2dc Michael Hanselmann
  @type path: string
4073 1a2eb2dc Michael Hanselmann
  @param path: Path to check
4074 1a2eb2dc Michael Hanselmann
  @param owner: C{None} or tuple containing UID and GID
4075 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or C{os.stat} result)
4076 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4077 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's the result of C{os.stat}
4078 1a2eb2dc Michael Hanselmann

4079 1a2eb2dc Michael Hanselmann
  """
4080 1a2eb2dc Michael Hanselmann
  if owner is None:
4081 1a2eb2dc Michael Hanselmann
    # Default to root as owner
4082 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
4083 1a2eb2dc Michael Hanselmann
4084 1a2eb2dc Michael Hanselmann
  try:
4085 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
4086 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
4087 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4088 1a2eb2dc Michael Hanselmann
4089 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
4090 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
4091 1a2eb2dc Michael Hanselmann
4092 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
4093 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
4094 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4095 1a2eb2dc Michael Hanselmann
4096 1a2eb2dc Michael Hanselmann
  return (True, st)
4097 1a2eb2dc Michael Hanselmann
4098 1a2eb2dc Michael Hanselmann
4099 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4100 45bc4635 Iustin Pop
  """Verifies restricted command directory.
4101 1a2eb2dc Michael Hanselmann

4102 1a2eb2dc Michael Hanselmann
  @type path: string
4103 1a2eb2dc Michael Hanselmann
  @param path: Path to check
4104 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
4105 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4106 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
4107 1a2eb2dc Michael Hanselmann

4108 1a2eb2dc Michael Hanselmann
  """
4109 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4110 1a2eb2dc Michael Hanselmann
4111 1a2eb2dc Michael Hanselmann
  if not status:
4112 1a2eb2dc Michael Hanselmann
    return (False, value)
4113 1a2eb2dc Michael Hanselmann
4114 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
4115 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
4116 1a2eb2dc Michael Hanselmann
4117 1a2eb2dc Michael Hanselmann
  return (True, None)
4118 1a2eb2dc Michael Hanselmann
4119 1a2eb2dc Michael Hanselmann
4120 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4121 45bc4635 Iustin Pop
  """Verifies a whole restricted command and returns its executable filename.
4122 1a2eb2dc Michael Hanselmann

4123 1a2eb2dc Michael Hanselmann
  @type path: string
4124 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
4125 1a2eb2dc Michael Hanselmann
  @type cmd: string
4126 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4127 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
4128 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4129 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
4130 1a2eb2dc Michael Hanselmann
    absolute path to the executable
4131 1a2eb2dc Michael Hanselmann

4132 1a2eb2dc Michael Hanselmann
  """
4133 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
4134 1a2eb2dc Michael Hanselmann
4135 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4136 1a2eb2dc Michael Hanselmann
4137 1a2eb2dc Michael Hanselmann
  if not status:
4138 1a2eb2dc Michael Hanselmann
    return (False, msg)
4139 1a2eb2dc Michael Hanselmann
4140 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
4141 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4142 1a2eb2dc Michael Hanselmann
4143 1a2eb2dc Michael Hanselmann
  return (True, executable)
4144 1a2eb2dc Michael Hanselmann
4145 1a2eb2dc Michael Hanselmann
4146 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
4147 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4148 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
4149 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
4150 45bc4635 Iustin Pop
  """Performs a number of tests on a restricted command.
4151 1a2eb2dc Michael Hanselmann

4152 1a2eb2dc Michael Hanselmann
  @type path: string
4153 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
4154 1a2eb2dc Michael Hanselmann
  @type cmd: string
4155 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4156 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
4157 1a2eb2dc Michael Hanselmann

4158 1a2eb2dc Michael Hanselmann
  """
4159 1a2eb2dc Michael Hanselmann
  # Verify the directory first
4160 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
4161 1a2eb2dc Michael Hanselmann
  if status:
4162 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
4163 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
4164 1a2eb2dc Michael Hanselmann
4165 1a2eb2dc Michael Hanselmann
  if not status:
4166 1a2eb2dc Michael Hanselmann
    return (False, msg)
4167 1a2eb2dc Michael Hanselmann
4168 1a2eb2dc Michael Hanselmann
  # Check actual executable
4169 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
4170 1a2eb2dc Michael Hanselmann
4171 1a2eb2dc Michael Hanselmann
4172 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
4173 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4174 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4175 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4176 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
4177 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
4178 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
4179 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4180 45bc4635 Iustin Pop
  """Executes a restricted command after performing strict tests.
4181 1a2eb2dc Michael Hanselmann

4182 1a2eb2dc Michael Hanselmann
  @type cmd: string
4183 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4184 1a2eb2dc Michael Hanselmann
  @rtype: string
4185 1a2eb2dc Michael Hanselmann
  @return: Command output
4186 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
4187 1a2eb2dc Michael Hanselmann

4188 1a2eb2dc Michael Hanselmann
  """
4189 45bc4635 Iustin Pop
  logging.info("Preparing to run restricted command '%s'", cmd)
4190 1a2eb2dc Michael Hanselmann
4191 1a2eb2dc Michael Hanselmann
  if not _enabled:
4192 45bc4635 Iustin Pop
    _Fail("Restricted commands disabled at configure time")
4193 1a2eb2dc Michael Hanselmann
4194 1a2eb2dc Michael Hanselmann
  lock = None
4195 1a2eb2dc Michael Hanselmann
  try:
4196 1a2eb2dc Michael Hanselmann
    cmdresult = None
4197 1a2eb2dc Michael Hanselmann
    try:
4198 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
4199 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4200 1a2eb2dc Michael Hanselmann
4201 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
4202 1a2eb2dc Michael Hanselmann
4203 1a2eb2dc Michael Hanselmann
      if status:
4204 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4205 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
4206 1a2eb2dc Michael Hanselmann
      else:
4207 1a2eb2dc Michael Hanselmann
        logging.error(value)
4208 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
4209 1a2eb2dc Michael Hanselmann
      # Keep original error in log
4210 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
4211 1a2eb2dc Michael Hanselmann
4212 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
4213 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
4214 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
4215 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
4216 1a2eb2dc Michael Hanselmann
4217 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
4218 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
4219 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
4220 45bc4635 Iustin Pop
      _Fail("Restricted command '%s' failed: %s; output: %s",
4221 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
4222 1a2eb2dc Michael Hanselmann
    else:
4223 1a2eb2dc Michael Hanselmann
      return cmdresult.output
4224 1a2eb2dc Michael Hanselmann
  finally:
4225 1a2eb2dc Michael Hanselmann
    if lock is not None:
4226 1a2eb2dc Michael Hanselmann
      # Release lock at last
4227 1a2eb2dc Michael Hanselmann
      lock.Close()
4228 1a2eb2dc Michael Hanselmann
      lock = None
4229 1a2eb2dc Michael Hanselmann
4230 1a2eb2dc Michael Hanselmann
4231 99e222b1 Michael Hanselmann
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4232 99e222b1 Michael Hanselmann
  """Creates or removes the watcher pause file.
4233 99e222b1 Michael Hanselmann

4234 99e222b1 Michael Hanselmann
  @type until: None or number
4235 99e222b1 Michael Hanselmann
  @param until: Unix timestamp saying until when the watcher shouldn't run
4236 99e222b1 Michael Hanselmann

4237 99e222b1 Michael Hanselmann
  """
4238 99e222b1 Michael Hanselmann
  if until is None:
4239 99e222b1 Michael Hanselmann
    logging.info("Received request to no longer pause watcher")
4240 99e222b1 Michael Hanselmann
    utils.RemoveFile(_filename)
4241 99e222b1 Michael Hanselmann
  else:
4242 99e222b1 Michael Hanselmann
    logging.info("Received request to pause watcher until %s", until)
4243 99e222b1 Michael Hanselmann
4244 99e222b1 Michael Hanselmann
    if not ht.TNumber(until):
4245 99e222b1 Michael Hanselmann
      _Fail("Duration must be numeric")
4246 99e222b1 Michael Hanselmann
4247 99e222b1 Michael Hanselmann
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
4248 99e222b1 Michael Hanselmann
4249 99e222b1 Michael Hanselmann
4250 a8083063 Iustin Pop
class HooksRunner(object):
4251 a8083063 Iustin Pop
  """Hook runner.
4252 a8083063 Iustin Pop

4253 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
4254 10c2650b Iustin Pop
  on the master side.
4255 a8083063 Iustin Pop

4256 a8083063 Iustin Pop
  """
4257 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
4258 a8083063 Iustin Pop
    """Constructor for hooks runner.
4259 a8083063 Iustin Pop

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

4264 a8083063 Iustin Pop
    """
4265 a8083063 Iustin Pop
    if hooks_base_dir is None:
4266 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4267 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4268 fe267188 Iustin Pop
    # constant
4269 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4270 a8083063 Iustin Pop
4271 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
4272 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
4273 0fa481f5 Andrea Spadaccini

4274 0fa481f5 Andrea Spadaccini
    """
4275 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
4276 0fa481f5 Andrea Spadaccini
    node = node_list[0]
4277 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
4278 0fa481f5 Andrea Spadaccini
    assert node == myself
4279 0fa481f5 Andrea Spadaccini
4280 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
4281 0fa481f5 Andrea Spadaccini
4282 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
4283 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
4284 0fa481f5 Andrea Spadaccini
4285 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
4286 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
4287 a8083063 Iustin Pop

4288 10c2650b Iustin Pop
    @type hpath: str
4289 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
4290 10c2650b Iustin Pop
        holds the scripts
4291 10c2650b Iustin Pop
    @type phase: str
4292 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4293 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
4294 10c2650b Iustin Pop
    @type env: dict
4295 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
4296 10c2650b Iustin Pop
    @rtype: list
4297 10c2650b Iustin Pop
    @return: list of 3-element tuples:
4298 10c2650b Iustin Pop
      - script path
4299 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
4300 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
4301 10c2650b Iustin Pop
      - output of the script
4302 10c2650b Iustin Pop

4303 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
4304 10c2650b Iustin Pop
        parameters
4305 a8083063 Iustin Pop

4306 a8083063 Iustin Pop
    """
4307 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
4308 a8083063 Iustin Pop
      suffix = "pre"
4309 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
4310 a8083063 Iustin Pop
      suffix = "post"
4311 a8083063 Iustin Pop
    else:
4312 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
4313 3fb4f740 Iustin Pop
4314 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
4315 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4316 6bb65e3a Guido Trotter
4317 6bb65e3a Guido Trotter
    results = []
4318 a9b7e346 Iustin Pop
4319 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
4320 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
4321 a9b7e346 Iustin Pop
      # warning at every operation
4322 a9b7e346 Iustin Pop
      return results
4323 a9b7e346 Iustin Pop
4324 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4325 a9b7e346 Iustin Pop
4326 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
4327 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
4328 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
4329 a8083063 Iustin Pop
        output = ""
4330 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
4331 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
4332 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
4333 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
4334 6bb65e3a Guido Trotter
        if runresult.failed:
4335 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
4336 a8083063 Iustin Pop
        else:
4337 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
4338 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
4339 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4340 6bb65e3a Guido Trotter
4341 6bb65e3a Guido Trotter
    return results
4342 3f78eef2 Iustin Pop
4343 3f78eef2 Iustin Pop
4344 8d528b7c Iustin Pop
class IAllocatorRunner(object):
4345 8d528b7c Iustin Pop
  """IAllocator runner.
4346 8d528b7c Iustin Pop

4347 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
4348 8d528b7c Iustin Pop
  the master side.
4349 8d528b7c Iustin Pop

4350 8d528b7c Iustin Pop
  """
4351 7e950d31 Iustin Pop
  @staticmethod
4352 7e950d31 Iustin Pop
  def Run(name, idata):
4353 8d528b7c Iustin Pop
    """Run an iallocator script.
4354 8d528b7c Iustin Pop

4355 10c2650b Iustin Pop
    @type name: str
4356 10c2650b Iustin Pop
    @param name: the iallocator script name
4357 10c2650b Iustin Pop
    @type idata: str
4358 10c2650b Iustin Pop
    @param idata: the allocator input data
4359 10c2650b Iustin Pop

4360 10c2650b Iustin Pop
    @rtype: tuple
4361 87f5c298 Iustin Pop
    @return: two element tuple of:
4362 87f5c298 Iustin Pop
       - status
4363 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
4364 8d528b7c Iustin Pop

4365 8d528b7c Iustin Pop
    """
4366 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4367 8d528b7c Iustin Pop
                                  os.path.isfile)
4368 8d528b7c Iustin Pop
    if alloc_script is None:
4369 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
4370 8d528b7c Iustin Pop
4371 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4372 8d528b7c Iustin Pop
    try:
4373 8d528b7c Iustin Pop
      os.write(fd, idata)
4374 8d528b7c Iustin Pop
      os.close(fd)
4375 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
4376 8d528b7c Iustin Pop
      if result.failed:
4377 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4378 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
4379 8d528b7c Iustin Pop
    finally:
4380 8d528b7c Iustin Pop
      os.unlink(fin_name)
4381 8d528b7c Iustin Pop
4382 c26a6bd2 Iustin Pop
    return result.stdout
4383 8d528b7c Iustin Pop
4384 8d528b7c Iustin Pop
4385 3f78eef2 Iustin Pop
class DevCacheManager(object):
4386 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
4387 3f78eef2 Iustin Pop

4388 3f78eef2 Iustin Pop
  """
4389 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
4390 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4391 3f78eef2 Iustin Pop
4392 3f78eef2 Iustin Pop
  @classmethod
4393 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
4394 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
4395 3f78eef2 Iustin Pop

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

4399 10c2650b Iustin Pop
    @type dev_path: str
4400 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
4401 10c2650b Iustin Pop
    @rtype: str
4402 10c2650b Iustin Pop
    @return: the converted path name
4403 3f78eef2 Iustin Pop

4404 3f78eef2 Iustin Pop
    """
4405 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
4406 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4407 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
4408 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4409 3f78eef2 Iustin Pop
    return fpath
4410 3f78eef2 Iustin Pop
4411 3f78eef2 Iustin Pop
  @classmethod
4412 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4413 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
4414 3f78eef2 Iustin Pop

4415 10c2650b Iustin Pop
    @type dev_path: str
4416 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4417 10c2650b Iustin Pop
    @type owner: str
4418 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
4419 10c2650b Iustin Pop
    @type on_primary: bool
4420 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
4421 10c2650b Iustin Pop
        node nor not
4422 10c2650b Iustin Pop
    @type iv_name: str
4423 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
4424 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
4425 10c2650b Iustin Pop

4426 10c2650b Iustin Pop
    @rtype: None
4427 10c2650b Iustin Pop

4428 3f78eef2 Iustin Pop
    """
4429 cf5a8306 Iustin Pop
    if dev_path is None:
4430 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4431 cf5a8306 Iustin Pop
      return
4432 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4433 3f78eef2 Iustin Pop
    if on_primary:
4434 3f78eef2 Iustin Pop
      state = "primary"
4435 3f78eef2 Iustin Pop
    else:
4436 3f78eef2 Iustin Pop
      state = "secondary"
4437 3f78eef2 Iustin Pop
    if iv_name is None:
4438 3f78eef2 Iustin Pop
      iv_name = "not_visible"
4439 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4440 3f78eef2 Iustin Pop
    try:
4441 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
4442 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4443 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4444 3f78eef2 Iustin Pop
4445 3f78eef2 Iustin Pop
  @classmethod
4446 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
4447 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
4448 3f78eef2 Iustin Pop

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

4452 10c2650b Iustin Pop
    @type dev_path: str
4453 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4454 10c2650b Iustin Pop

4455 10c2650b Iustin Pop
    @rtype: None
4456 10c2650b Iustin Pop

4457 3f78eef2 Iustin Pop
    """
4458 cf5a8306 Iustin Pop
    if dev_path is None:
4459 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4460 cf5a8306 Iustin Pop
      return
4461 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4462 3f78eef2 Iustin Pop
    try:
4463 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
4464 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4465 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)