Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ bc57fa8d

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

114 2cc6781a Iustin Pop
  Its argument is the error message.
115 2cc6781a Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

466 fb460cf7 Andrea Spadaccini
  @rtype: None
467 fb460cf7 Andrea Spadaccini

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

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

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

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

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

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

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

542 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
543 b989b9d9 Ken Wehr

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

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

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

602 3c8a599a Helga Velroyen
  @see: C{_CheckStorageParams}
603 3c8a599a Helga Velroyen

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

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

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

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

652 a18ab868 Helga Velroyen
  @see: C{_GetLvmVgSpaceInfo}
653 3c8a599a Helga Velroyen

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

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

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

688 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
689 78519c10 Michael Hanselmann

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

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

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

707 439e1d3f Helga Velroyen
  See C{_GetHvInfo} for information on the output.
708 439e1d3f Helga Velroyen

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

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

725 78519c10 Michael Hanselmann
  @rtype: None or dict
726 78519c10 Michael Hanselmann

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

949 e69d05fd Iustin Pop
  @type what: C{dict}
950 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
951 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
952 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
953 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
954 e69d05fd Iustin Pop
        connectivity with
955 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
956 5b0dfcef Helga Velroyen
  @type cluster_name: string
957 5b0dfcef Helga Velroyen
  @param cluster_name: the cluster's name
958 5b0dfcef Helga Velroyen
  @type all_hvparams: dict of dict of strings
959 5b0dfcef Helga Velroyen
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
960 a9f33339 Petr Pudlak
  @type node_groups: a dict of strings
961 a9f33339 Petr Pudlak
  @param node_groups: node _names_ mapped to their group uuids (it's enough to
962 a9f33339 Petr Pudlak
      have only those nodes that are in `what["nodelist"]`)
963 a9f33339 Petr Pudlak
  @type groups_cfg: a dict of dict of strings
964 a9f33339 Petr Pudlak
  @param groups_cfg: a dictionary mapping group uuids to their configuration
965 10c2650b Iustin Pop
  @rtype: dict
966 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
967 10c2650b Iustin Pop
      values representing the result of the checks
968 a8083063 Iustin Pop

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

1167 2be7273c Apollon Oikonomopoulos
  @type devices: list
1168 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
1169 2be7273c Apollon Oikonomopoulos
  @rtype: dict
1170 2be7273c Apollon Oikonomopoulos
  @return:
1171 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
1172 2be7273c Apollon Oikonomopoulos
    size in MiB.
1173 2be7273c Apollon Oikonomopoulos

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

1176 2be7273c Apollon Oikonomopoulos
  """
1177 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
1178 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
1179 2be7273c Apollon Oikonomopoulos
1180 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
1181 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1182 2be7273c Apollon Oikonomopoulos
      continue
1183 2be7273c Apollon Oikonomopoulos
1184 2be7273c Apollon Oikonomopoulos
    try:
1185 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
1186 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
1187 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1188 2be7273c Apollon Oikonomopoulos
      continue
1189 2be7273c Apollon Oikonomopoulos
1190 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
1191 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1192 2be7273c Apollon Oikonomopoulos
      if result.failed:
1193 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
1194 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
1195 2be7273c Apollon Oikonomopoulos
        continue
1196 2be7273c Apollon Oikonomopoulos
1197 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
1198 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
1199 2be7273c Apollon Oikonomopoulos
  return blockdevs
1200 2be7273c Apollon Oikonomopoulos
1201 2be7273c Apollon Oikonomopoulos
1202 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
1203 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
1204 a8083063 Iustin Pop

1205 84d7e26b Dmitry Chernyak
  @type vg_names: list
1206 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
1207 397693d3 Iustin Pop
      empty for all volume groups
1208 10c2650b Iustin Pop
  @rtype: dict
1209 10c2650b Iustin Pop
  @return:
1210 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
1211 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
1212 10c2650b Iustin Pop

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

1215 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
1216 10c2650b Iustin Pop
      details.
1217 a8083063 Iustin Pop

1218 a8083063 Iustin Pop
  """
1219 cb2037a2 Iustin Pop
  lvs = {}
1220 d0c8c01d Iustin Pop
  sep = "|"
1221 397693d3 Iustin Pop
  if not vg_names:
1222 397693d3 Iustin Pop
    vg_names = []
1223 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1224 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
1225 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1226 a8083063 Iustin Pop
  if result.failed:
1227 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1228 cb2037a2 Iustin Pop
1229 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
1230 df4c2628 Iustin Pop
    line = line.strip()
1231 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
1232 df4c2628 Iustin Pop
    if not match:
1233 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
1234 df4c2628 Iustin Pop
      continue
1235 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
1236 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
1237 d0c8c01d Iustin Pop
    online = attr[5] == "o"
1238 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
1239 33f2a81a Iustin Pop
    if virtual:
1240 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
1241 33f2a81a Iustin Pop
      # don't really hold data
1242 33f2a81a Iustin Pop
      continue
1243 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
1244 cb2037a2 Iustin Pop
1245 cb2037a2 Iustin Pop
  return lvs
1246 a8083063 Iustin Pop
1247 a8083063 Iustin Pop
1248 a8083063 Iustin Pop
def ListVolumeGroups():
1249 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
1250 a8083063 Iustin Pop

1251 10c2650b Iustin Pop
  @rtype: dict
1252 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
1253 10c2650b Iustin Pop
      size of the volume
1254 a8083063 Iustin Pop

1255 a8083063 Iustin Pop
  """
1256 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
1257 a8083063 Iustin Pop
1258 a8083063 Iustin Pop
1259 dcb93971 Michael Hanselmann
def NodeVolumes():
1260 dcb93971 Michael Hanselmann
  """List all volumes on this node.
1261 dcb93971 Michael Hanselmann

1262 10c2650b Iustin Pop
  @rtype: list
1263 10c2650b Iustin Pop
  @return:
1264 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
1265 10c2650b Iustin Pop
      - name: the logical volume name,
1266 10c2650b Iustin Pop
      - size: the size of the logical volume
1267 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
1268 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
1269 10c2650b Iustin Pop

1270 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
1271 10c2650b Iustin Pop
    error.
1272 10c2650b Iustin Pop

1273 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
1274 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
1275 10c2650b Iustin Pop
    multiple times.
1276 10c2650b Iustin Pop

1277 dcb93971 Michael Hanselmann
  """
1278 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1279 dcb93971 Michael Hanselmann
                         "--separator=|",
1280 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
1281 dcb93971 Michael Hanselmann
  if result.failed:
1282 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
1283 10bfe6cb Iustin Pop
          result.output)
1284 dcb93971 Michael Hanselmann
1285 dcb93971 Michael Hanselmann
  def parse_dev(dev):
1286 d0c8c01d Iustin Pop
    return dev.split("(")[0]
1287 89e5ab02 Iustin Pop
1288 89e5ab02 Iustin Pop
  def handle_dev(dev):
1289 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
1290 dcb93971 Michael Hanselmann
1291 dcb93971 Michael Hanselmann
  def map_line(line):
1292 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
1293 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
1294 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1295 89e5ab02 Iustin Pop
1296 89e5ab02 Iustin Pop
  all_devs = []
1297 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
1298 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
1299 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
1300 89e5ab02 Iustin Pop
    else:
1301 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
1302 89e5ab02 Iustin Pop
  return all_devs
1303 dcb93971 Michael Hanselmann
1304 dcb93971 Michael Hanselmann
1305 a8083063 Iustin Pop
def BridgesExist(bridges_list):
1306 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
1307 a8083063 Iustin Pop

1308 b1206984 Iustin Pop
  @rtype: boolean
1309 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
1310 a8083063 Iustin Pop

1311 a8083063 Iustin Pop
  """
1312 35c0c8da Iustin Pop
  missing = []
1313 a8083063 Iustin Pop
  for bridge in bridges_list:
1314 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
1315 35c0c8da Iustin Pop
      missing.append(bridge)
1316 a8083063 Iustin Pop
1317 35c0c8da Iustin Pop
  if missing:
1318 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1319 35c0c8da Iustin Pop
1320 a8083063 Iustin Pop
1321 2bff1928 Helga Velroyen
def GetInstanceListForHypervisor(hname, hvparams=None,
1322 2bff1928 Helga Velroyen
                                 get_hv_fn=hypervisor.GetHypervisor):
1323 2bff1928 Helga Velroyen
  """Provides a list of instances of the given hypervisor.
1324 2bff1928 Helga Velroyen

1325 2bff1928 Helga Velroyen
  @type hname: string
1326 2bff1928 Helga Velroyen
  @param hname: name of the hypervisor
1327 2bff1928 Helga Velroyen
  @type hvparams: dict of strings
1328 2bff1928 Helga Velroyen
  @param hvparams: hypervisor parameters for the given hypervisor
1329 2bff1928 Helga Velroyen
  @type get_hv_fn: function
1330 2bff1928 Helga Velroyen
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1331 2bff1928 Helga Velroyen
    name; optional parameter to increase testability
1332 2bff1928 Helga Velroyen

1333 2bff1928 Helga Velroyen
  @rtype: list
1334 2bff1928 Helga Velroyen
  @return: a list of all running instances on the current node
1335 2bff1928 Helga Velroyen
    - instance1.example.com
1336 2bff1928 Helga Velroyen
    - instance2.example.com
1337 2bff1928 Helga Velroyen

1338 2bff1928 Helga Velroyen
  """
1339 2bff1928 Helga Velroyen
  results = []
1340 2bff1928 Helga Velroyen
  try:
1341 2bff1928 Helga Velroyen
    hv = get_hv_fn(hname)
1342 5b0dfcef Helga Velroyen
    names = hv.ListInstances(hvparams=hvparams)
1343 2bff1928 Helga Velroyen
    results.extend(names)
1344 2bff1928 Helga Velroyen
  except errors.HypervisorError, err:
1345 2bff1928 Helga Velroyen
    _Fail("Error enumerating instances (hypervisor %s): %s",
1346 2bff1928 Helga Velroyen
          hname, err, exc=True)
1347 2bff1928 Helga Velroyen
  return results
1348 2bff1928 Helga Velroyen
1349 2bff1928 Helga Velroyen
1350 fac83f8a Helga Velroyen
def GetInstanceList(hypervisor_list, all_hvparams=None,
1351 fac83f8a Helga Velroyen
                    get_hv_fn=hypervisor.GetHypervisor):
1352 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
1353 a8083063 Iustin Pop

1354 e69d05fd Iustin Pop
  @type hypervisor_list: list
1355 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
1356 fac83f8a Helga Velroyen
  @type all_hvparams: dict of dict of strings
1357 fac83f8a Helga Velroyen
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1358 fac83f8a Helga Velroyen
    cluster-wide hypervisor parameters
1359 fac83f8a Helga Velroyen
  @type get_hv_fn: function
1360 fac83f8a Helga Velroyen
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1361 fac83f8a Helga Velroyen
    name; optional parameter to increase testability
1362 e69d05fd Iustin Pop

1363 e69d05fd Iustin Pop
  @rtype: list
1364 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
1365 10c2650b Iustin Pop
    - instance1.example.com
1366 10c2650b Iustin Pop
    - instance2.example.com
1367 a8083063 Iustin Pop

1368 098c0958 Michael Hanselmann
  """
1369 e69d05fd Iustin Pop
  results = []
1370 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1371 5b0dfcef Helga Velroyen
    hvparams = all_hvparams[hname]
1372 5b0dfcef Helga Velroyen
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1373 2bff1928 Helga Velroyen
                                                get_hv_fn=get_hv_fn))
1374 e69d05fd Iustin Pop
  return results
1375 a8083063 Iustin Pop
1376 a8083063 Iustin Pop
1377 0bbec3af Helga Velroyen
def GetInstanceInfo(instance, hname, hvparams=None):
1378 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
1379 a8083063 Iustin Pop

1380 e69d05fd Iustin Pop
  @type instance: string
1381 e69d05fd Iustin Pop
  @param instance: the instance name
1382 e69d05fd Iustin Pop
  @type hname: string
1383 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1384 0bbec3af Helga Velroyen
  @type hvparams: dict of strings
1385 0bbec3af Helga Velroyen
  @param hvparams: the instance's hvparams
1386 a8083063 Iustin Pop

1387 e69d05fd Iustin Pop
  @rtype: dict
1388 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1389 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1390 a3f0f306 Jose A. Lopes
      - state: state of instance (HvInstanceState)
1391 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1392 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1393 a8083063 Iustin Pop

1394 098c0958 Michael Hanselmann
  """
1395 a8083063 Iustin Pop
  output = {}
1396 a8083063 Iustin Pop
1397 0bbec3af Helga Velroyen
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1398 0bbec3af Helga Velroyen
                                                          hvparams=hvparams)
1399 a8083063 Iustin Pop
  if iinfo is not None:
1400 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1401 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1402 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1403 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1404 a8083063 Iustin Pop
1405 c26a6bd2 Iustin Pop
  return output
1406 a8083063 Iustin Pop
1407 a8083063 Iustin Pop
1408 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1409 3361ab37 Helga Velroyen
  """Computes whether an instance can be migrated.
1410 56e7640c Iustin Pop

1411 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1412 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1413 56e7640c Iustin Pop

1414 56e7640c Iustin Pop
  @rtype: tuple
1415 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1416 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1417 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1418 56e7640c Iustin Pop

1419 56e7640c Iustin Pop
  """
1420 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1421 afdc3985 Iustin Pop
  iname = instance.name
1422 3361ab37 Helga Velroyen
  if iname not in hyper.ListInstances(instance.hvparams):
1423 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1424 56e7640c Iustin Pop
1425 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1426 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1427 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1428 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1429 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1430 56e7640c Iustin Pop
1431 56e7640c Iustin Pop
1432 0200a1af Helga Velroyen
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1433 a8083063 Iustin Pop
  """Gather data about all instances.
1434 a8083063 Iustin Pop

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

1439 e69d05fd Iustin Pop
  @type hypervisor_list: list
1440 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1441 0200a1af Helga Velroyen
  @type all_hvparams: dict of dict of strings
1442 0200a1af Helga Velroyen
  @param all_hvparams: mapping of hypervisor names to hvparams
1443 e69d05fd Iustin Pop

1444 955db481 Guido Trotter
  @rtype: dict
1445 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1446 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1447 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1448 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1449 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1450 a8083063 Iustin Pop

1451 098c0958 Michael Hanselmann
  """
1452 a8083063 Iustin Pop
  output = {}
1453 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1454 0200a1af Helga Velroyen
    hvparams = all_hvparams[hname]
1455 0200a1af Helga Velroyen
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1456 e69d05fd Iustin Pop
    if iinfo:
1457 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1458 f23b5ae8 Iustin Pop
        value = {
1459 d0c8c01d Iustin Pop
          "memory": memory,
1460 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1461 d0c8c01d Iustin Pop
          "state": state,
1462 d0c8c01d Iustin Pop
          "time": times,
1463 e69d05fd Iustin Pop
          }
1464 b33b6f55 Iustin Pop
        if name in output:
1465 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1466 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1467 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1468 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1469 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1470 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1471 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1472 f23b5ae8 Iustin Pop
        output[name] = value
1473 a8083063 Iustin Pop
1474 c26a6bd2 Iustin Pop
  return output
1475 a8083063 Iustin Pop
1476 a8083063 Iustin Pop
1477 b9e12624 Hrvoje Ribicic
def GetInstanceConsoleInfo(instance_param_dict,
1478 b9e12624 Hrvoje Ribicic
                           get_hv_fn=hypervisor.GetHypervisor):
1479 b9e12624 Hrvoje Ribicic
  """Gather data about the console access of a set of instances of this node.
1480 b9e12624 Hrvoje Ribicic

1481 b9e12624 Hrvoje Ribicic
  This function assumes that the caller already knows which instances are on
1482 b9e12624 Hrvoje Ribicic
  this node, by calling a function such as L{GetAllInstancesInfo} or
1483 b9e12624 Hrvoje Ribicic
  L{GetInstanceList}.
1484 b9e12624 Hrvoje Ribicic

1485 b9e12624 Hrvoje Ribicic
  For every instance, a large amount of configuration data needs to be
1486 b9e12624 Hrvoje Ribicic
  provided to the hypervisor interface in order to receive the console
1487 b9e12624 Hrvoje Ribicic
  information. Whether this could or should be cut down can be discussed.
1488 b9e12624 Hrvoje Ribicic
  The information is provided in a dictionary indexed by instance name,
1489 b9e12624 Hrvoje Ribicic
  allowing any number of instance queries to be done.
1490 b9e12624 Hrvoje Ribicic

1491 b9e12624 Hrvoje Ribicic
  @type instance_param_dict: dict of string to tuple of dictionaries, where the
1492 c42be2c0 Petr Pudlak
    dictionaries represent: L{objects.Instance}, L{objects.Node},
1493 c42be2c0 Petr Pudlak
    L{objects.NodeGroup}, HvParams, BeParams
1494 b9e12624 Hrvoje Ribicic
  @param instance_param_dict: mapping of instance name to parameters necessary
1495 b9e12624 Hrvoje Ribicic
    for console information retrieval
1496 b9e12624 Hrvoje Ribicic

1497 b9e12624 Hrvoje Ribicic
  @rtype: dict
1498 b9e12624 Hrvoje Ribicic
  @return: dictionary of instance: data, with data having the following keys:
1499 b9e12624 Hrvoje Ribicic
      - instance: instance name
1500 b9e12624 Hrvoje Ribicic
      - kind: console kind
1501 b9e12624 Hrvoje Ribicic
      - message: used with kind == CONS_MESSAGE, indicates console to be
1502 b9e12624 Hrvoje Ribicic
                 unavailable, supplies error message
1503 b9e12624 Hrvoje Ribicic
      - host: host to connect to
1504 b9e12624 Hrvoje Ribicic
      - port: port to use
1505 b9e12624 Hrvoje Ribicic
      - user: user for login
1506 b9e12624 Hrvoje Ribicic
      - command: the command, broken into parts as an array
1507 b9e12624 Hrvoje Ribicic
      - display: unknown, potentially unused?
1508 b9e12624 Hrvoje Ribicic

1509 b9e12624 Hrvoje Ribicic
  """
1510 b9e12624 Hrvoje Ribicic
1511 b9e12624 Hrvoje Ribicic
  output = {}
1512 b9e12624 Hrvoje Ribicic
  for inst_name in instance_param_dict:
1513 b9e12624 Hrvoje Ribicic
    instance = instance_param_dict[inst_name]["instance"]
1514 b9e12624 Hrvoje Ribicic
    pnode = instance_param_dict[inst_name]["node"]
1515 c42be2c0 Petr Pudlak
    group = instance_param_dict[inst_name]["group"]
1516 b9e12624 Hrvoje Ribicic
    hvparams = instance_param_dict[inst_name]["hvParams"]
1517 b9e12624 Hrvoje Ribicic
    beparams = instance_param_dict[inst_name]["beParams"]
1518 b9e12624 Hrvoje Ribicic
1519 b9e12624 Hrvoje Ribicic
    instance = objects.Instance.FromDict(instance)
1520 b9e12624 Hrvoje Ribicic
    pnode = objects.Node.FromDict(pnode)
1521 c42be2c0 Petr Pudlak
    group = objects.NodeGroup.FromDict(group)
1522 b9e12624 Hrvoje Ribicic
1523 b9e12624 Hrvoje Ribicic
    h = get_hv_fn(instance.hypervisor)
1524 c42be2c0 Petr Pudlak
    output[inst_name] = h.GetInstanceConsole(instance, pnode, group,
1525 c42be2c0 Petr Pudlak
                                             hvparams, beparams).ToDict()
1526 b9e12624 Hrvoje Ribicic
1527 b9e12624 Hrvoje Ribicic
  return output
1528 b9e12624 Hrvoje Ribicic
1529 b9e12624 Hrvoje Ribicic
1530 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1531 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1532 81a3406c Iustin Pop

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

1536 81a3406c Iustin Pop
  @type kind: string
1537 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1538 81a3406c Iustin Pop
  @type os_name: string
1539 81a3406c Iustin Pop
  @param os_name: the os name
1540 81a3406c Iustin Pop
  @type instance: string
1541 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1542 6aa7a354 Iustin Pop
  @type component: string or None
1543 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1544 6aa7a354 Iustin Pop
      transferred
1545 81a3406c Iustin Pop

1546 81a3406c Iustin Pop
  """
1547 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1548 6aa7a354 Iustin Pop
  if component:
1549 6aa7a354 Iustin Pop
    assert "/" not in component
1550 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1551 6aa7a354 Iustin Pop
  else:
1552 6aa7a354 Iustin Pop
    c_msg = ""
1553 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1554 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1555 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1556 81a3406c Iustin Pop
1557 81a3406c Iustin Pop
1558 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1559 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1560 a8083063 Iustin Pop

1561 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1562 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1563 e557bae9 Guido Trotter
  @type reinstall: boolean
1564 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1565 4a0e011f Iustin Pop
  @type debug: integer
1566 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1567 c26a6bd2 Iustin Pop
  @rtype: None
1568 a8083063 Iustin Pop

1569 a8083063 Iustin Pop
  """
1570 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1571 255dcebd Iustin Pop
1572 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1573 e557bae9 Guido Trotter
  if reinstall:
1574 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1575 a8083063 Iustin Pop
1576 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1577 decd5f45 Iustin Pop
1578 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1579 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1580 decd5f45 Iustin Pop
  if result.failed:
1581 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1582 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1583 18682bca Iustin Pop
                  result.output)
1584 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1585 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1586 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1587 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1588 decd5f45 Iustin Pop
1589 decd5f45 Iustin Pop
1590 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1591 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1592 decd5f45 Iustin Pop

1593 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1594 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1595 d15a9ad3 Guido Trotter
  @type old_name: string
1596 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1597 4a0e011f Iustin Pop
  @type debug: integer
1598 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1599 10c2650b Iustin Pop
  @rtype: boolean
1600 10c2650b Iustin Pop
  @return: the success of the operation
1601 decd5f45 Iustin Pop

1602 decd5f45 Iustin Pop
  """
1603 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1604 decd5f45 Iustin Pop
1605 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1606 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1607 decd5f45 Iustin Pop
1608 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1609 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1610 a8083063 Iustin Pop
1611 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1612 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1613 a8083063 Iustin Pop
1614 a8083063 Iustin Pop
  if result.failed:
1615 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1616 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1617 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1618 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1619 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1620 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1621 a8083063 Iustin Pop
1622 a8083063 Iustin Pop
1623 3b721842 Michael Hanselmann
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1624 3b721842 Michael Hanselmann
  """Returns symlink path for block device.
1625 3b721842 Michael Hanselmann

1626 3b721842 Michael Hanselmann
  """
1627 3b721842 Michael Hanselmann
  if _dir is None:
1628 3b721842 Michael Hanselmann
    _dir = pathutils.DISK_LINKS_DIR
1629 3b721842 Michael Hanselmann
1630 3b721842 Michael Hanselmann
  return utils.PathJoin(_dir,
1631 3b721842 Michael Hanselmann
                        ("%s%s%s" %
1632 3b721842 Michael Hanselmann
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1633 5282084b Iustin Pop
1634 5282084b Iustin Pop
1635 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1636 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1637 9332fd8a Iustin Pop

1638 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1639 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1640 9332fd8a Iustin Pop

1641 9332fd8a Iustin Pop

1642 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1643 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1644 5282084b Iustin Pop
  @param idx: the disk index
1645 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1646 9332fd8a Iustin Pop

1647 9332fd8a Iustin Pop
  """
1648 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1649 9332fd8a Iustin Pop
  try:
1650 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1651 5282084b Iustin Pop
  except OSError, err:
1652 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1653 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1654 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1655 9332fd8a Iustin Pop
        os.remove(link_name)
1656 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1657 9332fd8a Iustin Pop
    else:
1658 9332fd8a Iustin Pop
      raise
1659 9332fd8a Iustin Pop
1660 9332fd8a Iustin Pop
  return link_name
1661 9332fd8a Iustin Pop
1662 9332fd8a Iustin Pop
1663 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1664 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1665 3c9c571d Iustin Pop

1666 3c9c571d Iustin Pop
  """
1667 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1668 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1669 5282084b Iustin Pop
    if os.path.islink(link_name):
1670 3c9c571d Iustin Pop
      try:
1671 03dfa658 Iustin Pop
        os.remove(link_name)
1672 03dfa658 Iustin Pop
      except OSError:
1673 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1674 3c9c571d Iustin Pop
1675 3c9c571d Iustin Pop
1676 66d3d195 Dimitris Aragiorgis
def _CalculateDeviceURI(instance, disk, device):
1677 66d3d195 Dimitris Aragiorgis
  """Get the URI for the device.
1678 66d3d195 Dimitris Aragiorgis

1679 66d3d195 Dimitris Aragiorgis
  @type instance: L{objects.Instance}
1680 66d3d195 Dimitris Aragiorgis
  @param instance: the instance which disk belongs to
1681 66d3d195 Dimitris Aragiorgis
  @type disk: L{objects.Disk}
1682 66d3d195 Dimitris Aragiorgis
  @param disk: the target disk object
1683 66d3d195 Dimitris Aragiorgis
  @type device: L{bdev.BlockDev}
1684 66d3d195 Dimitris Aragiorgis
  @param device: the corresponding BlockDevice
1685 66d3d195 Dimitris Aragiorgis
  @rtype: string
1686 66d3d195 Dimitris Aragiorgis
  @return: the device uri if any else None
1687 66d3d195 Dimitris Aragiorgis

1688 66d3d195 Dimitris Aragiorgis
  """
1689 66d3d195 Dimitris Aragiorgis
  access_mode = disk.params.get(constants.LDP_ACCESS,
1690 66d3d195 Dimitris Aragiorgis
                                constants.DISK_KERNELSPACE)
1691 66d3d195 Dimitris Aragiorgis
  if access_mode == constants.DISK_USERSPACE:
1692 66d3d195 Dimitris Aragiorgis
    # This can raise errors.BlockDeviceError
1693 66d3d195 Dimitris Aragiorgis
    return device.GetUserspaceAccessUri(instance.hypervisor)
1694 66d3d195 Dimitris Aragiorgis
  else:
1695 66d3d195 Dimitris Aragiorgis
    return None
1696 66d3d195 Dimitris Aragiorgis
1697 66d3d195 Dimitris Aragiorgis
1698 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1699 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1700 a8083063 Iustin Pop

1701 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1702 a8083063 Iustin Pop
  devices must be already assembled.
1703 a8083063 Iustin Pop

1704 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1705 5bd52dab Thomas Thrainer
  @param instance: the instance whose disks we should assemble
1706 069cfbf1 Iustin Pop
  @rtype: list
1707 66d3d195 Dimitris Aragiorgis
  @return: list of (disk_object, link_name, drive_uri)
1708 10c2650b Iustin Pop

1709 a8083063 Iustin Pop
  """
1710 a8083063 Iustin Pop
  block_devices = []
1711 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1712 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1713 a8083063 Iustin Pop
    if device is None:
1714 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1715 a8083063 Iustin Pop
                                    str(disk))
1716 a8083063 Iustin Pop
    device.Open()
1717 9332fd8a Iustin Pop
    try:
1718 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1719 9332fd8a Iustin Pop
    except OSError, e:
1720 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1721 9332fd8a Iustin Pop
                                    e.strerror)
1722 66d3d195 Dimitris Aragiorgis
    uri = _CalculateDeviceURI(instance, disk, device)
1723 9332fd8a Iustin Pop
1724 66d3d195 Dimitris Aragiorgis
    block_devices.append((disk, link_name, uri))
1725 9332fd8a Iustin Pop
1726 a8083063 Iustin Pop
  return block_devices
1727 a8083063 Iustin Pop
1728 a8083063 Iustin Pop
1729 1fa6fcba Michele Tartara
def StartInstance(instance, startup_paused, reason, store_reason=True):
1730 a8083063 Iustin Pop
  """Start an instance.
1731 a8083063 Iustin Pop

1732 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1733 e69d05fd Iustin Pop
  @param instance: the instance object
1734 323f9095 Stephen Shirley
  @type startup_paused: bool
1735 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1736 1fa6fcba Michele Tartara
  @type reason: list of reasons
1737 1fa6fcba Michele Tartara
  @param reason: the reason trail for this startup
1738 1fa6fcba Michele Tartara
  @type store_reason: boolean
1739 1fa6fcba Michele Tartara
  @param store_reason: whether to store the shutdown reason trail on file
1740 c26a6bd2 Iustin Pop
  @rtype: None
1741 a8083063 Iustin Pop

1742 098c0958 Michael Hanselmann
  """
1743 3361ab37 Helga Velroyen
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1744 3361ab37 Helga Velroyen
                                                   instance.hvparams)
1745 a8083063 Iustin Pop
1746 a8083063 Iustin Pop
  if instance.name in running_instances:
1747 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1748 c26a6bd2 Iustin Pop
    return
1749 a8083063 Iustin Pop
1750 a8083063 Iustin Pop
  try:
1751 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1752 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1753 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1754 1fa6fcba Michele Tartara
    if store_reason:
1755 1fa6fcba Michele Tartara
      _StoreInstReasonTrail(instance.name, reason)
1756 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1757 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1758 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1759 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1760 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1761 a8083063 Iustin Pop
1762 a8083063 Iustin Pop
1763 1f350e0f Michele Tartara
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1764 a8083063 Iustin Pop
  """Shut an instance down.
1765 a8083063 Iustin Pop

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

1768 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1769 e69d05fd Iustin Pop
  @param instance: the instance object
1770 6263189c Guido Trotter
  @type timeout: integer
1771 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1772 1f350e0f Michele Tartara
  @type reason: list of reasons
1773 1f350e0f Michele Tartara
  @param reason: the reason trail for this shutdown
1774 1f350e0f Michele Tartara
  @type store_reason: boolean
1775 1f350e0f Michele Tartara
  @param store_reason: whether to store the shutdown reason trail on file
1776 c26a6bd2 Iustin Pop
  @rtype: None
1777 a8083063 Iustin Pop

1778 098c0958 Michael Hanselmann
  """
1779 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1780 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1781 c26a6bd2 Iustin Pop
  iname = instance.name
1782 a8083063 Iustin Pop
1783 3361ab37 Helga Velroyen
  if instance.name not in hyper.ListInstances(instance.hvparams):
1784 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1785 c26a6bd2 Iustin Pop
    return
1786 a8083063 Iustin Pop
1787 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1788 3c0cdc83 Michael Hanselmann
    def __init__(self):
1789 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1790 a8083063 Iustin Pop
1791 3c0cdc83 Michael Hanselmann
    def __call__(self):
1792 3361ab37 Helga Velroyen
      if iname not in hyper.ListInstances(instance.hvparams):
1793 3c0cdc83 Michael Hanselmann
        return
1794 3c0cdc83 Michael Hanselmann
1795 3c0cdc83 Michael Hanselmann
      try:
1796 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1797 1f350e0f Michele Tartara
        if store_reason:
1798 1f350e0f Michele Tartara
          _StoreInstReasonTrail(instance.name, reason)
1799 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1800 3361ab37 Helga Velroyen
        if iname not in hyper.ListInstances(instance.hvparams):
1801 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1802 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1803 3c0cdc83 Michael Hanselmann
          return
1804 3c0cdc83 Michael Hanselmann
1805 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1806 3c0cdc83 Michael Hanselmann
1807 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1808 3c0cdc83 Michael Hanselmann
1809 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1810 3c0cdc83 Michael Hanselmann
1811 3c0cdc83 Michael Hanselmann
  try:
1812 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1813 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1814 a8083063 Iustin Pop
    # the shutdown did not succeed
1815 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1816 a8083063 Iustin Pop
1817 a8083063 Iustin Pop
    try:
1818 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1819 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1820 3361ab37 Helga Velroyen
      if iname in hyper.ListInstances(instance.hvparams):
1821 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1822 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1823 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1824 a8083063 Iustin Pop
1825 a8083063 Iustin Pop
    time.sleep(1)
1826 3c0cdc83 Michael Hanselmann
1827 3361ab37 Helga Velroyen
    if iname in hyper.ListInstances(instance.hvparams):
1828 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1829 3c9c571d Iustin Pop
1830 f28ec899 Guido Trotter
  try:
1831 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1832 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1833 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1834 f28ec899 Guido Trotter
1835 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1836 a8083063 Iustin Pop
1837 a8083063 Iustin Pop
1838 55cec070 Michele Tartara
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1839 007a2f3e Alexander Schreiber
  """Reboot an instance.
1840 007a2f3e Alexander Schreiber

1841 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1842 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1843 10c2650b Iustin Pop
  @type reboot_type: str
1844 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1845 10c2650b Iustin Pop
    constants:
1846 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1847 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1848 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1849 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1850 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1851 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1852 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1853 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1854 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1855 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1856 55cec070 Michele Tartara
  @type reason: list of reasons
1857 55cec070 Michele Tartara
  @param reason: the reason trail for this reboot
1858 c26a6bd2 Iustin Pop
  @rtype: None
1859 007a2f3e Alexander Schreiber

1860 007a2f3e Alexander Schreiber
  """
1861 3361ab37 Helga Velroyen
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1862 3361ab37 Helga Velroyen
                                                   instance.hvparams)
1863 007a2f3e Alexander Schreiber
1864 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1865 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1866 007a2f3e Alexander Schreiber
1867 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1868 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1869 007a2f3e Alexander Schreiber
    try:
1870 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1871 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1872 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1873 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1874 007a2f3e Alexander Schreiber
    try:
1875 1f350e0f Michele Tartara
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1876 1fa6fcba Michele Tartara
      result = StartInstance(instance, False, reason, store_reason=False)
1877 55cec070 Michele Tartara
      _StoreInstReasonTrail(instance.name, reason)
1878 4a90bd4f Michele Tartara
      return result
1879 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1880 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1881 007a2f3e Alexander Schreiber
  else:
1882 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1883 007a2f3e Alexander Schreiber
1884 007a2f3e Alexander Schreiber
1885 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1886 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1887 ebe466d8 Guido Trotter

1888 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1889 ebe466d8 Guido Trotter
  @param instance: the instance object
1890 ebe466d8 Guido Trotter
  @type memory: int
1891 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1892 ebe466d8 Guido Trotter
  @rtype: None
1893 ebe466d8 Guido Trotter

1894 ebe466d8 Guido Trotter
  """
1895 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1896 3361ab37 Helga Velroyen
  running = hyper.ListInstances(instance.hvparams)
1897 ebe466d8 Guido Trotter
  if instance.name not in running:
1898 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1899 ebe466d8 Guido Trotter
    return
1900 ebe466d8 Guido Trotter
  try:
1901 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1902 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1903 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1904 ebe466d8 Guido Trotter
1905 ebe466d8 Guido Trotter
1906 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1907 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1908 6906a9d8 Guido Trotter

1909 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1910 6906a9d8 Guido Trotter
  @param instance: the instance definition
1911 6906a9d8 Guido Trotter

1912 6906a9d8 Guido Trotter
  """
1913 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1914 cd42d0ad Guido Trotter
  try:
1915 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1916 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1917 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1918 c26a6bd2 Iustin Pop
  return info
1919 6906a9d8 Guido Trotter
1920 6906a9d8 Guido Trotter
1921 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1922 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1923 6906a9d8 Guido Trotter

1924 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1925 6906a9d8 Guido Trotter
  @param instance: the instance definition
1926 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1927 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1928 6906a9d8 Guido Trotter
  @type target: string
1929 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1930 6906a9d8 Guido Trotter

1931 6906a9d8 Guido Trotter
  """
1932 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1933 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1934 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1935 77fcff4a Apollon Oikonomopoulos
    # in any way
1936 77fcff4a Apollon Oikonomopoulos
    try:
1937 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1938 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1939 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1940 77fcff4a Apollon Oikonomopoulos
1941 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1942 cd42d0ad Guido Trotter
  try:
1943 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1944 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1945 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1946 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1947 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1948 6906a9d8 Guido Trotter
1949 6906a9d8 Guido Trotter
1950 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1951 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1952 6906a9d8 Guido Trotter

1953 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1954 6906a9d8 Guido Trotter
  @param instance: the instance definition
1955 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1956 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1957 6906a9d8 Guido Trotter
  @type success: boolean
1958 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1959 6906a9d8 Guido Trotter

1960 6906a9d8 Guido Trotter
  """
1961 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1962 cd42d0ad Guido Trotter
  try:
1963 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1964 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1965 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1966 6906a9d8 Guido Trotter
1967 6906a9d8 Guido Trotter
1968 bc0a2284 Helga Velroyen
def MigrateInstance(cluster_name, instance, target, live):
1969 2a10865c Iustin Pop
  """Migrates an instance to another node.
1970 2a10865c Iustin Pop

1971 bc0a2284 Helga Velroyen
  @type cluster_name: string
1972 bc0a2284 Helga Velroyen
  @param cluster_name: name of the cluster
1973 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1974 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1975 9f0e6b37 Iustin Pop
  @type target: string
1976 9f0e6b37 Iustin Pop
  @param target: the target node name
1977 9f0e6b37 Iustin Pop
  @type live: boolean
1978 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1979 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1980 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1981 9f0e6b37 Iustin Pop

1982 2a10865c Iustin Pop
  """
1983 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1984 2a10865c Iustin Pop
1985 2a10865c Iustin Pop
  try:
1986 bc0a2284 Helga Velroyen
    hyper.MigrateInstance(cluster_name, instance, target, live)
1987 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1988 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1989 2a10865c Iustin Pop
1990 2a10865c Iustin Pop
1991 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1992 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1993 6a1434d7 Andrea Spadaccini

1994 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1995 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1996 6a1434d7 Andrea Spadaccini
  @type success: bool
1997 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1998 6a1434d7 Andrea Spadaccini
  @type live: bool
1999 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
2000 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
2001 6a1434d7 Andrea Spadaccini

2002 6a1434d7 Andrea Spadaccini
  """
2003 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2004 6a1434d7 Andrea Spadaccini
2005 6a1434d7 Andrea Spadaccini
  try:
2006 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
2007 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
2008 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
2009 6a1434d7 Andrea Spadaccini
          exc=True)
2010 6a1434d7 Andrea Spadaccini
2011 6a1434d7 Andrea Spadaccini
2012 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
2013 6a1434d7 Andrea Spadaccini
  """Get the migration status
2014 6a1434d7 Andrea Spadaccini

2015 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
2016 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
2017 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
2018 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
2019 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
2020 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
2021 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
2022 6a1434d7 Andrea Spadaccini

2023 6a1434d7 Andrea Spadaccini
  """
2024 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2025 6a1434d7 Andrea Spadaccini
  try:
2026 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
2027 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
2028 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
2029 6a1434d7 Andrea Spadaccini
2030 6a1434d7 Andrea Spadaccini
2031 c5708931 Dimitris Aragiorgis
def HotplugDevice(instance, action, dev_type, device, extra, seq):
2032 c5708931 Dimitris Aragiorgis
  """Hotplug a device
2033 c5708931 Dimitris Aragiorgis

2034 c5708931 Dimitris Aragiorgis
  Hotplug is currently supported only for KVM Hypervisor.
2035 c5708931 Dimitris Aragiorgis
  @type instance: L{objects.Instance}
2036 c5708931 Dimitris Aragiorgis
  @param instance: the instance to which we hotplug a device
2037 c5708931 Dimitris Aragiorgis
  @type action: string
2038 c5708931 Dimitris Aragiorgis
  @param action: the hotplug action to perform
2039 c5708931 Dimitris Aragiorgis
  @type dev_type: string
2040 c5708931 Dimitris Aragiorgis
  @param dev_type: the device type to hotplug
2041 c5708931 Dimitris Aragiorgis
  @type device: either L{objects.NIC} or L{objects.Disk}
2042 c5708931 Dimitris Aragiorgis
  @param device: the device object to hotplug
2043 c5708931 Dimitris Aragiorgis
  @type extra: string
2044 c5708931 Dimitris Aragiorgis
  @param extra: extra info used by hotplug code (e.g. disk link)
2045 c5708931 Dimitris Aragiorgis
  @type seq: int
2046 c5708931 Dimitris Aragiorgis
  @param seq: the index of the device from master perspective
2047 c5708931 Dimitris Aragiorgis
  @raise RPCFail: in case instance does not have KVM hypervisor
2048 c5708931 Dimitris Aragiorgis

2049 c5708931 Dimitris Aragiorgis
  """
2050 c5708931 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2051 c5708931 Dimitris Aragiorgis
  try:
2052 50e0f1d9 Dimitris Aragiorgis
    hyper.VerifyHotplugSupport(instance, action, dev_type)
2053 50e0f1d9 Dimitris Aragiorgis
  except errors.HotplugError, err:
2054 c5708931 Dimitris Aragiorgis
    _Fail("Hotplug is not supported: %s", err)
2055 c5708931 Dimitris Aragiorgis
2056 c5708931 Dimitris Aragiorgis
  if action == constants.HOTPLUG_ACTION_ADD:
2057 c5708931 Dimitris Aragiorgis
    fn = hyper.HotAddDevice
2058 c5708931 Dimitris Aragiorgis
  elif action == constants.HOTPLUG_ACTION_REMOVE:
2059 c5708931 Dimitris Aragiorgis
    fn = hyper.HotDelDevice
2060 c5708931 Dimitris Aragiorgis
  elif action == constants.HOTPLUG_ACTION_MODIFY:
2061 c5708931 Dimitris Aragiorgis
    fn = hyper.HotModDevice
2062 c5708931 Dimitris Aragiorgis
  else:
2063 c5708931 Dimitris Aragiorgis
    assert action in constants.HOTPLUG_ALL_ACTIONS
2064 c5708931 Dimitris Aragiorgis
2065 c5708931 Dimitris Aragiorgis
  return fn(instance, dev_type, device, extra, seq)
2066 c5708931 Dimitris Aragiorgis
2067 c5708931 Dimitris Aragiorgis
2068 24711492 Dimitris Aragiorgis
def HotplugSupported(instance):
2069 24711492 Dimitris Aragiorgis
  """Checks if hotplug is generally supported.
2070 24711492 Dimitris Aragiorgis

2071 24711492 Dimitris Aragiorgis
  """
2072 24711492 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2073 24711492 Dimitris Aragiorgis
  try:
2074 24711492 Dimitris Aragiorgis
    hyper.HotplugSupported(instance)
2075 24711492 Dimitris Aragiorgis
  except errors.HotplugError, err:
2076 24711492 Dimitris Aragiorgis
    _Fail("Hotplug is not supported: %s", err)
2077 24711492 Dimitris Aragiorgis
2078 24711492 Dimitris Aragiorgis
2079 ee1478e5 Bernardo Dal Seno
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
2080 a8083063 Iustin Pop
  """Creates a block device for an instance.
2081 a8083063 Iustin Pop

2082 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
2083 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
2084 b1206984 Iustin Pop
  @type size: int
2085 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
2086 b1206984 Iustin Pop
  @type owner: str
2087 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
2088 b1206984 Iustin Pop
      used for device cache data
2089 b1206984 Iustin Pop
  @type on_primary: boolean
2090 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
2091 b1206984 Iustin Pop
  @type info: string
2092 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
2093 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
2094 ee1478e5 Bernardo Dal Seno
  @type excl_stor: boolean
2095 ee1478e5 Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
2096 b1206984 Iustin Pop

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

2101 a8083063 Iustin Pop
  """
2102 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
2103 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
2104 a8083063 Iustin Pop
  clist = []
2105 a8083063 Iustin Pop
  if disk.children:
2106 a8083063 Iustin Pop
    for child in disk.children:
2107 1063abd1 Iustin Pop
      try:
2108 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
2109 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
2110 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
2111 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
2112 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
2113 a8083063 Iustin Pop
        # be assembled
2114 1063abd1 Iustin Pop
        try:
2115 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
2116 1063abd1 Iustin Pop
          crdev.Open()
2117 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
2118 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
2119 a8083063 Iustin Pop
      clist.append(crdev)
2120 a8083063 Iustin Pop
2121 dab69e97 Iustin Pop
  try:
2122 ee1478e5 Bernardo Dal Seno
    device = bdev.Create(disk, clist, excl_stor)
2123 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
2124 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
2125 6c626518 Iustin Pop
2126 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
2127 1063abd1 Iustin Pop
    try:
2128 1063abd1 Iustin Pop
      device.Assemble()
2129 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
2130 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
2131 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
2132 1063abd1 Iustin Pop
      try:
2133 1063abd1 Iustin Pop
        device.Open(force=True)
2134 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
2135 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
2136 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
2137 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
2138 a0c3fea1 Michael Hanselmann
2139 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
2140 a0c3fea1 Michael Hanselmann
2141 c26a6bd2 Iustin Pop
  return device.unique_id
2142 a8083063 Iustin Pop
2143 a8083063 Iustin Pop
2144 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
2145 69dd363f René Nussbaumer
  """This function actually wipes the device.
2146 69dd363f René Nussbaumer

2147 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
2148 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
2149 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
2150 69dd363f René Nussbaumer

2151 69dd363f René Nussbaumer
  """
2152 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
2153 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
2154 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
2155 0188611b Michael Hanselmann
  block_size = 1024 * 1024
2156 0188611b Michael Hanselmann
2157 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2158 0188611b Michael Hanselmann
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2159 da63bb4e René Nussbaumer
         "count=%d" % size]
2160 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
2161 69dd363f René Nussbaumer
2162 69dd363f René Nussbaumer
  if result.failed:
2163 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2164 69dd363f René Nussbaumer
          result.fail_reason, result.output)
2165 69dd363f René Nussbaumer
2166 69dd363f René Nussbaumer
2167 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
2168 69dd363f René Nussbaumer
  """Wipes a block device.
2169 69dd363f René Nussbaumer

2170 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
2171 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
2172 da63bb4e René Nussbaumer
  @type offset: int
2173 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
2174 da63bb4e René Nussbaumer
  @type size: int
2175 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
2176 69dd363f René Nussbaumer

2177 69dd363f René Nussbaumer
  """
2178 69dd363f René Nussbaumer
  try:
2179 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
2180 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
2181 da63bb4e René Nussbaumer
    rdev = None
2182 da63bb4e René Nussbaumer
2183 da63bb4e René Nussbaumer
  if not rdev:
2184 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2185 da63bb4e René Nussbaumer
2186 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
2187 0188611b Michael Hanselmann
  if offset < 0:
2188 0188611b Michael Hanselmann
    _Fail("Negative offset")
2189 0188611b Michael Hanselmann
  if size < 0:
2190 0188611b Michael Hanselmann
    _Fail("Negative size")
2191 da63bb4e René Nussbaumer
  if offset > rdev.size:
2192 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
2193 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
2194 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
2195 69dd363f René Nussbaumer
2196 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
2197 69dd363f René Nussbaumer
2198 69dd363f René Nussbaumer
2199 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
2200 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
2201 5119c79e René Nussbaumer

2202 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
2203 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
2204 5119c79e René Nussbaumer
  @type pause: bool
2205 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
2206 5119c79e René Nussbaumer

2207 5119c79e René Nussbaumer
  """
2208 5119c79e René Nussbaumer
  success = []
2209 5119c79e René Nussbaumer
  for disk in disks:
2210 5119c79e René Nussbaumer
    try:
2211 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
2212 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
2213 5119c79e René Nussbaumer
      rdev = None
2214 5119c79e René Nussbaumer
2215 5119c79e René Nussbaumer
    if not rdev:
2216 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
2217 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
2218 5119c79e René Nussbaumer
      continue
2219 5119c79e René Nussbaumer
2220 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
2221 5119c79e René Nussbaumer
2222 5119c79e René Nussbaumer
    if result:
2223 5119c79e René Nussbaumer
      success.append((result, None))
2224 5119c79e René Nussbaumer
    else:
2225 5119c79e René Nussbaumer
      if pause:
2226 5119c79e René Nussbaumer
        msg = "Pause"
2227 5119c79e René Nussbaumer
      else:
2228 5119c79e René Nussbaumer
        msg = "Resume"
2229 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2230 5119c79e René Nussbaumer
2231 5119c79e René Nussbaumer
  return success
2232 5119c79e René Nussbaumer
2233 5119c79e René Nussbaumer
2234 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
2235 a8083063 Iustin Pop
  """Remove a block device.
2236 a8083063 Iustin Pop

2237 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
2238 10c2650b Iustin Pop

2239 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
2240 10c2650b Iustin Pop
  @param disk: the disk object we should remove
2241 10c2650b Iustin Pop
  @rtype: boolean
2242 10c2650b Iustin Pop
  @return: the success of the operation
2243 a8083063 Iustin Pop

2244 a8083063 Iustin Pop
  """
2245 e1bc0878 Iustin Pop
  msgs = []
2246 a8083063 Iustin Pop
  try:
2247 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
2248 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
2249 a8083063 Iustin Pop
    # probably can't attach
2250 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
2251 a8083063 Iustin Pop
    rdev = None
2252 a8083063 Iustin Pop
  if rdev is not None:
2253 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
2254 b3ae67d7 Dimitris Aragiorgis
2255 b3ae67d7 Dimitris Aragiorgis
    def _TryRemove():
2256 b3ae67d7 Dimitris Aragiorgis
      try:
2257 b3ae67d7 Dimitris Aragiorgis
        rdev.Remove()
2258 b3ae67d7 Dimitris Aragiorgis
        return []
2259 b3ae67d7 Dimitris Aragiorgis
      except errors.BlockDeviceError, err:
2260 b3ae67d7 Dimitris Aragiorgis
        return [str(err)]
2261 b3ae67d7 Dimitris Aragiorgis
2262 b3ae67d7 Dimitris Aragiorgis
    msgs.extend(utils.SimpleRetry([], _TryRemove,
2263 b3ae67d7 Dimitris Aragiorgis
                                  constants.DISK_REMOVE_RETRY_INTERVAL,
2264 b3ae67d7 Dimitris Aragiorgis
                                  constants.DISK_REMOVE_RETRY_TIMEOUT))
2265 b3ae67d7 Dimitris Aragiorgis
2266 c26a6bd2 Iustin Pop
    if not msgs:
2267 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
2268 e1bc0878 Iustin Pop
2269 a8083063 Iustin Pop
  if disk.children:
2270 a8083063 Iustin Pop
    for child in disk.children:
2271 c26a6bd2 Iustin Pop
      try:
2272 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
2273 c26a6bd2 Iustin Pop
      except RPCFail, err:
2274 c26a6bd2 Iustin Pop
        msgs.append(str(err))
2275 e1bc0878 Iustin Pop
2276 c26a6bd2 Iustin Pop
  if msgs:
2277 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2278 afdc3985 Iustin Pop
2279 a8083063 Iustin Pop
2280 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
2281 a8083063 Iustin Pop
  """Activate a block device for an instance.
2282 a8083063 Iustin Pop

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

2285 10c2650b Iustin Pop
  @note: this function is called recursively.
2286 a8083063 Iustin Pop

2287 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2288 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
2289 10c2650b Iustin Pop
  @type owner: str
2290 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
2291 10c2650b Iustin Pop
  @type as_primary: boolean
2292 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
2293 10c2650b Iustin Pop
      read/write
2294 a8083063 Iustin Pop

2295 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
2296 10c2650b Iustin Pop
      was assembled)
2297 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
2298 10c2650b Iustin Pop
      during the activation of the children or the device
2299 10c2650b Iustin Pop
      itself
2300 a8083063 Iustin Pop

2301 a8083063 Iustin Pop
  """
2302 a8083063 Iustin Pop
  children = []
2303 a8083063 Iustin Pop
  if disk.children:
2304 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
2305 fc1dc9d7 Iustin Pop
    if mcn == -1:
2306 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
2307 fc1dc9d7 Iustin Pop
    else:
2308 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
2309 a8083063 Iustin Pop
    for chld_disk in disk.children:
2310 fc1dc9d7 Iustin Pop
      try:
2311 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2312 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
2313 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
2314 fc1dc9d7 Iustin Pop
          raise
2315 fc1dc9d7 Iustin Pop
        cdev = None
2316 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
2317 1063abd1 Iustin Pop
                      str(err))
2318 fc1dc9d7 Iustin Pop
      children.append(cdev)
2319 a8083063 Iustin Pop
2320 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
2321 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
2322 a8083063 Iustin Pop
    result = r_dev
2323 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
2324 a8083063 Iustin Pop
      r_dev.Open()
2325 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2326 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
2327 3f78eef2 Iustin Pop
2328 a8083063 Iustin Pop
  else:
2329 a8083063 Iustin Pop
    result = True
2330 a8083063 Iustin Pop
  return result
2331 a8083063 Iustin Pop
2332 a8083063 Iustin Pop
2333 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
2334 a8083063 Iustin Pop
  """Activate a block device for an instance.
2335 a8083063 Iustin Pop

2336 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
2337 a8083063 Iustin Pop

2338 b1206984 Iustin Pop
  @rtype: str or boolean
2339 ff5def9b Dimitris Aragiorgis
  @return: a tuple with the C{/dev/...} path and the created symlink
2340 ff5def9b Dimitris Aragiorgis
      for primary nodes, and (C{True}, C{True}) for secondary nodes
2341 a8083063 Iustin Pop

2342 a8083063 Iustin Pop
  """
2343 53c14ef1 Iustin Pop
  try:
2344 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2345 89ff748d Thomas Thrainer
    if isinstance(result, BlockDev):
2346 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
2347 ff5def9b Dimitris Aragiorgis
      dev_path = result.dev_path
2348 ff5def9b Dimitris Aragiorgis
      link_name = None
2349 c417e115 Iustin Pop
      if as_primary:
2350 ff5def9b Dimitris Aragiorgis
        link_name = _SymlinkBlockDev(owner, dev_path, idx)
2351 ff5def9b Dimitris Aragiorgis
    elif result:
2352 ff5def9b Dimitris Aragiorgis
      return result, result
2353 ff5def9b Dimitris Aragiorgis
    else:
2354 ff5def9b Dimitris Aragiorgis
      _Fail("Unexpected result from _RecursiveAssembleBD")
2355 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
2356 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
2357 c417e115 Iustin Pop
  except OSError, err:
2358 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
2359 afdc3985 Iustin Pop
2360 ff5def9b Dimitris Aragiorgis
  return dev_path, link_name
2361 a8083063 Iustin Pop
2362 a8083063 Iustin Pop
2363 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
2364 a8083063 Iustin Pop
  """Shut down a block device.
2365 a8083063 Iustin Pop

2366 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
2367 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
2368 c41eea6e Iustin Pop
  shutdown.
2369 a8083063 Iustin Pop

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

2374 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2375 10c2650b Iustin Pop
  @param disk: the description of the disk we should
2376 10c2650b Iustin Pop
      shutdown
2377 c26a6bd2 Iustin Pop
  @rtype: None
2378 10c2650b Iustin Pop

2379 a8083063 Iustin Pop
  """
2380 cacfd1fd Iustin Pop
  msgs = []
2381 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2382 a8083063 Iustin Pop
  if r_dev is not None:
2383 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
2384 cacfd1fd Iustin Pop
    try:
2385 746f7476 Iustin Pop
      r_dev.Shutdown()
2386 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
2387 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
2388 cacfd1fd Iustin Pop
      msgs.append(str(err))
2389 746f7476 Iustin Pop
2390 a8083063 Iustin Pop
  if disk.children:
2391 a8083063 Iustin Pop
    for child in disk.children:
2392 c26a6bd2 Iustin Pop
      try:
2393 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
2394 c26a6bd2 Iustin Pop
      except RPCFail, err:
2395 c26a6bd2 Iustin Pop
        msgs.append(str(err))
2396 746f7476 Iustin Pop
2397 c26a6bd2 Iustin Pop
  if msgs:
2398 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2399 a8083063 Iustin Pop
2400 a8083063 Iustin Pop
2401 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
2402 153d9724 Iustin Pop
  """Extend a mirrored block device.
2403 a8083063 Iustin Pop

2404 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
2405 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
2406 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
2407 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
2408 c26a6bd2 Iustin Pop
  @rtype: None
2409 10c2650b Iustin Pop

2410 a8083063 Iustin Pop
  """
2411 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
2412 153d9724 Iustin Pop
  if parent_bdev is None:
2413 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2414 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2415 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
2416 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2417 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
2418 a8083063 Iustin Pop
2419 a8083063 Iustin Pop
2420 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2421 153d9724 Iustin Pop
  """Shrink a mirrored block device.
2422 a8083063 Iustin Pop

2423 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
2424 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
2425 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
2426 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
2427 c26a6bd2 Iustin Pop
  @rtype: None
2428 10c2650b Iustin Pop

2429 a8083063 Iustin Pop
  """
2430 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
2431 153d9724 Iustin Pop
  if parent_bdev is None:
2432 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2433 e739bd57 Iustin Pop
  devs = []
2434 e739bd57 Iustin Pop
  for disk in new_cdevs:
2435 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
2436 e739bd57 Iustin Pop
    if rpath is None:
2437 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
2438 e739bd57 Iustin Pop
      if bd is None:
2439 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
2440 e739bd57 Iustin Pop
      else:
2441 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
2442 e739bd57 Iustin Pop
    else:
2443 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
2444 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2445 e739bd57 Iustin Pop
      devs.append(rpath)
2446 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
2447 a8083063 Iustin Pop
2448 a8083063 Iustin Pop
2449 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
2450 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
2451 a8083063 Iustin Pop

2452 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2453 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
2454 10c2650b Iustin Pop
  @rtype: disk
2455 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
2456 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
2457 10c2650b Iustin Pop
      found
2458 a8083063 Iustin Pop

2459 a8083063 Iustin Pop
  """
2460 a8083063 Iustin Pop
  stats = []
2461 a8083063 Iustin Pop
  for dsk in disks:
2462 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
2463 a8083063 Iustin Pop
    if rbd is None:
2464 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
2465 96acbc09 Michael Hanselmann
2466 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
2467 96acbc09 Michael Hanselmann
2468 c26a6bd2 Iustin Pop
  return stats
2469 a8083063 Iustin Pop
2470 a8083063 Iustin Pop
2471 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
2472 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
2473 c6a9dffa Michael Hanselmann

2474 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
2475 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
2476 c6a9dffa Michael Hanselmann
  @rtype: disk
2477 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2478 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
2479 c6a9dffa Michael Hanselmann
    otherwise
2480 c6a9dffa Michael Hanselmann

2481 c6a9dffa Michael Hanselmann
  """
2482 c6a9dffa Michael Hanselmann
  result = []
2483 c6a9dffa Michael Hanselmann
  for disk in disks:
2484 c6a9dffa Michael Hanselmann
    try:
2485 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
2486 c6a9dffa Michael Hanselmann
      if rbd is None:
2487 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
2488 c6a9dffa Michael Hanselmann
        continue
2489 c6a9dffa Michael Hanselmann
2490 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
2491 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
2492 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
2493 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
2494 c6a9dffa Michael Hanselmann
    else:
2495 c6a9dffa Michael Hanselmann
      result.append((True, status))
2496 c6a9dffa Michael Hanselmann
2497 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
2498 c6a9dffa Michael Hanselmann
2499 c6a9dffa Michael Hanselmann
  return result
2500 c6a9dffa Michael Hanselmann
2501 c6a9dffa Michael Hanselmann
2502 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
2503 a8083063 Iustin Pop
  """Check if a device is activated.
2504 a8083063 Iustin Pop

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

2507 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2508 10c2650b Iustin Pop
  @param disk: the disk object we need to find
2509 a8083063 Iustin Pop

2510 10c2650b Iustin Pop
  @return: None if the device can't be found,
2511 10c2650b Iustin Pop
      otherwise the device instance
2512 a8083063 Iustin Pop

2513 a8083063 Iustin Pop
  """
2514 a8083063 Iustin Pop
  children = []
2515 a8083063 Iustin Pop
  if disk.children:
2516 a8083063 Iustin Pop
    for chdisk in disk.children:
2517 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
2518 a8083063 Iustin Pop
2519 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
2520 a8083063 Iustin Pop
2521 a8083063 Iustin Pop
2522 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
2523 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
2524 f2e07bb4 Michael Hanselmann

2525 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
2526 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
2527 f2e07bb4 Michael Hanselmann

2528 f2e07bb4 Michael Hanselmann
  """
2529 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
2530 f2e07bb4 Michael Hanselmann
  if real_disk is None:
2531 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
2532 f2e07bb4 Michael Hanselmann
2533 f2e07bb4 Michael Hanselmann
  real_disk.Open()
2534 f2e07bb4 Michael Hanselmann
2535 f2e07bb4 Michael Hanselmann
  return real_disk
2536 f2e07bb4 Michael Hanselmann
2537 f2e07bb4 Michael Hanselmann
2538 821d1bd1 Iustin Pop
def BlockdevFind(disk):
2539 a8083063 Iustin Pop
  """Check if a device is activated.
2540 a8083063 Iustin Pop

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

2543 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2544 10c2650b Iustin Pop
  @param disk: the disk to find
2545 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2546 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2547 96acbc09 Michael Hanselmann
           information
2548 a8083063 Iustin Pop

2549 a8083063 Iustin Pop
  """
2550 23829f6f Iustin Pop
  try:
2551 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
2552 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
2553 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
2554 96acbc09 Michael Hanselmann
2555 a8083063 Iustin Pop
  if rbd is None:
2556 c26a6bd2 Iustin Pop
    return None
2557 96acbc09 Michael Hanselmann
2558 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2559 a8083063 Iustin Pop
2560 a8083063 Iustin Pop
2561 6ef8077e Bernardo Dal Seno
def BlockdevGetdimensions(disks):
2562 968a7623 Iustin Pop
  """Computes the size of the given disks.
2563 968a7623 Iustin Pop

2564 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2565 968a7623 Iustin Pop

2566 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2567 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2568 968a7623 Iustin Pop
  @rtype: list
2569 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2570 6ef8077e Bernardo Dal Seno
      otherwise the pair (size, spindles), where spindles is None if the
2571 6ef8077e Bernardo Dal Seno
      device doesn't support that
2572 968a7623 Iustin Pop

2573 968a7623 Iustin Pop
  """
2574 968a7623 Iustin Pop
  result = []
2575 968a7623 Iustin Pop
  for cf in disks:
2576 968a7623 Iustin Pop
    try:
2577 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2578 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2579 968a7623 Iustin Pop
      result.append(None)
2580 968a7623 Iustin Pop
      continue
2581 968a7623 Iustin Pop
    if rbd is None:
2582 968a7623 Iustin Pop
      result.append(None)
2583 968a7623 Iustin Pop
    else:
2584 6ef8077e Bernardo Dal Seno
      result.append(rbd.GetActualDimensions())
2585 968a7623 Iustin Pop
  return result
2586 968a7623 Iustin Pop
2587 968a7623 Iustin Pop
2588 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2589 a8083063 Iustin Pop
  """Write a file to the filesystem.
2590 a8083063 Iustin Pop

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

2594 10c2650b Iustin Pop
  @type file_name: str
2595 10c2650b Iustin Pop
  @param file_name: the target file name
2596 10c2650b Iustin Pop
  @type data: str
2597 10c2650b Iustin Pop
  @param data: the new contents of the file
2598 10c2650b Iustin Pop
  @type mode: int
2599 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2600 9a914f7a René Nussbaumer
  @type uid: string
2601 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2602 9a914f7a René Nussbaumer
  @type gid: string
2603 9a914f7a René Nussbaumer
  @param gid: the group of the file
2604 10c2650b Iustin Pop
  @type atime: float
2605 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2606 10c2650b Iustin Pop
  @type mtime: float
2607 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2608 c26a6bd2 Iustin Pop
  @rtype: None
2609 10c2650b Iustin Pop

2610 a8083063 Iustin Pop
  """
2611 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2612 cffbbae7 Michael Hanselmann
2613 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2614 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2615 a8083063 Iustin Pop
2616 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2617 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2618 2cc6781a Iustin Pop
          file_name)
2619 a8083063 Iustin Pop
2620 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2621 12bce260 Michael Hanselmann
2622 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2623 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2624 9a914f7a René Nussbaumer
2625 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2626 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2627 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2628 9a914f7a René Nussbaumer
2629 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2630 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2631 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2632 a8083063 Iustin Pop
2633 386b57af Iustin Pop
2634 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2635 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2636 b2f29800 René Nussbaumer

2637 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2638 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2639 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2640 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2641 b2f29800 René Nussbaumer

2642 b2f29800 René Nussbaumer
  @return: stdout
2643 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2644 b2f29800 René Nussbaumer

2645 b2f29800 René Nussbaumer
  """
2646 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2647 b2f29800 René Nussbaumer
2648 b2f29800 René Nussbaumer
  if result.failed:
2649 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2650 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2651 b2f29800 René Nussbaumer
2652 b2f29800 René Nussbaumer
  return result.stdout
2653 b2f29800 René Nussbaumer
2654 b2f29800 René Nussbaumer
2655 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2656 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2657 a8083063 Iustin Pop

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

2661 10c2650b Iustin Pop
  @type os_dir: str
2662 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2663 8e70b181 Iustin Pop
  @rtype: tuple
2664 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2665 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2666 a8083063 Iustin Pop

2667 a8083063 Iustin Pop
  """
2668 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2669 a8083063 Iustin Pop
2670 a8083063 Iustin Pop
  try:
2671 a8083063 Iustin Pop
    st = os.stat(api_file)
2672 a8083063 Iustin Pop
  except EnvironmentError, err:
2673 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2674 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2675 a8083063 Iustin Pop
2676 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2677 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2678 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2679 a8083063 Iustin Pop
2680 a8083063 Iustin Pop
  try:
2681 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2682 a8083063 Iustin Pop
  except EnvironmentError, err:
2683 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2684 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2685 a8083063 Iustin Pop
2686 a8083063 Iustin Pop
  try:
2687 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2688 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2689 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2690 255dcebd Iustin Pop
                   str(err))
2691 a8083063 Iustin Pop
2692 255dcebd Iustin Pop
  return True, api_versions
2693 a8083063 Iustin Pop
2694 386b57af Iustin Pop
2695 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2696 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2697 a8083063 Iustin Pop

2698 10c2650b Iustin Pop
  @type top_dirs: list
2699 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2700 10c2650b Iustin Pop
      search (if not given defaults to
2701 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2702 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2703 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2704 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2705 bad78e66 Iustin Pop
      search paths, where:
2706 255dcebd Iustin Pop
          - name is the (potential) OS name
2707 255dcebd Iustin Pop
          - path is the full path to the OS
2708 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2709 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2710 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2711 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2712 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2713 a8083063 Iustin Pop

2714 a8083063 Iustin Pop
  """
2715 7c3d51d4 Guido Trotter
  if top_dirs is None:
2716 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2717 a8083063 Iustin Pop
2718 a8083063 Iustin Pop
  result = []
2719 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2720 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2721 7c3d51d4 Guido Trotter
      try:
2722 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2723 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2724 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2725 7c3d51d4 Guido Trotter
        break
2726 7c3d51d4 Guido Trotter
      for name in f_names:
2727 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2728 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2729 255dcebd Iustin Pop
        if status:
2730 255dcebd Iustin Pop
          diagnose = ""
2731 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2732 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2733 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2734 255dcebd Iustin Pop
        else:
2735 255dcebd Iustin Pop
          diagnose = os_inst
2736 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2737 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2738 bad78e66 Iustin Pop
                       parameters, api_versions))
2739 a8083063 Iustin Pop
2740 c26a6bd2 Iustin Pop
  return result
2741 a8083063 Iustin Pop
2742 a8083063 Iustin Pop
2743 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2744 a8083063 Iustin Pop
  """Create an OS instance from disk.
2745 a8083063 Iustin Pop

2746 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2747 8e70b181 Iustin Pop
  valid OS name.
2748 a8083063 Iustin Pop

2749 8ee4dc80 Guido Trotter
  @type base_dir: string
2750 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2751 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2752 255dcebd Iustin Pop
  @rtype: tuple
2753 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2754 255dcebd Iustin Pop
      or error message
2755 7c3d51d4 Guido Trotter

2756 a8083063 Iustin Pop
  """
2757 56bcd3f4 Guido Trotter
  if base_dir is None:
2758 710f30ec Michael Hanselmann
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2759 c34c0cfd Iustin Pop
  else:
2760 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2761 f95c81bf Iustin Pop
2762 f95c81bf Iustin Pop
  if os_dir is None:
2763 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
2764 a8083063 Iustin Pop
2765 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2766 255dcebd Iustin Pop
  if not status:
2767 255dcebd Iustin Pop
    # push the error up
2768 255dcebd Iustin Pop
    return status, api_versions
2769 a8083063 Iustin Pop
2770 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2771 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2772 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2773 a8083063 Iustin Pop
2774 35007011 Iustin Pop
  # OS Files dictionary, we will populate it with the absolute path
2775 35007011 Iustin Pop
  # names; if the value is True, then it is a required file, otherwise
2776 35007011 Iustin Pop
  # an optional one
2777 35007011 Iustin Pop
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2778 a8083063 Iustin Pop
2779 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
2780 35007011 Iustin Pop
    os_files[constants.OS_VARIANTS_FILE] = False
2781 95075fba Guido Trotter
2782 c7d04a6b Iustin Pop
  if max(api_versions) >= constants.OS_API_V20:
2783 35007011 Iustin Pop
    os_files[constants.OS_PARAMETERS_FILE] = True
2784 c7d04a6b Iustin Pop
  else:
2785 c7d04a6b Iustin Pop
    del os_files[constants.OS_SCRIPT_VERIFY]
2786 c7d04a6b Iustin Pop
2787 35007011 Iustin Pop
  for (filename, required) in os_files.items():
2788 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
2789 a8083063 Iustin Pop
2790 a8083063 Iustin Pop
    try:
2791 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
2792 a8083063 Iustin Pop
    except EnvironmentError, err:
2793 35007011 Iustin Pop
      if err.errno == errno.ENOENT and not required:
2794 35007011 Iustin Pop
        del os_files[filename]
2795 35007011 Iustin Pop
        continue
2796 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
2797 eb93b673 Guido Trotter
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2798 a8083063 Iustin Pop
2799 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2800 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
2801 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
2802 255dcebd Iustin Pop
2803 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
2804 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2805 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
2806 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
2807 0757c107 Guido Trotter
2808 845da3e8 Iustin Pop
  variants = []
2809 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
2810 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2811 95075fba Guido Trotter
    try:
2812 5a7cb9d3 Iustin Pop
      variants = \
2813 5a7cb9d3 Iustin Pop
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2814 95075fba Guido Trotter
    except EnvironmentError, err:
2815 35007011 Iustin Pop
      # we accept missing files, but not other errors
2816 35007011 Iustin Pop
      if err.errno != errno.ENOENT:
2817 35007011 Iustin Pop
        return False, ("Error while reading the OS variants file at %s: %s" %
2818 eb93b673 Guido Trotter
                       (variants_file, utils.ErrnoOrStr(err)))
2819 0757c107 Guido Trotter
2820 c7d04a6b Iustin Pop
  parameters = []
2821 c7d04a6b Iustin Pop
  if constants.OS_PARAMETERS_FILE in os_files:
2822 c7d04a6b Iustin Pop
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2823 c7d04a6b Iustin Pop
    try:
2824 c7d04a6b Iustin Pop
      parameters = utils.ReadFile(parameters_file).splitlines()
2825 c7d04a6b Iustin Pop
    except EnvironmentError, err:
2826 c7d04a6b Iustin Pop
      return False, ("Error while reading the OS parameters file at %s: %s" %
2827 eb93b673 Guido Trotter
                     (parameters_file, utils.ErrnoOrStr(err)))
2828 c7d04a6b Iustin Pop
    parameters = [v.split(None, 1) for v in parameters]
2829 c7d04a6b Iustin Pop
2830 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
2831 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2832 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2833 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2834 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2835 40684c3a Iustin Pop
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2836 40684c3a Iustin Pop
                                                 None),
2837 95075fba Guido Trotter
                      supported_variants=variants,
2838 c7d04a6b Iustin Pop
                      supported_parameters=parameters,
2839 255dcebd Iustin Pop
                      api_versions=api_versions)
2840 255dcebd Iustin Pop
  return True, os_obj
2841 255dcebd Iustin Pop
2842 255dcebd Iustin Pop
2843 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
2844 255dcebd Iustin Pop
  """Create an OS instance from disk.
2845 255dcebd Iustin Pop

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

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

2853 255dcebd Iustin Pop
  @type base_dir: string
2854 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2855 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2856 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2857 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2858 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2859 255dcebd Iustin Pop

2860 255dcebd Iustin Pop
  """
2861 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2862 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2863 255dcebd Iustin Pop
2864 255dcebd Iustin Pop
  if not status:
2865 255dcebd Iustin Pop
    _Fail(payload)
2866 a8083063 Iustin Pop
2867 255dcebd Iustin Pop
  return payload
2868 a8083063 Iustin Pop
2869 a8083063 Iustin Pop
2870 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2871 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2872 2266edb2 Guido Trotter

2873 a025e535 Vitaly Kuznetsov
  @type os_name: str
2874 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2875 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2876 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2877 1bdcbbab Iustin Pop
  @type os_params: dict
2878 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2879 2266edb2 Guido Trotter
  @type debug: integer
2880 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2881 2266edb2 Guido Trotter
  @rtype: dict
2882 2266edb2 Guido Trotter
  @return: dict of environment variables
2883 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2884 10c2650b Iustin Pop
      cannot be found
2885 2266edb2 Guido Trotter

2886 2266edb2 Guido Trotter
  """
2887 2266edb2 Guido Trotter
  result = {}
2888 099c52ad Iustin Pop
  api_version = \
2889 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2890 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2891 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2892 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2893 efaa9b06 Iustin Pop
2894 efaa9b06 Iustin Pop
  # OS variants
2895 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2896 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2897 870dc44c Iustin Pop
    if not variant:
2898 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2899 35007011 Iustin Pop
  else:
2900 35007011 Iustin Pop
    variant = ""
2901 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2902 efaa9b06 Iustin Pop
2903 1bdcbbab Iustin Pop
  # OS params
2904 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2905 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2906 1bdcbbab Iustin Pop
2907 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
2908 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
2909 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
2910 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
2911 9a6ade06 Iustin Pop
2912 efaa9b06 Iustin Pop
  return result
2913 efaa9b06 Iustin Pop
2914 efaa9b06 Iustin Pop
2915 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2916 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2917 efaa9b06 Iustin Pop

2918 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2919 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2920 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2921 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2922 efaa9b06 Iustin Pop
  @type debug: integer
2923 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2924 efaa9b06 Iustin Pop
  @rtype: dict
2925 efaa9b06 Iustin Pop
  @return: dict of environment variables
2926 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2927 efaa9b06 Iustin Pop
      cannot be found
2928 efaa9b06 Iustin Pop

2929 efaa9b06 Iustin Pop
  """
2930 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2931 efaa9b06 Iustin Pop
2932 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2933 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2934 f2165b8a Iustin Pop
2935 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2936 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2937 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2938 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2939 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2940 efaa9b06 Iustin Pop
2941 efaa9b06 Iustin Pop
  # Disks
2942 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2943 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2944 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2945 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2946 8a348b15 Christos Stavrakakis
    result["DISK_%d_UUID" % idx] = disk.uuid
2947 8a348b15 Christos Stavrakakis
    if disk.name:
2948 8a348b15 Christos Stavrakakis
      result["DISK_%d_NAME" % idx] = disk.name
2949 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2950 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2951 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2952 cd3b4ff4 Helga Velroyen
    if disk.dev_type in constants.DTS_BLOCK:
2953 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2954 a09639d1 Santi Raffa
    elif disk.dev_type in constants.DTS_FILEBASED:
2955 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2956 a57e502a Thomas Thrainer
        "file:%s" % disk.logical_id[0]
2957 efaa9b06 Iustin Pop
2958 efaa9b06 Iustin Pop
  # NICs
2959 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2960 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2961 8a348b15 Christos Stavrakakis
    result["NIC_%d_UUID" % idx] = nic.uuid
2962 8a348b15 Christos Stavrakakis
    if nic.name:
2963 8a348b15 Christos Stavrakakis
      result["NIC_%d_NAME" % idx] = nic.name
2964 2266edb2 Guido Trotter
    if nic.ip:
2965 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2966 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2967 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2968 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2969 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2970 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2971 d89168ff Guido Trotter
    if nic.netinfo:
2972 d89168ff Guido Trotter
      nobj = objects.Network.FromDict(nic.netinfo)
2973 d89168ff Guido Trotter
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2974 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2975 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2976 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2977 2266edb2 Guido Trotter
2978 efaa9b06 Iustin Pop
  # HV/BE params
2979 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2980 67fc3042 Iustin Pop
    for key, value in source.items():
2981 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2982 67fc3042 Iustin Pop
2983 2266edb2 Guido Trotter
  return result
2984 a8083063 Iustin Pop
2985 f2e07bb4 Michael Hanselmann
2986 b954f097 Constantinos Venetsanopoulos
def DiagnoseExtStorage(top_dirs=None):
2987 b954f097 Constantinos Venetsanopoulos
  """Compute the validity for all ExtStorage Providers.
2988 b954f097 Constantinos Venetsanopoulos

2989 b954f097 Constantinos Venetsanopoulos
  @type top_dirs: list
2990 b954f097 Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
2991 b954f097 Constantinos Venetsanopoulos
      search (if not given defaults to
2992 b954f097 Constantinos Venetsanopoulos
      L{pathutils.ES_SEARCH_PATH})
2993 b954f097 Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
2994 b954f097 Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
2995 b954f097 Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
2996 b954f097 Constantinos Venetsanopoulos
      search paths, where:
2997 b954f097 Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
2998 b954f097 Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
2999 b954f097 Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
3000 b954f097 Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
3001 b954f097 Constantinos Venetsanopoulos
            otherwise empty
3002 b954f097 Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
3003 b954f097 Constantinos Venetsanopoulos

3004 b954f097 Constantinos Venetsanopoulos
  """
3005 b954f097 Constantinos Venetsanopoulos
  if top_dirs is None:
3006 b954f097 Constantinos Venetsanopoulos
    top_dirs = pathutils.ES_SEARCH_PATH
3007 b954f097 Constantinos Venetsanopoulos
3008 b954f097 Constantinos Venetsanopoulos
  result = []
3009 b954f097 Constantinos Venetsanopoulos
  for dir_name in top_dirs:
3010 b954f097 Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
3011 b954f097 Constantinos Venetsanopoulos
      try:
3012 b954f097 Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
3013 b954f097 Constantinos Venetsanopoulos
      except EnvironmentError, err:
3014 b954f097 Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
3015 b954f097 Constantinos Venetsanopoulos
                          dir_name, err)
3016 b954f097 Constantinos Venetsanopoulos
        break
3017 b954f097 Constantinos Venetsanopoulos
      for name in f_names:
3018 b954f097 Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
3019 b954f097 Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
3020 b954f097 Constantinos Venetsanopoulos
        if status:
3021 b954f097 Constantinos Venetsanopoulos
          diagnose = ""
3022 b954f097 Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
3023 b954f097 Constantinos Venetsanopoulos
        else:
3024 b954f097 Constantinos Venetsanopoulos
          diagnose = es_inst
3025 b954f097 Constantinos Venetsanopoulos
          parameters = []
3026 b954f097 Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
3027 b954f097 Constantinos Venetsanopoulos
3028 b954f097 Constantinos Venetsanopoulos
  return result
3029 b954f097 Constantinos Venetsanopoulos
3030 b954f097 Constantinos Venetsanopoulos
3031 be9150ea Bernardo Dal Seno
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
3032 594609c0 Iustin Pop
  """Grow a stack of block devices.
3033 594609c0 Iustin Pop

3034 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
3035 10c2650b Iustin Pop
  first ones to resize.
3036 594609c0 Iustin Pop

3037 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
3038 10c2650b Iustin Pop
  @param disk: the disk to be grown
3039 a59faf4b Iustin Pop
  @type amount: integer
3040 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
3041 a59faf4b Iustin Pop
  @type dryrun: boolean
3042 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
3043 a59faf4b Iustin Pop
      only, without actually increasing the size
3044 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
3045 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
3046 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
3047 10c2650b Iustin Pop
  @rtype: (status, result)
3048 be9150ea Bernardo Dal Seno
  @type excl_stor: boolean
3049 be9150ea Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
3050 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
3051 a59faf4b Iustin Pop
      the errors message if status is False
3052 594609c0 Iustin Pop

3053 594609c0 Iustin Pop
  """
3054 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
3055 594609c0 Iustin Pop
  if r_dev is None:
3056 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
3057 594609c0 Iustin Pop
3058 594609c0 Iustin Pop
  try:
3059 be9150ea Bernardo Dal Seno
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
3060 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
3061 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
3062 594609c0 Iustin Pop
3063 594609c0 Iustin Pop
3064 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
3065 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
3066 a8083063 Iustin Pop

3067 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
3068 a8083063 Iustin Pop
  just for the leaf lvm backend device.
3069 a8083063 Iustin Pop

3070 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
3071 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
3072 e9e9263d Guido Trotter
  @rtype: string
3073 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
3074 a8083063 Iustin Pop

3075 098c0958 Michael Hanselmann
  """
3076 cd3b4ff4 Helga Velroyen
  if disk.dev_type == constants.DT_DRBD8:
3077 433c63aa Iustin Pop
    if not disk.children:
3078 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
3079 433c63aa Iustin Pop
            disk.unique_id)
3080 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
3081 cd3b4ff4 Helga Velroyen
  elif disk.dev_type == constants.DT_PLAIN:
3082 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
3083 a8083063 Iustin Pop
    if r_dev is not None:
3084 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
3085 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
3086 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
3087 a8083063 Iustin Pop
    else:
3088 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
3089 a8083063 Iustin Pop
  else:
3090 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
3091 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
3092 a8083063 Iustin Pop
3093 a8083063 Iustin Pop
3094 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
3095 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
3096 48e175a2 Iustin Pop

3097 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
3098 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
3099 48e175a2 Iustin Pop
  for example after renames.
3100 48e175a2 Iustin Pop

3101 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
3102 48e175a2 Iustin Pop
  @param disk: the disk to be grown
3103 48e175a2 Iustin Pop
  @type info: string
3104 48e175a2 Iustin Pop
  @param info: new 'info' metadata
3105 48e175a2 Iustin Pop
  @rtype: (status, result)
3106 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
3107 48e175a2 Iustin Pop
      the errors message if status is False
3108 48e175a2 Iustin Pop

3109 48e175a2 Iustin Pop
  """
3110 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
3111 48e175a2 Iustin Pop
  if r_dev is None:
3112 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
3113 48e175a2 Iustin Pop
3114 48e175a2 Iustin Pop
  try:
3115 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
3116 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
3117 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
3118 48e175a2 Iustin Pop
3119 48e175a2 Iustin Pop
3120 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
3121 a8083063 Iustin Pop
  """Write out the export configuration information.
3122 a8083063 Iustin Pop

3123 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
3124 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
3125 10c2650b Iustin Pop
      saving configuration
3126 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
3127 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
3128 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
3129 a8083063 Iustin Pop

3130 c26a6bd2 Iustin Pop
  @rtype: None
3131 a8083063 Iustin Pop

3132 098c0958 Michael Hanselmann
  """
3133 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3134 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3135 a8083063 Iustin Pop
3136 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
3137 a8083063 Iustin Pop
3138 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
3139 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
3140 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3141 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3142 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
3143 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
3144 a8083063 Iustin Pop
3145 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
3146 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
3147 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3148 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
3149 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
3150 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
3151 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3152 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
3153 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
3154 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3155 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
3156 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3157 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3158 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3159 66f93869 Manuel Franceschini
3160 95268cc3 Iustin Pop
  nic_total = 0
3161 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
3162 95268cc3 Iustin Pop
    nic_total += 1
3163 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
3164 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
3165 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3166 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3167 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
3168 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
3169 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3170 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
3171 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
3172 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3173 a8083063 Iustin Pop
3174 726d7d68 Iustin Pop
  disk_total = 0
3175 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
3176 19d7f90a Guido Trotter
    if disk:
3177 726d7d68 Iustin Pop
      disk_total += 1
3178 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3179 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
3180 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3181 a57e502a Thomas Thrainer
                 ("%s" % disk.logical_id[1]))
3182 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3183 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
3184 d0c8c01d Iustin Pop
3185 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3186 a8083063 Iustin Pop
3187 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
3188 3c8954ad Iustin Pop
3189 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
3190 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
3191 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
3192 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
3193 3c8954ad Iustin Pop
3194 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
3195 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
3196 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
3197 3c8954ad Iustin Pop
3198 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
3199 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
3200 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
3201 535b49cb Iustin Pop
3202 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3203 726d7d68 Iustin Pop
                  data=config.Dumps())
3204 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
3205 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
3206 a8083063 Iustin Pop
3207 a8083063 Iustin Pop
3208 a8083063 Iustin Pop
def ExportInfo(dest):
3209 a8083063 Iustin Pop
  """Get export configuration information.
3210 a8083063 Iustin Pop

3211 10c2650b Iustin Pop
  @type dest: str
3212 10c2650b Iustin Pop
  @param dest: directory containing the export
3213 a8083063 Iustin Pop

3214 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
3215 10c2650b Iustin Pop
  @return: a serializable config file containing the
3216 10c2650b Iustin Pop
      export info
3217 a8083063 Iustin Pop

3218 a8083063 Iustin Pop
  """
3219 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3220 a8083063 Iustin Pop
3221 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
3222 a8083063 Iustin Pop
  config.read(cff)
3223 a8083063 Iustin Pop
3224 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
3225 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
3226 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
3227 a8083063 Iustin Pop
3228 c26a6bd2 Iustin Pop
  return config.Dumps()
3229 a8083063 Iustin Pop
3230 a8083063 Iustin Pop
3231 a8083063 Iustin Pop
def ListExports():
3232 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
3233 098c0958 Michael Hanselmann

3234 10c2650b Iustin Pop
  @rtype: list
3235 10c2650b Iustin Pop
  @return: list of the exports
3236 10c2650b Iustin Pop

3237 a8083063 Iustin Pop
  """
3238 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
3239 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3240 a8083063 Iustin Pop
  else:
3241 afdc3985 Iustin Pop
    _Fail("No exports directory")
3242 a8083063 Iustin Pop
3243 a8083063 Iustin Pop
3244 a8083063 Iustin Pop
def RemoveExport(export):
3245 a8083063 Iustin Pop
  """Remove an existing export from the node.
3246 a8083063 Iustin Pop

3247 10c2650b Iustin Pop
  @type export: str
3248 10c2650b Iustin Pop
  @param export: the name of the export to remove
3249 c26a6bd2 Iustin Pop
  @rtype: None
3250 a8083063 Iustin Pop

3251 098c0958 Michael Hanselmann
  """
3252 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3253 a8083063 Iustin Pop
3254 35fbcd11 Iustin Pop
  try:
3255 35fbcd11 Iustin Pop
    shutil.rmtree(target)
3256 35fbcd11 Iustin Pop
  except EnvironmentError, err:
3257 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
3258 a8083063 Iustin Pop
3259 a8083063 Iustin Pop
3260 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
3261 f3e513ad Iustin Pop
  """Rename a list of block devices.
3262 f3e513ad Iustin Pop

3263 10c2650b Iustin Pop
  @type devlist: list of tuples
3264 a57e502a Thomas Thrainer
  @param devlist: list of tuples of the form  (disk, new_unique_id); disk is
3265 a57e502a Thomas Thrainer
      an L{objects.Disk} object describing the current disk, and new
3266 a57e502a Thomas Thrainer
      unique_id is the name we rename it to
3267 10c2650b Iustin Pop
  @rtype: boolean
3268 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
3269 f3e513ad Iustin Pop

3270 f3e513ad Iustin Pop
  """
3271 6b5e3f70 Iustin Pop
  msgs = []
3272 f3e513ad Iustin Pop
  result = True
3273 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
3274 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
3275 f3e513ad Iustin Pop
    if dev is None:
3276 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
3277 f3e513ad Iustin Pop
      result = False
3278 f3e513ad Iustin Pop
      continue
3279 f3e513ad Iustin Pop
    try:
3280 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
3281 f3e513ad Iustin Pop
      dev.Rename(unique_id)
3282 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
3283 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
3284 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
3285 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
3286 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3287 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
3288 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
3289 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
3290 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
3291 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
3292 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
3293 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3294 f3e513ad Iustin Pop
      result = False
3295 afdc3985 Iustin Pop
  if not result:
3296 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
3297 f3e513ad Iustin Pop
3298 f3e513ad Iustin Pop
3299 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
3300 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
3301 778b75bb Manuel Franceschini

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

3306 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
3307 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
3308 d61cbe76 Iustin Pop

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

3311 778b75bb Manuel Franceschini
  """
3312 13a6c760 Helga Velroyen
  filestorage.CheckFileStoragePath(fs_dir)
3313 5e09a309 Michael Hanselmann
3314 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
3315 778b75bb Manuel Franceschini
3316 778b75bb Manuel Franceschini
3317 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
3318 778b75bb Manuel Franceschini
  """Create file storage directory.
3319 778b75bb Manuel Franceschini

3320 b1206984 Iustin Pop
  @type file_storage_dir: str
3321 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
3322 778b75bb Manuel Franceschini

3323 b1206984 Iustin Pop
  @rtype: tuple
3324 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
3325 b1206984 Iustin Pop
      creation was successful or not
3326 778b75bb Manuel Franceschini

3327 778b75bb Manuel Franceschini
  """
3328 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3329 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
3330 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
3331 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
3332 b2b8bcce Iustin Pop
            file_storage_dir)
3333 778b75bb Manuel Franceschini
  else:
3334 b2b8bcce Iustin Pop
    try:
3335 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
3336 b2b8bcce Iustin Pop
    except OSError, err:
3337 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
3338 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
3339 778b75bb Manuel Franceschini
3340 778b75bb Manuel Franceschini
3341 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
3342 778b75bb Manuel Franceschini
  """Remove file storage directory.
3343 778b75bb Manuel Franceschini

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

3346 10c2650b Iustin Pop
  @type file_storage_dir: str
3347 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
3348 10c2650b Iustin Pop
  @rtype: tuple (success,)
3349 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
3350 5bbd3f7f Michael Hanselmann
      whether the operation was successful
3351 778b75bb Manuel Franceschini

3352 778b75bb Manuel Franceschini
  """
3353 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3354 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
3355 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
3356 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
3357 b2b8bcce Iustin Pop
            file_storage_dir)
3358 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
3359 b2b8bcce Iustin Pop
    try:
3360 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
3361 b2b8bcce Iustin Pop
    except OSError, err:
3362 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
3363 b2b8bcce Iustin Pop
            file_storage_dir, err)
3364 b2b8bcce Iustin Pop
3365 778b75bb Manuel Franceschini
3366 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3367 778b75bb Manuel Franceschini
  """Rename the file storage directory.
3368 778b75bb Manuel Franceschini

3369 10c2650b Iustin Pop
  @type old_file_storage_dir: str
3370 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
3371 10c2650b Iustin Pop
  @type new_file_storage_dir: str
3372 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
3373 10c2650b Iustin Pop
  @rtype: tuple (success,)
3374 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
3375 10c2650b Iustin Pop
      whether the operation was successful
3376 778b75bb Manuel Franceschini

3377 778b75bb Manuel Franceschini
  """
3378 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3379 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3380 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
3381 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
3382 b2b8bcce Iustin Pop
      try:
3383 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
3384 b2b8bcce Iustin Pop
      except OSError, err:
3385 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
3386 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
3387 778b75bb Manuel Franceschini
    else:
3388 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
3389 b2b8bcce Iustin Pop
            old_file_storage_dir)
3390 b2b8bcce Iustin Pop
  else:
3391 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
3392 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3393 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
3394 778b75bb Manuel Franceschini
3395 778b75bb Manuel Franceschini
3396 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
3397 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
3398 ca52cdeb Michael Hanselmann

3399 10c2650b Iustin Pop
  @type file_name: str
3400 10c2650b Iustin Pop
  @param file_name: the file name we should check
3401 c8457ce7 Iustin Pop
  @rtype: None
3402 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
3403 10c2650b Iustin Pop

3404 ca52cdeb Michael Hanselmann
  """
3405 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3406 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
3407 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3408 dc31eae3 Michael Hanselmann
3409 dc31eae3 Michael Hanselmann
3410 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
3411 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
3412 dc31eae3 Michael Hanselmann

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

3416 10c2650b Iustin Pop
  @type file_name: str
3417 10c2650b Iustin Pop
  @param file_name: the job file name
3418 10c2650b Iustin Pop
  @type content: str
3419 10c2650b Iustin Pop
  @param content: the new job contents
3420 10c2650b Iustin Pop
  @rtype: boolean
3421 10c2650b Iustin Pop
  @return: the success of the operation
3422 10c2650b Iustin Pop

3423 dc31eae3 Michael Hanselmann
  """
3424 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
3425 cffbbae7 Michael Hanselmann
3426 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
3427 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
3428 ca52cdeb Michael Hanselmann
3429 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
3430 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3431 fe05a931 Michele Tartara
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3432 ca52cdeb Michael Hanselmann
3433 ca52cdeb Michael Hanselmann
3434 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
3435 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
3436 af5ebcb1 Michael Hanselmann

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

3439 10c2650b Iustin Pop
  @type old: str
3440 10c2650b Iustin Pop
  @param old: the old (actual) file name
3441 10c2650b Iustin Pop
  @type new: str
3442 10c2650b Iustin Pop
  @param new: the desired file name
3443 c8457ce7 Iustin Pop
  @rtype: tuple
3444 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
3445 10c2650b Iustin Pop

3446 af5ebcb1 Michael Hanselmann
  """
3447 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
3448 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
3449 cffbbae7 Michael Hanselmann
3450 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
3451 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
3452 af5ebcb1 Michael Hanselmann
3453 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
3454 8e5a705d René Nussbaumer
3455 fe05a931 Michele Tartara
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3456 fe05a931 Michele Tartara
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3457 af5ebcb1 Michael Hanselmann
3458 af5ebcb1 Michael Hanselmann
3459 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
3460 d61cbe76 Iustin Pop
  """Closes the given block devices.
3461 d61cbe76 Iustin Pop

3462 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
3463 10c2650b Iustin Pop
  DRBD).
3464 10c2650b Iustin Pop

3465 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
3466 b2e7666a Iustin Pop
      of this instance will be removed
3467 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
3468 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
3469 10c2650b Iustin Pop
  @rtype: tuple (success, message)
3470 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
3471 10c2650b Iustin Pop
      indicates the succes of the operation, and message
3472 10c2650b Iustin Pop
      which will contain the error details in case we
3473 10c2650b Iustin Pop
      failed
3474 d61cbe76 Iustin Pop

3475 d61cbe76 Iustin Pop
  """
3476 d61cbe76 Iustin Pop
  bdevs = []
3477 d61cbe76 Iustin Pop
  for cf in disks:
3478 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
3479 d61cbe76 Iustin Pop
    if rd is None:
3480 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
3481 d61cbe76 Iustin Pop
    bdevs.append(rd)
3482 d61cbe76 Iustin Pop
3483 d61cbe76 Iustin Pop
  msg = []
3484 d61cbe76 Iustin Pop
  for rd in bdevs:
3485 d61cbe76 Iustin Pop
    try:
3486 d61cbe76 Iustin Pop
      rd.Close()
3487 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
3488 d61cbe76 Iustin Pop
      msg.append(str(err))
3489 d61cbe76 Iustin Pop
  if msg:
3490 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3491 d61cbe76 Iustin Pop
  else:
3492 b2e7666a Iustin Pop
    if instance_name:
3493 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
3494 d61cbe76 Iustin Pop
3495 d61cbe76 Iustin Pop
3496 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
3497 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
3498 6217e295 Iustin Pop

3499 6217e295 Iustin Pop
  @type hvname: string
3500 6217e295 Iustin Pop
  @param hvname: the hypervisor name
3501 6217e295 Iustin Pop
  @type hvparams: dict
3502 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
3503 c26a6bd2 Iustin Pop
  @rtype: None
3504 6217e295 Iustin Pop

3505 6217e295 Iustin Pop
  """
3506 6217e295 Iustin Pop
  try:
3507 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
3508 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
3509 6217e295 Iustin Pop
  except errors.HypervisorError, err:
3510 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
3511 6217e295 Iustin Pop
3512 6217e295 Iustin Pop
3513 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
3514 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
3515 acd9ff9e Iustin Pop

3516 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
3517 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
3518 acd9ff9e Iustin Pop
  @type parameters: list
3519 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
3520 acd9ff9e Iustin Pop

3521 acd9ff9e Iustin Pop
  """
3522 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
3523 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
3524 acd9ff9e Iustin Pop
  if delta:
3525 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
3526 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3527 acd9ff9e Iustin Pop
3528 acd9ff9e Iustin Pop
3529 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
3530 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
3531 acd9ff9e Iustin Pop

3532 acd9ff9e Iustin Pop
  @type required: boolean
3533 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3534 acd9ff9e Iustin Pop
      failure or not
3535 acd9ff9e Iustin Pop
  @type osname: string
3536 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3537 acd9ff9e Iustin Pop
  @type checks: list
3538 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3539 acd9ff9e Iustin Pop
  @type osparams: dict
3540 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
3541 acd9ff9e Iustin Pop
  @rtype: boolean
3542 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3543 acd9ff9e Iustin Pop
      found and L{required} was false
3544 acd9ff9e Iustin Pop

3545 acd9ff9e Iustin Pop
  """
3546 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3547 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3548 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3549 acd9ff9e Iustin Pop
3550 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3551 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3552 acd9ff9e Iustin Pop
3553 acd9ff9e Iustin Pop
  if not status:
3554 acd9ff9e Iustin Pop
    if required:
3555 acd9ff9e Iustin Pop
      _Fail(tbv)
3556 acd9ff9e Iustin Pop
    else:
3557 acd9ff9e Iustin Pop
      return False
3558 acd9ff9e Iustin Pop
3559 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3560 72db3fd7 Iustin Pop
    return True
3561 72db3fd7 Iustin Pop
3562 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3563 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3564 acd9ff9e Iustin Pop
3565 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3566 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3567 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3568 acd9ff9e Iustin Pop
  if result.failed:
3569 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3570 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3571 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3572 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3573 acd9ff9e Iustin Pop
3574 acd9ff9e Iustin Pop
  return True
3575 acd9ff9e Iustin Pop
3576 acd9ff9e Iustin Pop
3577 56aa9fd5 Iustin Pop
def DemoteFromMC():
3578 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3579 56aa9fd5 Iustin Pop

3580 56aa9fd5 Iustin Pop
  """
3581 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3582 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3583 56aa9fd5 Iustin Pop
  if master == myself:
3584 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3585 f154a7a3 Michael Hanselmann
3586 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3587 f154a7a3 Michael Hanselmann
  if not result.failed:
3588 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3589 f154a7a3 Michael Hanselmann
3590 56aa9fd5 Iustin Pop
  try:
3591 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3592 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3593 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3594 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3595 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3596 f154a7a3 Michael Hanselmann
3597 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3598 56aa9fd5 Iustin Pop
3599 56aa9fd5 Iustin Pop
3600 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3601 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3602 f942a838 Michael Hanselmann

3603 f942a838 Michael Hanselmann
  """
3604 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3605 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3606 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3607 f942a838 Michael Hanselmann
3608 f942a838 Michael Hanselmann
3609 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3610 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3611 f942a838 Michael Hanselmann

3612 f942a838 Michael Hanselmann
  @type validity: int
3613 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3614 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3615 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3616 f942a838 Michael Hanselmann

3617 f942a838 Michael Hanselmann
  """
3618 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3619 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3620 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3621 f942a838 Michael Hanselmann
3622 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3623 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3624 f942a838 Michael Hanselmann
  try:
3625 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3626 f942a838 Michael Hanselmann
    assert len(name) > 5
3627 f942a838 Michael Hanselmann
3628 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3629 f942a838 Michael Hanselmann
3630 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3631 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3632 f942a838 Michael Hanselmann
3633 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3634 f942a838 Michael Hanselmann
    return (name, cert_pem)
3635 f942a838 Michael Hanselmann
  except Exception:
3636 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3637 f942a838 Michael Hanselmann
    raise
3638 f942a838 Michael Hanselmann
3639 f942a838 Michael Hanselmann
3640 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3641 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3642 f942a838 Michael Hanselmann

3643 f942a838 Michael Hanselmann
  @type name: string
3644 f942a838 Michael Hanselmann
  @param name: Certificate name
3645 f942a838 Michael Hanselmann

3646 f942a838 Michael Hanselmann
  """
3647 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3648 f942a838 Michael Hanselmann
3649 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3650 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3651 f942a838 Michael Hanselmann
3652 f942a838 Michael Hanselmann
  try:
3653 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3654 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3655 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3656 f942a838 Michael Hanselmann
          cert_dir, err)
3657 f942a838 Michael Hanselmann
3658 f942a838 Michael Hanselmann
3659 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3660 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3661 1651d116 Michael Hanselmann

3662 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3663 1651d116 Michael Hanselmann
  @param instance: The instance object
3664 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3665 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3666 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3667 1651d116 Michael Hanselmann

3668 1651d116 Michael Hanselmann
  """
3669 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3670 1651d116 Michael Hanselmann
3671 1651d116 Michael Hanselmann
  env = None
3672 1651d116 Michael Hanselmann
  prefix = None
3673 1651d116 Michael Hanselmann
  suffix = None
3674 2ad5550d Michael Hanselmann
  exp_size = None
3675 1651d116 Michael Hanselmann
3676 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
3677 1651d116 Michael Hanselmann
    (filename, ) = ieargs
3678 1651d116 Michael Hanselmann
3679 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
3680 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
3681 1651d116 Michael Hanselmann
3682 748c9884 René Nussbaumer
    real_filename = os.path.realpath(filename)
3683 748c9884 René Nussbaumer
    directory = os.path.dirname(real_filename)
3684 1651d116 Michael Hanselmann
3685 710f30ec Michael Hanselmann
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3686 748c9884 René Nussbaumer
      _Fail("File '%s' is not under exports directory '%s': %s",
3687 710f30ec Michael Hanselmann
            filename, pathutils.EXPORT_DIR, real_filename)
3688 1651d116 Michael Hanselmann
3689 1651d116 Michael Hanselmann
    # Create directory
3690 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
3691 1651d116 Michael Hanselmann
3692 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
3693 1651d116 Michael Hanselmann
3694 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3695 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
3696 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3697 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
3698 1651d116 Michael Hanselmann
3699 2ad5550d Michael Hanselmann
      # Retrieve file size
3700 2ad5550d Michael Hanselmann
      try:
3701 2ad5550d Michael Hanselmann
        st = os.stat(filename)
3702 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
3703 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
3704 2ad5550d Michael Hanselmann
      else:
3705 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
3706 2ad5550d Michael Hanselmann
3707 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
3708 1651d116 Michael Hanselmann
    (disk, ) = ieargs
3709 1651d116 Michael Hanselmann
3710 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3711 1651d116 Michael Hanselmann
3712 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3713 a986a581 Thomas Thrainer
      # we use nocreat to fail if the device is not already there or we pass a
3714 a986a581 Thomas Thrainer
      # wrong path; we use notrunc to no attempt truncate on an LV device
3715 a986a581 Thomas Thrainer
      suffix = utils.BuildShellCmd("| dd of=%s conv=nocreat,notrunc bs=%s",
3716 a986a581 Thomas Thrainer
                                   real_disk.dev_path,
3717 a986a581 Thomas Thrainer
                                   str(1024 * 1024)) # 1 MB
3718 1651d116 Michael Hanselmann
3719 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3720 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
3721 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3722 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
3723 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
3724 1651d116 Michael Hanselmann
                                   str(disk.size))
3725 2ad5550d Michael Hanselmann
      exp_size = disk.size
3726 1651d116 Michael Hanselmann
3727 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
3728 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
3729 1651d116 Michael Hanselmann
3730 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
3731 1651d116 Michael Hanselmann
3732 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
3733 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
3734 1651d116 Michael Hanselmann
3735 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3736 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3737 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
3738 1651d116 Michael Hanselmann
      script = inst_os.import_script
3739 1651d116 Michael Hanselmann
3740 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3741 0c3d9c7c Thomas Thrainer
      real_disk = _OpenRealBD(disk)
3742 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
3743 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
3744 1651d116 Michael Hanselmann
      script = inst_os.export_script
3745 1651d116 Michael Hanselmann
3746 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
3747 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3748 1651d116 Michael Hanselmann
3749 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3750 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
3751 1651d116 Michael Hanselmann
3752 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3753 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
3754 1651d116 Michael Hanselmann
3755 2ad5550d Michael Hanselmann
    # Let script predict size
3756 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
3757 2ad5550d Michael Hanselmann
3758 1651d116 Michael Hanselmann
  else:
3759 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3760 1651d116 Michael Hanselmann
3761 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
3762 1651d116 Michael Hanselmann
3763 1651d116 Michael Hanselmann
3764 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
3765 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
3766 1651d116 Michael Hanselmann

3767 1651d116 Michael Hanselmann
  """
3768 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3769 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3770 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3771 1651d116 Michael Hanselmann
3772 1651d116 Michael Hanselmann
3773 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3774 6613661a Iustin Pop
                            ieio, ieioargs):
3775 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3776 1651d116 Michael Hanselmann

3777 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3778 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3779 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3780 1651d116 Michael Hanselmann
  @type host: string
3781 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3782 1651d116 Michael Hanselmann
  @type port: int
3783 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3784 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3785 1651d116 Michael Hanselmann
  @param instance: Instance object
3786 6613661a Iustin Pop
  @type component: string
3787 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3788 6613661a Iustin Pop
      e.g. 'disk/0'
3789 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3790 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3791 1651d116 Michael Hanselmann

3792 1651d116 Michael Hanselmann
  """
3793 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
3794 1651d116 Michael Hanselmann
    prefix = "import"
3795 1651d116 Michael Hanselmann
3796 1651d116 Michael Hanselmann
    if not (host is None and port is None):
3797 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
3798 1651d116 Michael Hanselmann
3799 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
3800 1651d116 Michael Hanselmann
    prefix = "export"
3801 1651d116 Michael Hanselmann
3802 1651d116 Michael Hanselmann
    if host is None or port is None:
3803 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
3804 1651d116 Michael Hanselmann
3805 1651d116 Michael Hanselmann
  else:
3806 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
3807 1651d116 Michael Hanselmann
3808 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
3809 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
3810 1651d116 Michael Hanselmann
3811 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3812 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3813 1651d116 Michael Hanselmann
3814 eb630f50 Michael Hanselmann
  if opts.key_name is None:
3815 1651d116 Michael Hanselmann
    # Use server.pem
3816 710f30ec Michael Hanselmann
    key_path = pathutils.NODED_CERT_FILE
3817 710f30ec Michael Hanselmann
    cert_path = pathutils.NODED_CERT_FILE
3818 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
3819 1651d116 Michael Hanselmann
  else:
3820 710f30ec Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3821 eb630f50 Michael Hanselmann
                                                 opts.key_name)
3822 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
3823 1651d116 Michael Hanselmann
3824 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
3825 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
3826 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
3827 63bcea2a Michael Hanselmann
3828 6613661a Iustin Pop
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3829 1651d116 Michael Hanselmann
  try:
3830 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3831 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3832 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3833 1651d116 Michael Hanselmann
3834 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
3835 1651d116 Michael Hanselmann
      # Use server.pem
3836 710f30ec Michael Hanselmann
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3837 eb630f50 Michael Hanselmann
    else:
3838 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
3839 63bcea2a Michael Hanselmann
3840 eb630f50 Michael Hanselmann
    # Write CA file
3841 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
3842 1651d116 Michael Hanselmann
3843 1651d116 Michael Hanselmann
    cmd = [
3844 710f30ec Michael Hanselmann
      pathutils.IMPORT_EXPORT_DAEMON,
3845 1651d116 Michael Hanselmann
      status_file, mode,
3846 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
3847 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
3848 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
3849 1651d116 Michael Hanselmann
      ]
3850 1651d116 Michael Hanselmann
3851 1651d116 Michael Hanselmann
    if host:
3852 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
3853 1651d116 Michael Hanselmann
3854 1651d116 Michael Hanselmann
    if port:
3855 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
3856 1651d116 Michael Hanselmann
3857 855d2fc7 Michael Hanselmann
    if opts.ipv6:
3858 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
3859 855d2fc7 Michael Hanselmann
    else:
3860 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
3861 855d2fc7 Michael Hanselmann
3862 a5310c2a Michael Hanselmann
    if opts.compress:
3863 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
3864 a5310c2a Michael Hanselmann
3865 af1d39b1 Michael Hanselmann
    if opts.magic:
3866 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
3867 af1d39b1 Michael Hanselmann
3868 2ad5550d Michael Hanselmann
    if exp_size is not None:
3869 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
3870 2ad5550d Michael Hanselmann
3871 1651d116 Michael Hanselmann
    if cmd_prefix:
3872 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3873 1651d116 Michael Hanselmann
3874 1651d116 Michael Hanselmann
    if cmd_suffix:
3875 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3876 1651d116 Michael Hanselmann
3877 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
3878 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
3879 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3880 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3881 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
3882 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
3883 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
3884 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3885 4478301b Michael Hanselmann
3886 6aa7a354 Iustin Pop
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3887 1651d116 Michael Hanselmann
3888 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3889 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
3890 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3891 1651d116 Michael Hanselmann
                      output=logfile)
3892 1651d116 Michael Hanselmann
3893 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
3894 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
3895 1651d116 Michael Hanselmann
3896 1651d116 Michael Hanselmann
  except Exception:
3897 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
3898 1651d116 Michael Hanselmann
    raise
3899 1651d116 Michael Hanselmann
3900 1651d116 Michael Hanselmann
3901 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
3902 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
3903 1651d116 Michael Hanselmann

3904 1651d116 Michael Hanselmann
  @type names: sequence
3905 1651d116 Michael Hanselmann
  @param names: List of names
3906 1651d116 Michael Hanselmann
  @rtype: List of dicts
3907 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3908 1651d116 Michael Hanselmann
           status couldn't be read
3909 1651d116 Michael Hanselmann

3910 1651d116 Michael Hanselmann
  """
3911 1651d116 Michael Hanselmann
  result = []
3912 1651d116 Michael Hanselmann
3913 1651d116 Michael Hanselmann
  for name in names:
3914 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3915 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3916 1651d116 Michael Hanselmann
3917 1651d116 Michael Hanselmann
    try:
3918 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3919 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3920 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3921 1651d116 Michael Hanselmann
        raise
3922 1651d116 Michael Hanselmann
      data = None
3923 1651d116 Michael Hanselmann
3924 1651d116 Michael Hanselmann
    if not data:
3925 1651d116 Michael Hanselmann
      result.append(None)
3926 1651d116 Michael Hanselmann
      continue
3927 1651d116 Michael Hanselmann
3928 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3929 1651d116 Michael Hanselmann
3930 1651d116 Michael Hanselmann
  return result
3931 1651d116 Michael Hanselmann
3932 1651d116 Michael Hanselmann
3933 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3934 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3935 f81c4737 Michael Hanselmann

3936 f81c4737 Michael Hanselmann
  """
3937 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3938 f81c4737 Michael Hanselmann
3939 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3940 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3941 f81c4737 Michael Hanselmann
3942 f81c4737 Michael Hanselmann
  if pid:
3943 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3944 f81c4737 Michael Hanselmann
                 name, pid)
3945 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3946 f81c4737 Michael Hanselmann
3947 f81c4737 Michael Hanselmann
3948 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3949 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3950 1651d116 Michael Hanselmann

3951 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3952 1651d116 Michael Hanselmann
  whole status directory is removed.
3953 1651d116 Michael Hanselmann

3954 1651d116 Michael Hanselmann
  """
3955 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3956 1651d116 Michael Hanselmann
3957 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3958 1651d116 Michael Hanselmann
3959 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3960 1651d116 Michael Hanselmann
3961 1651d116 Michael Hanselmann
  if pid:
3962 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3963 1651d116 Michael Hanselmann
                 name, pid)
3964 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3965 1651d116 Michael Hanselmann
3966 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3967 1651d116 Michael Hanselmann
3968 1651d116 Michael Hanselmann
3969 0c3d9c7c Thomas Thrainer
def _FindDisks(disks):
3970 0c3d9c7c Thomas Thrainer
  """Finds attached L{BlockDev}s for the given disks.
3971 6b93ec9d Iustin Pop

3972 0c3d9c7c Thomas Thrainer
  @type disks: list of L{objects.Disk}
3973 0c3d9c7c Thomas Thrainer
  @param disks: the disk objects we need to find
3974 235a6b29 Thomas Thrainer

3975 0c3d9c7c Thomas Thrainer
  @return: list of L{BlockDev} objects or C{None} if a given disk
3976 0c3d9c7c Thomas Thrainer
           was not found or was no attached.
3977 235a6b29 Thomas Thrainer

3978 235a6b29 Thomas Thrainer
  """
3979 6b93ec9d Iustin Pop
  bdevs = []
3980 6b93ec9d Iustin Pop
3981 0c3d9c7c Thomas Thrainer
  for disk in disks:
3982 0c3d9c7c Thomas Thrainer
    rd = _RecursiveFindBD(disk)
3983 6b93ec9d Iustin Pop
    if rd is None:
3984 0c3d9c7c Thomas Thrainer
      _Fail("Can't find device %s", disk)
3985 6b93ec9d Iustin Pop
    bdevs.append(rd)
3986 5a533f8a Iustin Pop
  return bdevs
3987 6b93ec9d Iustin Pop
3988 6b93ec9d Iustin Pop
3989 0c3d9c7c Thomas Thrainer
def DrbdDisconnectNet(disks):
3990 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3991 6b93ec9d Iustin Pop

3992 6b93ec9d Iustin Pop
  """
3993 0c3d9c7c Thomas Thrainer
  bdevs = _FindDisks(disks)
3994 6b93ec9d Iustin Pop
3995 6b93ec9d Iustin Pop
  # disconnect disks
3996 6b93ec9d Iustin Pop
  for rd in bdevs:
3997 6b93ec9d Iustin Pop
    try:
3998 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3999 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
4000 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
4001 2cc6781a Iustin Pop
            err, exc=True)
4002 6b93ec9d Iustin Pop
4003 6b93ec9d Iustin Pop
4004 0c3d9c7c Thomas Thrainer
def DrbdAttachNet(disks, instance_name, multimaster):
4005 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
4006 6b93ec9d Iustin Pop

4007 6b93ec9d Iustin Pop
  """
4008 0c3d9c7c Thomas Thrainer
  bdevs = _FindDisks(disks)
4009 6b93ec9d Iustin Pop
4010 6b93ec9d Iustin Pop
  if multimaster:
4011 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
4012 6b93ec9d Iustin Pop
      try:
4013 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
4014 6b93ec9d Iustin Pop
      except EnvironmentError, err:
4015 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
4016 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
4017 6b93ec9d Iustin Pop
  # needed primary mode
4018 6b93ec9d Iustin Pop
  for rd in bdevs:
4019 6b93ec9d Iustin Pop
    try:
4020 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
4021 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
4022 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
4023 3c0cdc83 Michael Hanselmann
4024 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
4025 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
4026 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
4027 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
4028 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
4029 3c0cdc83 Michael Hanselmann
4030 3c0cdc83 Michael Hanselmann
  def _Attach():
4031 6b93ec9d Iustin Pop
    all_connected = True
4032 3c0cdc83 Michael Hanselmann
4033 6b93ec9d Iustin Pop
    for rd in bdevs:
4034 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
4035 3c0cdc83 Michael Hanselmann
4036 73e15b5e Apollon Oikonomopoulos
      if multimaster:
4037 73e15b5e Apollon Oikonomopoulos
        # In the multimaster case we have to wait explicitly until
4038 73e15b5e Apollon Oikonomopoulos
        # the resource is Connected and UpToDate/UpToDate, because
4039 73e15b5e Apollon Oikonomopoulos
        # we promote *both nodes* to primary directly afterwards.
4040 73e15b5e Apollon Oikonomopoulos
        # Being in resync is not enough, since there is a race during which we
4041 73e15b5e Apollon Oikonomopoulos
        # may promote a node with an Outdated disk to primary, effectively
4042 73e15b5e Apollon Oikonomopoulos
        # tearing down the connection.
4043 73e15b5e Apollon Oikonomopoulos
        all_connected = (all_connected and
4044 73e15b5e Apollon Oikonomopoulos
                         stats.is_connected and
4045 73e15b5e Apollon Oikonomopoulos
                         stats.is_disk_uptodate and
4046 73e15b5e Apollon Oikonomopoulos
                         stats.peer_disk_uptodate)
4047 73e15b5e Apollon Oikonomopoulos
      else:
4048 73e15b5e Apollon Oikonomopoulos
        all_connected = (all_connected and
4049 73e15b5e Apollon Oikonomopoulos
                         (stats.is_connected or stats.is_in_resync))
4050 3c0cdc83 Michael Hanselmann
4051 6b93ec9d Iustin Pop
      if stats.is_standalone:
4052 6b93ec9d Iustin Pop
        # peer had different config info and this node became
4053 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
4054 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
4055 6b93ec9d Iustin Pop
        try:
4056 c738375b Iustin Pop
          rd.AttachNet(multimaster)
4057 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
4058 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
4059 3c0cdc83 Michael Hanselmann
4060 3c0cdc83 Michael Hanselmann
    if not all_connected:
4061 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
4062 3c0cdc83 Michael Hanselmann
4063 3c0cdc83 Michael Hanselmann
  try:
4064 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
4065 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
4066 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
4067 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
4068 3c0cdc83 Michael Hanselmann
4069 6b93ec9d Iustin Pop
  if multimaster:
4070 6b93ec9d Iustin Pop
    # change to primary mode
4071 6b93ec9d Iustin Pop
    for rd in bdevs:
4072 d3da87b8 Iustin Pop
      try:
4073 d3da87b8 Iustin Pop
        rd.Open()
4074 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
4075 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
4076 6b93ec9d Iustin Pop
4077 6b93ec9d Iustin Pop
4078 0c3d9c7c Thomas Thrainer
def DrbdWaitSync(disks):
4079 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
4080 6b93ec9d Iustin Pop

4081 6b93ec9d Iustin Pop
  """
4082 db8667b7 Iustin Pop
  def _helper(rd):
4083 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
4084 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
4085 db8667b7 Iustin Pop
      raise utils.RetryAgain()
4086 db8667b7 Iustin Pop
    return stats
4087 db8667b7 Iustin Pop
4088 0c3d9c7c Thomas Thrainer
  bdevs = _FindDisks(disks)
4089 6b93ec9d Iustin Pop
4090 6b93ec9d Iustin Pop
  min_resync = 100
4091 6b93ec9d Iustin Pop
  alldone = True
4092 6b93ec9d Iustin Pop
  for rd in bdevs:
4093 db8667b7 Iustin Pop
    try:
4094 db8667b7 Iustin Pop
      # poll each second for 15 seconds
4095 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
4096 db8667b7 Iustin Pop
    except utils.RetryTimeout:
4097 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
4098 db8667b7 Iustin Pop
      # last check
4099 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
4100 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
4101 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
4102 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
4103 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
4104 afdc3985 Iustin Pop
4105 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
4106 6b93ec9d Iustin Pop
4107 6b93ec9d Iustin Pop
4108 0c3d9c7c Thomas Thrainer
def DrbdNeedsActivation(disks):
4109 235a6b29 Thomas Thrainer
  """Checks which of the passed disks needs activation and returns their UUIDs.
4110 235a6b29 Thomas Thrainer

4111 235a6b29 Thomas Thrainer
  """
4112 235a6b29 Thomas Thrainer
  faulty_disks = []
4113 235a6b29 Thomas Thrainer
4114 235a6b29 Thomas Thrainer
  for disk in disks:
4115 235a6b29 Thomas Thrainer
    rd = _RecursiveFindBD(disk)
4116 235a6b29 Thomas Thrainer
    if rd is None:
4117 235a6b29 Thomas Thrainer
      faulty_disks.append(disk)
4118 235a6b29 Thomas Thrainer
      continue
4119 235a6b29 Thomas Thrainer
4120 235a6b29 Thomas Thrainer
    stats = rd.GetProcStatus()
4121 235a6b29 Thomas Thrainer
    if stats.is_standalone or stats.is_diskless:
4122 235a6b29 Thomas Thrainer
      faulty_disks.append(disk)
4123 235a6b29 Thomas Thrainer
4124 235a6b29 Thomas Thrainer
  return [disk.uuid for disk in faulty_disks]
4125 235a6b29 Thomas Thrainer
4126 235a6b29 Thomas Thrainer
4127 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
4128 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
4129 c46b9782 Luca Bigliardi

4130 c46b9782 Luca Bigliardi
  """
4131 c46b9782 Luca Bigliardi
  try:
4132 47e0abee Thomas Thrainer
    return drbd.DRBD8.GetUsermodeHelper()
4133 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
4134 c46b9782 Luca Bigliardi
    _Fail(str(err))
4135 c46b9782 Luca Bigliardi
4136 c46b9782 Luca Bigliardi
4137 8ef418bb Helga Velroyen
def PowercycleNode(hypervisor_type, hvparams=None):
4138 f5118ade Iustin Pop
  """Hard-powercycle the node.
4139 f5118ade Iustin Pop

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

4143 f5118ade Iustin Pop
  """
4144 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4145 f5118ade Iustin Pop
  try:
4146 f5118ade Iustin Pop
    pid = os.fork()
4147 29921401 Iustin Pop
  except OSError:
4148 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
4149 f5118ade Iustin Pop
    pid = 0
4150 f5118ade Iustin Pop
  if pid > 0:
4151 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
4152 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
4153 1af6ac0f Luca Bigliardi
  try:
4154 1af6ac0f Luca Bigliardi
    utils.Mlockall()
4155 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
4156 1af6ac0f Luca Bigliardi
    pass
4157 f5118ade Iustin Pop
  time.sleep(5)
4158 8ef418bb Helga Velroyen
  hyper.PowercycleNode(hvparams=hvparams)
4159 f5118ade Iustin Pop
4160 f5118ade Iustin Pop
4161 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
4162 45bc4635 Iustin Pop
  """Verifies a restricted command name.
4163 1a2eb2dc Michael Hanselmann

4164 1a2eb2dc Michael Hanselmann
  @type cmd: string
4165 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4166 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
4167 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4168 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
4169 1a2eb2dc Michael Hanselmann

4170 1a2eb2dc Michael Hanselmann
  """
4171 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
4172 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
4173 1a2eb2dc Michael Hanselmann
4174 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
4175 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
4176 1a2eb2dc Michael Hanselmann
4177 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4178 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
4179 1a2eb2dc Michael Hanselmann
4180 1a2eb2dc Michael Hanselmann
  return (True, None)
4181 1a2eb2dc Michael Hanselmann
4182 1a2eb2dc Michael Hanselmann
4183 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
4184 45bc4635 Iustin Pop
  """Common checks for restricted command file system directories and files.
4185 1a2eb2dc Michael Hanselmann

4186 1a2eb2dc Michael Hanselmann
  @type path: string
4187 1a2eb2dc Michael Hanselmann
  @param path: Path to check
4188 1a2eb2dc Michael Hanselmann
  @param owner: C{None} or tuple containing UID and GID
4189 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or C{os.stat} result)
4190 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4191 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's the result of C{os.stat}
4192 1a2eb2dc Michael Hanselmann

4193 1a2eb2dc Michael Hanselmann
  """
4194 1a2eb2dc Michael Hanselmann
  if owner is None:
4195 1a2eb2dc Michael Hanselmann
    # Default to root as owner
4196 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
4197 1a2eb2dc Michael Hanselmann
4198 1a2eb2dc Michael Hanselmann
  try:
4199 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
4200 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
4201 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4202 1a2eb2dc Michael Hanselmann
4203 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
4204 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
4205 1a2eb2dc Michael Hanselmann
4206 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
4207 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
4208 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4209 1a2eb2dc Michael Hanselmann
4210 1a2eb2dc Michael Hanselmann
  return (True, st)
4211 1a2eb2dc Michael Hanselmann
4212 1a2eb2dc Michael Hanselmann
4213 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4214 45bc4635 Iustin Pop
  """Verifies restricted command directory.
4215 1a2eb2dc Michael Hanselmann

4216 1a2eb2dc Michael Hanselmann
  @type path: string
4217 1a2eb2dc Michael Hanselmann
  @param path: Path to check
4218 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
4219 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4220 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
4221 1a2eb2dc Michael Hanselmann

4222 1a2eb2dc Michael Hanselmann
  """
4223 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4224 1a2eb2dc Michael Hanselmann
4225 1a2eb2dc Michael Hanselmann
  if not status:
4226 1a2eb2dc Michael Hanselmann
    return (False, value)
4227 1a2eb2dc Michael Hanselmann
4228 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
4229 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
4230 1a2eb2dc Michael Hanselmann
4231 1a2eb2dc Michael Hanselmann
  return (True, None)
4232 1a2eb2dc Michael Hanselmann
4233 1a2eb2dc Michael Hanselmann
4234 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4235 45bc4635 Iustin Pop
  """Verifies a whole restricted command and returns its executable filename.
4236 1a2eb2dc Michael Hanselmann

4237 1a2eb2dc Michael Hanselmann
  @type path: string
4238 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
4239 1a2eb2dc Michael Hanselmann
  @type cmd: string
4240 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4241 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
4242 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4243 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
4244 1a2eb2dc Michael Hanselmann
    absolute path to the executable
4245 1a2eb2dc Michael Hanselmann

4246 1a2eb2dc Michael Hanselmann
  """
4247 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
4248 1a2eb2dc Michael Hanselmann
4249 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4250 1a2eb2dc Michael Hanselmann
4251 1a2eb2dc Michael Hanselmann
  if not status:
4252 1a2eb2dc Michael Hanselmann
    return (False, msg)
4253 1a2eb2dc Michael Hanselmann
4254 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
4255 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4256 1a2eb2dc Michael Hanselmann
4257 1a2eb2dc Michael Hanselmann
  return (True, executable)
4258 1a2eb2dc Michael Hanselmann
4259 1a2eb2dc Michael Hanselmann
4260 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
4261 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4262 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
4263 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
4264 45bc4635 Iustin Pop
  """Performs a number of tests on a restricted command.
4265 1a2eb2dc Michael Hanselmann

4266 1a2eb2dc Michael Hanselmann
  @type path: string
4267 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
4268 1a2eb2dc Michael Hanselmann
  @type cmd: string
4269 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4270 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
4271 1a2eb2dc Michael Hanselmann

4272 1a2eb2dc Michael Hanselmann
  """
4273 1a2eb2dc Michael Hanselmann
  # Verify the directory first
4274 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
4275 1a2eb2dc Michael Hanselmann
  if status:
4276 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
4277 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
4278 1a2eb2dc Michael Hanselmann
4279 1a2eb2dc Michael Hanselmann
  if not status:
4280 1a2eb2dc Michael Hanselmann
    return (False, msg)
4281 1a2eb2dc Michael Hanselmann
4282 1a2eb2dc Michael Hanselmann
  # Check actual executable
4283 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
4284 1a2eb2dc Michael Hanselmann
4285 1a2eb2dc Michael Hanselmann
4286 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
4287 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4288 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4289 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4290 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
4291 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
4292 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
4293 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4294 45bc4635 Iustin Pop
  """Executes a restricted command after performing strict tests.
4295 1a2eb2dc Michael Hanselmann

4296 1a2eb2dc Michael Hanselmann
  @type cmd: string
4297 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4298 1a2eb2dc Michael Hanselmann
  @rtype: string
4299 1a2eb2dc Michael Hanselmann
  @return: Command output
4300 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
4301 1a2eb2dc Michael Hanselmann

4302 1a2eb2dc Michael Hanselmann
  """
4303 45bc4635 Iustin Pop
  logging.info("Preparing to run restricted command '%s'", cmd)
4304 1a2eb2dc Michael Hanselmann
4305 1a2eb2dc Michael Hanselmann
  if not _enabled:
4306 45bc4635 Iustin Pop
    _Fail("Restricted commands disabled at configure time")
4307 1a2eb2dc Michael Hanselmann
4308 1a2eb2dc Michael Hanselmann
  lock = None
4309 1a2eb2dc Michael Hanselmann
  try:
4310 1a2eb2dc Michael Hanselmann
    cmdresult = None
4311 1a2eb2dc Michael Hanselmann
    try:
4312 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
4313 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4314 1a2eb2dc Michael Hanselmann
4315 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
4316 1a2eb2dc Michael Hanselmann
4317 1a2eb2dc Michael Hanselmann
      if status:
4318 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4319 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
4320 1a2eb2dc Michael Hanselmann
      else:
4321 1a2eb2dc Michael Hanselmann
        logging.error(value)
4322 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
4323 1a2eb2dc Michael Hanselmann
      # Keep original error in log
4324 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
4325 1a2eb2dc Michael Hanselmann
4326 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
4327 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
4328 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
4329 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
4330 1a2eb2dc Michael Hanselmann
4331 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
4332 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
4333 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
4334 45bc4635 Iustin Pop
      _Fail("Restricted command '%s' failed: %s; output: %s",
4335 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
4336 1a2eb2dc Michael Hanselmann
    else:
4337 1a2eb2dc Michael Hanselmann
      return cmdresult.output
4338 1a2eb2dc Michael Hanselmann
  finally:
4339 1a2eb2dc Michael Hanselmann
    if lock is not None:
4340 1a2eb2dc Michael Hanselmann
      # Release lock at last
4341 1a2eb2dc Michael Hanselmann
      lock.Close()
4342 1a2eb2dc Michael Hanselmann
      lock = None
4343 1a2eb2dc Michael Hanselmann
4344 1a2eb2dc Michael Hanselmann
4345 99e222b1 Michael Hanselmann
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4346 99e222b1 Michael Hanselmann
  """Creates or removes the watcher pause file.
4347 99e222b1 Michael Hanselmann

4348 99e222b1 Michael Hanselmann
  @type until: None or number
4349 99e222b1 Michael Hanselmann
  @param until: Unix timestamp saying until when the watcher shouldn't run
4350 99e222b1 Michael Hanselmann

4351 99e222b1 Michael Hanselmann
  """
4352 99e222b1 Michael Hanselmann
  if until is None:
4353 99e222b1 Michael Hanselmann
    logging.info("Received request to no longer pause watcher")
4354 99e222b1 Michael Hanselmann
    utils.RemoveFile(_filename)
4355 99e222b1 Michael Hanselmann
  else:
4356 99e222b1 Michael Hanselmann
    logging.info("Received request to pause watcher until %s", until)
4357 99e222b1 Michael Hanselmann
4358 99e222b1 Michael Hanselmann
    if not ht.TNumber(until):
4359 99e222b1 Michael Hanselmann
      _Fail("Duration must be numeric")
4360 99e222b1 Michael Hanselmann
4361 99e222b1 Michael Hanselmann
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
4362 99e222b1 Michael Hanselmann
4363 99e222b1 Michael Hanselmann
4364 4daa5eb9 Sebastian Gebhard
def ConfigureOVS(ovs_name, ovs_link):
4365 4daa5eb9 Sebastian Gebhard
  """Creates a OpenvSwitch on the node.
4366 4daa5eb9 Sebastian Gebhard

4367 4daa5eb9 Sebastian Gebhard
  This function sets up a OpenvSwitch on the node with given name nad
4368 4daa5eb9 Sebastian Gebhard
  connects it via a given eth device.
4369 4daa5eb9 Sebastian Gebhard

4370 4daa5eb9 Sebastian Gebhard
  @type ovs_name: string
4371 4daa5eb9 Sebastian Gebhard
  @param ovs_name: Name of the OpenvSwitch to create.
4372 4daa5eb9 Sebastian Gebhard
  @type ovs_link: None or string
4373 4daa5eb9 Sebastian Gebhard
  @param ovs_link: Ethernet device for outside connection (can be missing)
4374 4daa5eb9 Sebastian Gebhard

4375 4daa5eb9 Sebastian Gebhard
  """
4376 4daa5eb9 Sebastian Gebhard
  # Initialize the OpenvSwitch
4377 4daa5eb9 Sebastian Gebhard
  result = utils.RunCmd(["ovs-vsctl", "add-br", ovs_name])
4378 4daa5eb9 Sebastian Gebhard
  if result.failed:
4379 a1578ccf Sebastian Gebhard
    _Fail("Failed to create openvswitch. Script return value: %s, output: '%s'"
4380 a1578ccf Sebastian Gebhard
          % (result.exit_code, result.output), log=True)
4381 4daa5eb9 Sebastian Gebhard
4382 4daa5eb9 Sebastian Gebhard
  # And connect it to a physical interface, if given
4383 4daa5eb9 Sebastian Gebhard
  if ovs_link:
4384 4daa5eb9 Sebastian Gebhard
    result = utils.RunCmd(["ovs-vsctl", "add-port", ovs_name, ovs_link])
4385 4daa5eb9 Sebastian Gebhard
    if result.failed:
4386 4daa5eb9 Sebastian Gebhard
      _Fail("Failed to connect openvswitch to  interface %s. Script return"
4387 a1578ccf Sebastian Gebhard
            " value: %s, output: '%s'" % (ovs_link, result.exit_code,
4388 a1578ccf Sebastian Gebhard
            result.output), log=True)
4389 4daa5eb9 Sebastian Gebhard
4390 4daa5eb9 Sebastian Gebhard
4391 a8083063 Iustin Pop
class HooksRunner(object):
4392 a8083063 Iustin Pop
  """Hook runner.
4393 a8083063 Iustin Pop

4394 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
4395 10c2650b Iustin Pop
  on the master side.
4396 a8083063 Iustin Pop

4397 a8083063 Iustin Pop
  """
4398 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
4399 a8083063 Iustin Pop
    """Constructor for hooks runner.
4400 a8083063 Iustin Pop

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

4405 a8083063 Iustin Pop
    """
4406 a8083063 Iustin Pop
    if hooks_base_dir is None:
4407 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4408 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4409 fe267188 Iustin Pop
    # constant
4410 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4411 a8083063 Iustin Pop
4412 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
4413 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
4414 0fa481f5 Andrea Spadaccini

4415 0fa481f5 Andrea Spadaccini
    """
4416 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
4417 0fa481f5 Andrea Spadaccini
    node = node_list[0]
4418 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
4419 0fa481f5 Andrea Spadaccini
    assert node == myself
4420 0fa481f5 Andrea Spadaccini
4421 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
4422 0fa481f5 Andrea Spadaccini
4423 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
4424 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
4425 0fa481f5 Andrea Spadaccini
4426 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
4427 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
4428 a8083063 Iustin Pop

4429 10c2650b Iustin Pop
    @type hpath: str
4430 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
4431 10c2650b Iustin Pop
        holds the scripts
4432 10c2650b Iustin Pop
    @type phase: str
4433 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4434 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
4435 10c2650b Iustin Pop
    @type env: dict
4436 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
4437 10c2650b Iustin Pop
    @rtype: list
4438 10c2650b Iustin Pop
    @return: list of 3-element tuples:
4439 10c2650b Iustin Pop
      - script path
4440 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
4441 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
4442 10c2650b Iustin Pop
      - output of the script
4443 10c2650b Iustin Pop

4444 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
4445 10c2650b Iustin Pop
        parameters
4446 a8083063 Iustin Pop

4447 a8083063 Iustin Pop
    """
4448 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
4449 a8083063 Iustin Pop
      suffix = "pre"
4450 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
4451 a8083063 Iustin Pop
      suffix = "post"
4452 a8083063 Iustin Pop
    else:
4453 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
4454 3fb4f740 Iustin Pop
4455 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
4456 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4457 6bb65e3a Guido Trotter
4458 6bb65e3a Guido Trotter
    results = []
4459 a9b7e346 Iustin Pop
4460 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
4461 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
4462 a9b7e346 Iustin Pop
      # warning at every operation
4463 a9b7e346 Iustin Pop
      return results
4464 a9b7e346 Iustin Pop
4465 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4466 a9b7e346 Iustin Pop
4467 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
4468 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
4469 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
4470 a8083063 Iustin Pop
        output = ""
4471 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
4472 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
4473 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
4474 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
4475 6bb65e3a Guido Trotter
        if runresult.failed:
4476 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
4477 a8083063 Iustin Pop
        else:
4478 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
4479 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
4480 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4481 6bb65e3a Guido Trotter
4482 6bb65e3a Guido Trotter
    return results
4483 3f78eef2 Iustin Pop
4484 3f78eef2 Iustin Pop
4485 8d528b7c Iustin Pop
class IAllocatorRunner(object):
4486 8d528b7c Iustin Pop
  """IAllocator runner.
4487 8d528b7c Iustin Pop

4488 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
4489 8d528b7c Iustin Pop
  the master side.
4490 8d528b7c Iustin Pop

4491 8d528b7c Iustin Pop
  """
4492 7e950d31 Iustin Pop
  @staticmethod
4493 7e950d31 Iustin Pop
  def Run(name, idata):
4494 8d528b7c Iustin Pop
    """Run an iallocator script.
4495 8d528b7c Iustin Pop

4496 10c2650b Iustin Pop
    @type name: str
4497 10c2650b Iustin Pop
    @param name: the iallocator script name
4498 10c2650b Iustin Pop
    @type idata: str
4499 10c2650b Iustin Pop
    @param idata: the allocator input data
4500 10c2650b Iustin Pop

4501 10c2650b Iustin Pop
    @rtype: tuple
4502 87f5c298 Iustin Pop
    @return: two element tuple of:
4503 87f5c298 Iustin Pop
       - status
4504 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
4505 8d528b7c Iustin Pop

4506 8d528b7c Iustin Pop
    """
4507 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4508 8d528b7c Iustin Pop
                                  os.path.isfile)
4509 8d528b7c Iustin Pop
    if alloc_script is None:
4510 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
4511 8d528b7c Iustin Pop
4512 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4513 8d528b7c Iustin Pop
    try:
4514 8d528b7c Iustin Pop
      os.write(fd, idata)
4515 8d528b7c Iustin Pop
      os.close(fd)
4516 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
4517 8d528b7c Iustin Pop
      if result.failed:
4518 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4519 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
4520 8d528b7c Iustin Pop
    finally:
4521 8d528b7c Iustin Pop
      os.unlink(fin_name)
4522 8d528b7c Iustin Pop
4523 c26a6bd2 Iustin Pop
    return result.stdout
4524 8d528b7c Iustin Pop
4525 8d528b7c Iustin Pop
4526 3f78eef2 Iustin Pop
class DevCacheManager(object):
4527 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
4528 3f78eef2 Iustin Pop

4529 3f78eef2 Iustin Pop
  """
4530 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
4531 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4532 3f78eef2 Iustin Pop
4533 3f78eef2 Iustin Pop
  @classmethod
4534 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
4535 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
4536 3f78eef2 Iustin Pop

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

4540 10c2650b Iustin Pop
    @type dev_path: str
4541 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
4542 10c2650b Iustin Pop
    @rtype: str
4543 10c2650b Iustin Pop
    @return: the converted path name
4544 3f78eef2 Iustin Pop

4545 3f78eef2 Iustin Pop
    """
4546 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
4547 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4548 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
4549 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4550 3f78eef2 Iustin Pop
    return fpath
4551 3f78eef2 Iustin Pop
4552 3f78eef2 Iustin Pop
  @classmethod
4553 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4554 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
4555 3f78eef2 Iustin Pop

4556 10c2650b Iustin Pop
    @type dev_path: str
4557 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4558 10c2650b Iustin Pop
    @type owner: str
4559 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
4560 10c2650b Iustin Pop
    @type on_primary: bool
4561 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
4562 10c2650b Iustin Pop
        node nor not
4563 10c2650b Iustin Pop
    @type iv_name: str
4564 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
4565 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
4566 10c2650b Iustin Pop

4567 10c2650b Iustin Pop
    @rtype: None
4568 10c2650b Iustin Pop

4569 3f78eef2 Iustin Pop
    """
4570 cf5a8306 Iustin Pop
    if dev_path is None:
4571 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4572 cf5a8306 Iustin Pop
      return
4573 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4574 3f78eef2 Iustin Pop
    if on_primary:
4575 3f78eef2 Iustin Pop
      state = "primary"
4576 3f78eef2 Iustin Pop
    else:
4577 3f78eef2 Iustin Pop
      state = "secondary"
4578 3f78eef2 Iustin Pop
    if iv_name is None:
4579 3f78eef2 Iustin Pop
      iv_name = "not_visible"
4580 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4581 3f78eef2 Iustin Pop
    try:
4582 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
4583 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4584 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4585 3f78eef2 Iustin Pop
4586 3f78eef2 Iustin Pop
  @classmethod
4587 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
4588 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
4589 3f78eef2 Iustin Pop

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

4593 10c2650b Iustin Pop
    @type dev_path: str
4594 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4595 10c2650b Iustin Pop

4596 10c2650b Iustin Pop
    @rtype: None
4597 10c2650b Iustin Pop

4598 3f78eef2 Iustin Pop
    """
4599 cf5a8306 Iustin Pop
    if dev_path is None:
4600 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4601 cf5a8306 Iustin Pop
      return
4602 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4603 3f78eef2 Iustin Pop
    try:
4604 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
4605 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4606 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)