Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 3360026f

History | View | Annotate | Download (149 kB)

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

116 2cc6781a Iustin Pop
  Its argument is the error message.
117 2cc6781a Iustin Pop

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

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

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

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

139 584ea340 Michele Tartara
  @type instance_name: string
140 584ea340 Michele Tartara
  @param instance_name: The name of the instance
141 3cf06dd4 Jose A. Lopes

142 3cf06dd4 Jose A. Lopes
  @type trail: list of reasons
143 3cf06dd4 Jose A. Lopes
  @param trail: reason trail
144 3cf06dd4 Jose A. Lopes

145 584ea340 Michele Tartara
  @rtype: None
146 584ea340 Michele Tartara

147 584ea340 Michele Tartara
  """
148 584ea340 Michele Tartara
  json = serializer.DumpJson(trail)
149 584ea340 Michele Tartara
  filename = _GetInstReasonFilename(instance_name)
150 584ea340 Michele Tartara
  utils.WriteFile(filename, data=json)
151 584ea340 Michele Tartara
152 584ea340 Michele Tartara
153 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
154 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
155 2cc6781a Iustin Pop

156 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
157 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
158 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
159 2cc6781a Iustin Pop
  daemon.
160 2cc6781a Iustin Pop

161 2cc6781a Iustin Pop
  @type msg: string
162 2cc6781a Iustin Pop
  @param msg: the text of the exception
163 2cc6781a Iustin Pop
  @raise RPCFail
164 2cc6781a Iustin Pop

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

179 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
180 93384844 Iustin Pop
  @return: a SimpleStore instance
181 10c2650b Iustin Pop

182 10c2650b Iustin Pop
  """
183 93384844 Iustin Pop
  return ssconf.SimpleStore()
184 c657dcc9 Michael Hanselmann
185 c657dcc9 Michael Hanselmann
186 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
187 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
188 10c2650b Iustin Pop

189 10c2650b Iustin Pop
  @type cluster_name: str
190 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
191 10c2650b Iustin Pop
      by the SshRunner constructor
192 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
193 10c2650b Iustin Pop
  @return: an SshRunner instance
194 10c2650b Iustin Pop

195 10c2650b Iustin Pop
  """
196 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
197 c92b310a Michael Hanselmann
198 c92b310a Michael Hanselmann
199 12bce260 Michael Hanselmann
def _Decompress(data):
200 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
201 12bce260 Michael Hanselmann

202 12bce260 Michael Hanselmann
  @type data: list or tuple
203 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
204 12bce260 Michael Hanselmann
  @rtype: str
205 12bce260 Michael Hanselmann
  @return: Decompressed data
206 12bce260 Michael Hanselmann

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

222 10c2650b Iustin Pop
  @type path: str
223 10c2650b Iustin Pop
  @param path: the directory to clean
224 76ab5558 Michael Hanselmann
  @type exclude: list
225 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
226 10c2650b Iustin Pop
      to the empty list
227 76ab5558 Michael Hanselmann

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

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

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

284 c8457ce7 Iustin Pop
  @rtype: tuple
285 c8457ce7 Iustin Pop
  @return: True, None
286 24fc781f Michael Hanselmann

287 24fc781f Michael Hanselmann
  """
288 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
289 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
290 24fc781f Michael Hanselmann
291 24fc781f Michael Hanselmann
292 cb8028f3 Jose A. Lopes
def GetMasterNodeName():
293 cb8028f3 Jose A. Lopes
  """Returns the master node name.
294 bd1e4562 Iustin Pop

295 cb8028f3 Jose A. Lopes
  @rtype: string
296 cb8028f3 Jose A. Lopes
  @return: name of the master node
297 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
298 b1b6ea87 Iustin Pop

299 b1b6ea87 Iustin Pop
  """
300 b1b6ea87 Iustin Pop
  try:
301 cb8028f3 Jose A. Lopes
    return _GetConfig().GetMasterNode()
302 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
303 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
304 b1b6ea87 Iustin Pop
305 b1b6ea87 Iustin Pop
306 0fa481f5 Andrea Spadaccini
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
307 0fa481f5 Andrea Spadaccini
  """Decorator that runs hooks before and after the decorated function.
308 0fa481f5 Andrea Spadaccini

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

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

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

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

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

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

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

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

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

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

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

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

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

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

461 fb460cf7 Andrea Spadaccini
  @rtype: None
462 fb460cf7 Andrea Spadaccini

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

477 41e079ce Andrea Spadaccini
  @param old_netmask: the old value of the netmask
478 41e079ce Andrea Spadaccini
  @param netmask: the new value of the netmask
479 41e079ce Andrea Spadaccini
  @param master_ip: the master IP
480 41e079ce Andrea Spadaccini
  @param master_netdev: the master network device
481 41e079ce Andrea Spadaccini

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

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

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

530 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
531 10c2650b Iustin Pop
  from the cluster.
532 10c2650b Iustin Pop

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

537 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
538 b989b9d9 Ken Wehr

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

576 b01b7a50 Helga Velroyen
  @type params: list
577 b01b7a50 Helga Velroyen
  @param params: list of storage parameters
578 b01b7a50 Helga Velroyen
  @type num_params: int
579 b01b7a50 Helga Velroyen
  @param num_params: expected number of parameters
580 b01b7a50 Helga Velroyen

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

597 3c8a599a Helga Velroyen
  @see: C{_CheckStorageParams}
598 3c8a599a Helga Velroyen

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

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

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

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

647 a18ab868 Helga Velroyen
  @see: C{_GetLvmVgSpaceInfo}
648 3c8a599a Helga Velroyen

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

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

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

683 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
684 78519c10 Michael Hanselmann

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

692 439e1d3f Helga Velroyen
  @type hvparams: dict of string
693 439e1d3f Helga Velroyen
  @param hvparams: the hypervisor's hvparams
694 439e1d3f Helga Velroyen

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

702 439e1d3f Helga Velroyen
  See C{_GetHvInfo} for information on the output.
703 439e1d3f Helga Velroyen

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

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

720 78519c10 Michael Hanselmann
  @rtype: None or dict
721 78519c10 Michael Hanselmann

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

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

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

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

760 13669ecd Helga Velroyen
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
761 13669ecd Helga Velroyen
    parameters.
762 13669ecd Helga Velroyen

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

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

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

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

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

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

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

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

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

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

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

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

920 5b0dfcef Helga Velroyen
  """
921 5b0dfcef Helga Velroyen
  if constants.NV_HVINFO in what and vm_capable:
922 5b0dfcef Helga Velroyen
    hvname = what[constants.NV_HVINFO]
923 5b0dfcef Helga Velroyen
    hyper = hypervisor.GetHypervisor(hvname)
924 5b0dfcef Helga Velroyen
    hvparams = all_hvparams[hvname]
925 5b0dfcef Helga Velroyen
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
926 5b0dfcef Helga Velroyen
927 5b0dfcef Helga Velroyen
928 a6c43c02 Helga Velroyen
def _VerifyClientCertificate(cert_file=pathutils.NODED_CLIENT_CERT_FILE):
929 a6c43c02 Helga Velroyen
  """Verify the existance and validity of the client SSL certificate.
930 a6c43c02 Helga Velroyen

931 a6c43c02 Helga Velroyen
  """
932 a6c43c02 Helga Velroyen
  create_cert_cmd = "gnt-cluster renew-crypto --new-node-certificates"
933 a6c43c02 Helga Velroyen
  if not os.path.exists(cert_file):
934 a6c43c02 Helga Velroyen
    return (constants.CV_ERROR,
935 a6c43c02 Helga Velroyen
            "The client certificate does not exist. Run '%s' to create"
936 46ae85de Helga Velroyen
            " client certificates for all nodes." % create_cert_cmd)
937 a6c43c02 Helga Velroyen
938 a6c43c02 Helga Velroyen
  (errcode, msg) = utils.VerifyCertificate(cert_file)
939 a6c43c02 Helga Velroyen
  if errcode is not None:
940 a6c43c02 Helga Velroyen
    return (errcode, msg)
941 a6c43c02 Helga Velroyen
  else:
942 a6c43c02 Helga Velroyen
    # if everything is fine, we return the digest to be compared to the config
943 a6c43c02 Helga Velroyen
    return (None, utils.GetCertificateDigest(cert_filename=cert_file))
944 a6c43c02 Helga Velroyen
945 a6c43c02 Helga Velroyen
946 a9f33339 Petr Pudlak
def VerifyNode(what, cluster_name, all_hvparams, node_groups, groups_cfg):
947 a8083063 Iustin Pop
  """Verify the status of the local node.
948 a8083063 Iustin Pop

949 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
950 e69d05fd Iustin Pop
  local node.
951 e69d05fd Iustin Pop

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

955 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
956 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
957 e69d05fd Iustin Pop
  report).
958 a8083063 Iustin Pop

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

963 e69d05fd Iustin Pop
  @type what: C{dict}
964 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
965 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
966 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
967 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
968 e69d05fd Iustin Pop
        connectivity with
969 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
970 5b0dfcef Helga Velroyen
  @type cluster_name: string
971 5b0dfcef Helga Velroyen
  @param cluster_name: the cluster's name
972 5b0dfcef Helga Velroyen
  @type all_hvparams: dict of dict of strings
973 5b0dfcef Helga Velroyen
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
974 a9f33339 Petr Pudlak
  @type node_groups: a dict of strings
975 a9f33339 Petr Pudlak
  @param node_groups: node _names_ mapped to their group uuids (it's enough to
976 a9f33339 Petr Pudlak
      have only those nodes that are in `what["nodelist"]`)
977 a9f33339 Petr Pudlak
  @type groups_cfg: a dict of dict of strings
978 a9f33339 Petr Pudlak
  @param groups_cfg: a dictionary mapping group uuids to their configuration
979 10c2650b Iustin Pop
  @rtype: dict
980 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
981 10c2650b Iustin Pop
      values representing the result of the checks
982 a8083063 Iustin Pop

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

1184 d722af8b Helga Velroyen
  Token types can be 'ssl' or 'ssh'. So far only some actions are implemented
1185 d722af8b Helga Velroyen
  for 'ssl'. Action 'get' returns the digest of the public client ssl
1186 d722af8b Helga Velroyen
  certificate. Action 'create' creates a new client certificate and private key
1187 d722af8b Helga Velroyen
  and also returns the digest of the certificate. The third parameter of a
1188 d722af8b Helga Velroyen
  token request are optional parameters for the actions, so far only the
1189 d722af8b Helga Velroyen
  filename is supported.
1190 d722af8b Helga Velroyen

1191 d722af8b Helga Velroyen
  @type token_requests: list of tuples of (string, string, dict), where the
1192 d722af8b Helga Velroyen
    first string is in constants.CRYPTO_TYPES, the second in
1193 d722af8b Helga Velroyen
    constants.CRYPTO_ACTIONS. The third parameter is a dictionary of string
1194 d722af8b Helga Velroyen
    to string.
1195 d722af8b Helga Velroyen
  @param token_requests: list of requests of cryptographic tokens and actions
1196 d722af8b Helga Velroyen
    to perform on them. The actions come with a dictionary of options.
1197 b544a3c2 Helga Velroyen
  @rtype: list of tuples (string, string)
1198 b544a3c2 Helga Velroyen
  @return: list of tuples of the token type and the public crypto token
1199 b544a3c2 Helga Velroyen

1200 b544a3c2 Helga Velroyen
  """
1201 22114677 Helga Velroyen
  getents = runtime.GetEnts()
1202 d722af8b Helga Velroyen
  _VALID_CERT_FILES = [pathutils.NODED_CERT_FILE,
1203 d722af8b Helga Velroyen
                       pathutils.NODED_CLIENT_CERT_FILE,
1204 d722af8b Helga Velroyen
                       pathutils.NODED_CLIENT_CERT_FILE_TMP]
1205 d722af8b Helga Velroyen
  _DEFAULT_CERT_FILE = pathutils.NODED_CLIENT_CERT_FILE
1206 b544a3c2 Helga Velroyen
  tokens = []
1207 d722af8b Helga Velroyen
  for (token_type, action, options) in token_requests:
1208 b544a3c2 Helga Velroyen
    if token_type not in constants.CRYPTO_TYPES:
1209 d722af8b Helga Velroyen
      raise errors.ProgrammerError("Token type '%s' not supported." %
1210 b544a3c2 Helga Velroyen
                                   token_type)
1211 d722af8b Helga Velroyen
    if action not in constants.CRYPTO_ACTIONS:
1212 d722af8b Helga Velroyen
      raise errors.ProgrammerError("Action '%s' is not supported." %
1213 d722af8b Helga Velroyen
                                   action)
1214 b544a3c2 Helga Velroyen
    if token_type == constants.CRYPTO_TYPE_SSL_DIGEST:
1215 d722af8b Helga Velroyen
      if action == constants.CRYPTO_ACTION_CREATE:
1216 ab4b1cf2 Helga Velroyen
1217 ab4b1cf2 Helga Velroyen
        # extract file name from options
1218 d722af8b Helga Velroyen
        cert_filename = None
1219 d722af8b Helga Velroyen
        if options:
1220 d722af8b Helga Velroyen
          cert_filename = options.get(constants.CRYPTO_OPTION_CERT_FILE)
1221 d722af8b Helga Velroyen
        if not cert_filename:
1222 d722af8b Helga Velroyen
          cert_filename = _DEFAULT_CERT_FILE
1223 d722af8b Helga Velroyen
        # For security reason, we don't allow arbitrary filenames
1224 d722af8b Helga Velroyen
        if not cert_filename in _VALID_CERT_FILES:
1225 d722af8b Helga Velroyen
          raise errors.ProgrammerError(
1226 d722af8b Helga Velroyen
            "The certificate file name path '%s' is not allowed." %
1227 d722af8b Helga Velroyen
            cert_filename)
1228 ab4b1cf2 Helga Velroyen
1229 ab4b1cf2 Helga Velroyen
        # extract serial number from options
1230 ab4b1cf2 Helga Velroyen
        serial_no = None
1231 ab4b1cf2 Helga Velroyen
        if options:
1232 ab4b1cf2 Helga Velroyen
          try:
1233 ab4b1cf2 Helga Velroyen
            serial_no = int(options[constants.CRYPTO_OPTION_SERIAL_NO])
1234 ab4b1cf2 Helga Velroyen
          except ValueError:
1235 ab4b1cf2 Helga Velroyen
            raise errors.ProgrammerError(
1236 ab4b1cf2 Helga Velroyen
              "The given serial number is not an intenger: %s." %
1237 ab4b1cf2 Helga Velroyen
              options.get(constants.CRYPTO_OPTION_SERIAL_NO))
1238 ab4b1cf2 Helga Velroyen
          except KeyError:
1239 ab4b1cf2 Helga Velroyen
            raise errors.ProgrammerError("No serial number was provided.")
1240 ab4b1cf2 Helga Velroyen
1241 ab4b1cf2 Helga Velroyen
        if not serial_no:
1242 ab4b1cf2 Helga Velroyen
          raise errors.ProgrammerError(
1243 ab4b1cf2 Helga Velroyen
            "Cannot create an SSL certificate without a serial no.")
1244 ab4b1cf2 Helga Velroyen
1245 d722af8b Helga Velroyen
        utils.GenerateNewSslCert(
1246 ab4b1cf2 Helga Velroyen
          True, cert_filename, serial_no,
1247 22114677 Helga Velroyen
          "Create new client SSL certificate in %s." % cert_filename,
1248 22114677 Helga Velroyen
          uid=getents.masterd_uid, gid=getents.masterd_gid)
1249 d722af8b Helga Velroyen
        tokens.append((token_type,
1250 b3cc1646 Helga Velroyen
                       utils.GetCertificateDigest(
1251 d722af8b Helga Velroyen
                         cert_filename=cert_filename)))
1252 d722af8b Helga Velroyen
      elif action == constants.CRYPTO_ACTION_GET:
1253 d722af8b Helga Velroyen
        tokens.append((token_type,
1254 b3cc1646 Helga Velroyen
                       utils.GetCertificateDigest()))
1255 b544a3c2 Helga Velroyen
  return tokens
1256 b544a3c2 Helga Velroyen
1257 b544a3c2 Helga Velroyen
1258 2be7273c Apollon Oikonomopoulos
def GetBlockDevSizes(devices):
1259 2be7273c Apollon Oikonomopoulos
  """Return the size of the given block devices
1260 2be7273c Apollon Oikonomopoulos

1261 2be7273c Apollon Oikonomopoulos
  @type devices: list
1262 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
1263 2be7273c Apollon Oikonomopoulos
  @rtype: dict
1264 2be7273c Apollon Oikonomopoulos
  @return:
1265 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
1266 2be7273c Apollon Oikonomopoulos
    size in MiB.
1267 2be7273c Apollon Oikonomopoulos

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

1270 2be7273c Apollon Oikonomopoulos
  """
1271 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
1272 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
1273 2be7273c Apollon Oikonomopoulos
1274 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
1275 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1276 2be7273c Apollon Oikonomopoulos
      continue
1277 2be7273c Apollon Oikonomopoulos
1278 2be7273c Apollon Oikonomopoulos
    try:
1279 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
1280 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
1281 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1282 2be7273c Apollon Oikonomopoulos
      continue
1283 2be7273c Apollon Oikonomopoulos
1284 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
1285 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1286 2be7273c Apollon Oikonomopoulos
      if result.failed:
1287 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
1288 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
1289 2be7273c Apollon Oikonomopoulos
        continue
1290 2be7273c Apollon Oikonomopoulos
1291 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
1292 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
1293 2be7273c Apollon Oikonomopoulos
  return blockdevs
1294 2be7273c Apollon Oikonomopoulos
1295 2be7273c Apollon Oikonomopoulos
1296 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
1297 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
1298 a8083063 Iustin Pop

1299 84d7e26b Dmitry Chernyak
  @type vg_names: list
1300 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
1301 397693d3 Iustin Pop
      empty for all volume groups
1302 10c2650b Iustin Pop
  @rtype: dict
1303 10c2650b Iustin Pop
  @return:
1304 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
1305 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
1306 10c2650b Iustin Pop

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

1309 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
1310 10c2650b Iustin Pop
      details.
1311 a8083063 Iustin Pop

1312 a8083063 Iustin Pop
  """
1313 cb2037a2 Iustin Pop
  lvs = {}
1314 d0c8c01d Iustin Pop
  sep = "|"
1315 397693d3 Iustin Pop
  if not vg_names:
1316 397693d3 Iustin Pop
    vg_names = []
1317 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1318 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
1319 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1320 a8083063 Iustin Pop
  if result.failed:
1321 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1322 cb2037a2 Iustin Pop
1323 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
1324 df4c2628 Iustin Pop
    line = line.strip()
1325 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
1326 df4c2628 Iustin Pop
    if not match:
1327 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
1328 df4c2628 Iustin Pop
      continue
1329 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
1330 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
1331 d0c8c01d Iustin Pop
    online = attr[5] == "o"
1332 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
1333 33f2a81a Iustin Pop
    if virtual:
1334 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
1335 33f2a81a Iustin Pop
      # don't really hold data
1336 33f2a81a Iustin Pop
      continue
1337 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
1338 cb2037a2 Iustin Pop
1339 cb2037a2 Iustin Pop
  return lvs
1340 a8083063 Iustin Pop
1341 a8083063 Iustin Pop
1342 a8083063 Iustin Pop
def ListVolumeGroups():
1343 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
1344 a8083063 Iustin Pop

1345 10c2650b Iustin Pop
  @rtype: dict
1346 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
1347 10c2650b Iustin Pop
      size of the volume
1348 a8083063 Iustin Pop

1349 a8083063 Iustin Pop
  """
1350 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
1351 a8083063 Iustin Pop
1352 a8083063 Iustin Pop
1353 dcb93971 Michael Hanselmann
def NodeVolumes():
1354 dcb93971 Michael Hanselmann
  """List all volumes on this node.
1355 dcb93971 Michael Hanselmann

1356 10c2650b Iustin Pop
  @rtype: list
1357 10c2650b Iustin Pop
  @return:
1358 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
1359 10c2650b Iustin Pop
      - name: the logical volume name,
1360 10c2650b Iustin Pop
      - size: the size of the logical volume
1361 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
1362 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
1363 10c2650b Iustin Pop

1364 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
1365 10c2650b Iustin Pop
    error.
1366 10c2650b Iustin Pop

1367 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
1368 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
1369 10c2650b Iustin Pop
    multiple times.
1370 10c2650b Iustin Pop

1371 dcb93971 Michael Hanselmann
  """
1372 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1373 dcb93971 Michael Hanselmann
                         "--separator=|",
1374 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
1375 dcb93971 Michael Hanselmann
  if result.failed:
1376 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
1377 10bfe6cb Iustin Pop
          result.output)
1378 dcb93971 Michael Hanselmann
1379 dcb93971 Michael Hanselmann
  def parse_dev(dev):
1380 d0c8c01d Iustin Pop
    return dev.split("(")[0]
1381 89e5ab02 Iustin Pop
1382 89e5ab02 Iustin Pop
  def handle_dev(dev):
1383 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
1384 dcb93971 Michael Hanselmann
1385 dcb93971 Michael Hanselmann
  def map_line(line):
1386 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
1387 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
1388 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1389 89e5ab02 Iustin Pop
1390 89e5ab02 Iustin Pop
  all_devs = []
1391 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
1392 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
1393 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
1394 89e5ab02 Iustin Pop
    else:
1395 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
1396 89e5ab02 Iustin Pop
  return all_devs
1397 dcb93971 Michael Hanselmann
1398 dcb93971 Michael Hanselmann
1399 a8083063 Iustin Pop
def BridgesExist(bridges_list):
1400 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
1401 a8083063 Iustin Pop

1402 b1206984 Iustin Pop
  @rtype: boolean
1403 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
1404 a8083063 Iustin Pop

1405 a8083063 Iustin Pop
  """
1406 35c0c8da Iustin Pop
  missing = []
1407 a8083063 Iustin Pop
  for bridge in bridges_list:
1408 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
1409 35c0c8da Iustin Pop
      missing.append(bridge)
1410 a8083063 Iustin Pop
1411 35c0c8da Iustin Pop
  if missing:
1412 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1413 35c0c8da Iustin Pop
1414 a8083063 Iustin Pop
1415 2bff1928 Helga Velroyen
def GetInstanceListForHypervisor(hname, hvparams=None,
1416 2bff1928 Helga Velroyen
                                 get_hv_fn=hypervisor.GetHypervisor):
1417 2bff1928 Helga Velroyen
  """Provides a list of instances of the given hypervisor.
1418 2bff1928 Helga Velroyen

1419 2bff1928 Helga Velroyen
  @type hname: string
1420 2bff1928 Helga Velroyen
  @param hname: name of the hypervisor
1421 2bff1928 Helga Velroyen
  @type hvparams: dict of strings
1422 2bff1928 Helga Velroyen
  @param hvparams: hypervisor parameters for the given hypervisor
1423 2bff1928 Helga Velroyen
  @type get_hv_fn: function
1424 2bff1928 Helga Velroyen
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1425 2bff1928 Helga Velroyen
    name; optional parameter to increase testability
1426 2bff1928 Helga Velroyen

1427 2bff1928 Helga Velroyen
  @rtype: list
1428 2bff1928 Helga Velroyen
  @return: a list of all running instances on the current node
1429 2bff1928 Helga Velroyen
    - instance1.example.com
1430 2bff1928 Helga Velroyen
    - instance2.example.com
1431 2bff1928 Helga Velroyen

1432 2bff1928 Helga Velroyen
  """
1433 2bff1928 Helga Velroyen
  results = []
1434 2bff1928 Helga Velroyen
  try:
1435 2bff1928 Helga Velroyen
    hv = get_hv_fn(hname)
1436 5b0dfcef Helga Velroyen
    names = hv.ListInstances(hvparams=hvparams)
1437 2bff1928 Helga Velroyen
    results.extend(names)
1438 2bff1928 Helga Velroyen
  except errors.HypervisorError, err:
1439 2bff1928 Helga Velroyen
    _Fail("Error enumerating instances (hypervisor %s): %s",
1440 2bff1928 Helga Velroyen
          hname, err, exc=True)
1441 2bff1928 Helga Velroyen
  return results
1442 2bff1928 Helga Velroyen
1443 2bff1928 Helga Velroyen
1444 fac83f8a Helga Velroyen
def GetInstanceList(hypervisor_list, all_hvparams=None,
1445 fac83f8a Helga Velroyen
                    get_hv_fn=hypervisor.GetHypervisor):
1446 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
1447 a8083063 Iustin Pop

1448 e69d05fd Iustin Pop
  @type hypervisor_list: list
1449 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
1450 fac83f8a Helga Velroyen
  @type all_hvparams: dict of dict of strings
1451 fac83f8a Helga Velroyen
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1452 fac83f8a Helga Velroyen
    cluster-wide hypervisor parameters
1453 fac83f8a Helga Velroyen
  @type get_hv_fn: function
1454 fac83f8a Helga Velroyen
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1455 fac83f8a Helga Velroyen
    name; optional parameter to increase testability
1456 e69d05fd Iustin Pop

1457 e69d05fd Iustin Pop
  @rtype: list
1458 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
1459 10c2650b Iustin Pop
    - instance1.example.com
1460 10c2650b Iustin Pop
    - instance2.example.com
1461 a8083063 Iustin Pop

1462 098c0958 Michael Hanselmann
  """
1463 e69d05fd Iustin Pop
  results = []
1464 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1465 5b0dfcef Helga Velroyen
    hvparams = all_hvparams[hname]
1466 5b0dfcef Helga Velroyen
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1467 2bff1928 Helga Velroyen
                                                get_hv_fn=get_hv_fn))
1468 e69d05fd Iustin Pop
  return results
1469 a8083063 Iustin Pop
1470 a8083063 Iustin Pop
1471 0bbec3af Helga Velroyen
def GetInstanceInfo(instance, hname, hvparams=None):
1472 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
1473 a8083063 Iustin Pop

1474 e69d05fd Iustin Pop
  @type instance: string
1475 e69d05fd Iustin Pop
  @param instance: the instance name
1476 e69d05fd Iustin Pop
  @type hname: string
1477 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1478 0bbec3af Helga Velroyen
  @type hvparams: dict of strings
1479 0bbec3af Helga Velroyen
  @param hvparams: the instance's hvparams
1480 a8083063 Iustin Pop

1481 e69d05fd Iustin Pop
  @rtype: dict
1482 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1483 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1484 a3f0f306 Jose A. Lopes
      - state: state of instance (HvInstanceState)
1485 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1486 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1487 a8083063 Iustin Pop

1488 098c0958 Michael Hanselmann
  """
1489 a8083063 Iustin Pop
  output = {}
1490 a8083063 Iustin Pop
1491 0bbec3af Helga Velroyen
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1492 0bbec3af Helga Velroyen
                                                          hvparams=hvparams)
1493 a8083063 Iustin Pop
  if iinfo is not None:
1494 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1495 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1496 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1497 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1498 a8083063 Iustin Pop
1499 c26a6bd2 Iustin Pop
  return output
1500 a8083063 Iustin Pop
1501 a8083063 Iustin Pop
1502 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1503 3361ab37 Helga Velroyen
  """Computes whether an instance can be migrated.
1504 56e7640c Iustin Pop

1505 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1506 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1507 56e7640c Iustin Pop

1508 56e7640c Iustin Pop
  @rtype: tuple
1509 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1510 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1511 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1512 56e7640c Iustin Pop

1513 56e7640c Iustin Pop
  """
1514 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1515 afdc3985 Iustin Pop
  iname = instance.name
1516 3361ab37 Helga Velroyen
  if iname not in hyper.ListInstances(instance.hvparams):
1517 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1518 56e7640c Iustin Pop
1519 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1520 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1521 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1522 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1523 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1524 56e7640c Iustin Pop
1525 56e7640c Iustin Pop
1526 0200a1af Helga Velroyen
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1527 a8083063 Iustin Pop
  """Gather data about all instances.
1528 a8083063 Iustin Pop

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

1533 e69d05fd Iustin Pop
  @type hypervisor_list: list
1534 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1535 0200a1af Helga Velroyen
  @type all_hvparams: dict of dict of strings
1536 0200a1af Helga Velroyen
  @param all_hvparams: mapping of hypervisor names to hvparams
1537 e69d05fd Iustin Pop

1538 955db481 Guido Trotter
  @rtype: dict
1539 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1540 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1541 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1542 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1543 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1544 a8083063 Iustin Pop

1545 098c0958 Michael Hanselmann
  """
1546 a8083063 Iustin Pop
  output = {}
1547 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1548 0200a1af Helga Velroyen
    hvparams = all_hvparams[hname]
1549 0200a1af Helga Velroyen
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1550 e69d05fd Iustin Pop
    if iinfo:
1551 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1552 f23b5ae8 Iustin Pop
        value = {
1553 d0c8c01d Iustin Pop
          "memory": memory,
1554 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1555 d0c8c01d Iustin Pop
          "state": state,
1556 d0c8c01d Iustin Pop
          "time": times,
1557 e69d05fd Iustin Pop
          }
1558 b33b6f55 Iustin Pop
        if name in output:
1559 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1560 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1561 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1562 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1563 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1564 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1565 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1566 f23b5ae8 Iustin Pop
        output[name] = value
1567 a8083063 Iustin Pop
1568 c26a6bd2 Iustin Pop
  return output
1569 a8083063 Iustin Pop
1570 a8083063 Iustin Pop
1571 b9e12624 Hrvoje Ribicic
def GetInstanceConsoleInfo(instance_param_dict,
1572 b9e12624 Hrvoje Ribicic
                           get_hv_fn=hypervisor.GetHypervisor):
1573 b9e12624 Hrvoje Ribicic
  """Gather data about the console access of a set of instances of this node.
1574 b9e12624 Hrvoje Ribicic

1575 b9e12624 Hrvoje Ribicic
  This function assumes that the caller already knows which instances are on
1576 b9e12624 Hrvoje Ribicic
  this node, by calling a function such as L{GetAllInstancesInfo} or
1577 b9e12624 Hrvoje Ribicic
  L{GetInstanceList}.
1578 b9e12624 Hrvoje Ribicic

1579 b9e12624 Hrvoje Ribicic
  For every instance, a large amount of configuration data needs to be
1580 b9e12624 Hrvoje Ribicic
  provided to the hypervisor interface in order to receive the console
1581 b9e12624 Hrvoje Ribicic
  information. Whether this could or should be cut down can be discussed.
1582 b9e12624 Hrvoje Ribicic
  The information is provided in a dictionary indexed by instance name,
1583 b9e12624 Hrvoje Ribicic
  allowing any number of instance queries to be done.
1584 b9e12624 Hrvoje Ribicic

1585 b9e12624 Hrvoje Ribicic
  @type instance_param_dict: dict of string to tuple of dictionaries, where the
1586 c42be2c0 Petr Pudlak
    dictionaries represent: L{objects.Instance}, L{objects.Node},
1587 c42be2c0 Petr Pudlak
    L{objects.NodeGroup}, HvParams, BeParams
1588 b9e12624 Hrvoje Ribicic
  @param instance_param_dict: mapping of instance name to parameters necessary
1589 b9e12624 Hrvoje Ribicic
    for console information retrieval
1590 b9e12624 Hrvoje Ribicic

1591 b9e12624 Hrvoje Ribicic
  @rtype: dict
1592 b9e12624 Hrvoje Ribicic
  @return: dictionary of instance: data, with data having the following keys:
1593 b9e12624 Hrvoje Ribicic
      - instance: instance name
1594 b9e12624 Hrvoje Ribicic
      - kind: console kind
1595 b9e12624 Hrvoje Ribicic
      - message: used with kind == CONS_MESSAGE, indicates console to be
1596 b9e12624 Hrvoje Ribicic
                 unavailable, supplies error message
1597 b9e12624 Hrvoje Ribicic
      - host: host to connect to
1598 b9e12624 Hrvoje Ribicic
      - port: port to use
1599 b9e12624 Hrvoje Ribicic
      - user: user for login
1600 b9e12624 Hrvoje Ribicic
      - command: the command, broken into parts as an array
1601 b9e12624 Hrvoje Ribicic
      - display: unknown, potentially unused?
1602 b9e12624 Hrvoje Ribicic

1603 b9e12624 Hrvoje Ribicic
  """
1604 b9e12624 Hrvoje Ribicic
1605 b9e12624 Hrvoje Ribicic
  output = {}
1606 b9e12624 Hrvoje Ribicic
  for inst_name in instance_param_dict:
1607 b9e12624 Hrvoje Ribicic
    instance = instance_param_dict[inst_name]["instance"]
1608 b9e12624 Hrvoje Ribicic
    pnode = instance_param_dict[inst_name]["node"]
1609 c42be2c0 Petr Pudlak
    group = instance_param_dict[inst_name]["group"]
1610 b9e12624 Hrvoje Ribicic
    hvparams = instance_param_dict[inst_name]["hvParams"]
1611 b9e12624 Hrvoje Ribicic
    beparams = instance_param_dict[inst_name]["beParams"]
1612 b9e12624 Hrvoje Ribicic
1613 b9e12624 Hrvoje Ribicic
    instance = objects.Instance.FromDict(instance)
1614 b9e12624 Hrvoje Ribicic
    pnode = objects.Node.FromDict(pnode)
1615 c42be2c0 Petr Pudlak
    group = objects.NodeGroup.FromDict(group)
1616 b9e12624 Hrvoje Ribicic
1617 b9e12624 Hrvoje Ribicic
    h = get_hv_fn(instance.hypervisor)
1618 c42be2c0 Petr Pudlak
    output[inst_name] = h.GetInstanceConsole(instance, pnode, group,
1619 c42be2c0 Petr Pudlak
                                             hvparams, beparams).ToDict()
1620 b9e12624 Hrvoje Ribicic
1621 b9e12624 Hrvoje Ribicic
  return output
1622 b9e12624 Hrvoje Ribicic
1623 b9e12624 Hrvoje Ribicic
1624 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1625 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1626 81a3406c Iustin Pop

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

1630 81a3406c Iustin Pop
  @type kind: string
1631 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1632 81a3406c Iustin Pop
  @type os_name: string
1633 81a3406c Iustin Pop
  @param os_name: the os name
1634 81a3406c Iustin Pop
  @type instance: string
1635 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1636 6aa7a354 Iustin Pop
  @type component: string or None
1637 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1638 6aa7a354 Iustin Pop
      transferred
1639 81a3406c Iustin Pop

1640 81a3406c Iustin Pop
  """
1641 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1642 6aa7a354 Iustin Pop
  if component:
1643 6aa7a354 Iustin Pop
    assert "/" not in component
1644 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1645 6aa7a354 Iustin Pop
  else:
1646 6aa7a354 Iustin Pop
    c_msg = ""
1647 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1648 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1649 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1650 81a3406c Iustin Pop
1651 81a3406c Iustin Pop
1652 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1653 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1654 a8083063 Iustin Pop

1655 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1656 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1657 e557bae9 Guido Trotter
  @type reinstall: boolean
1658 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1659 4a0e011f Iustin Pop
  @type debug: integer
1660 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1661 c26a6bd2 Iustin Pop
  @rtype: None
1662 a8083063 Iustin Pop

1663 a8083063 Iustin Pop
  """
1664 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1665 255dcebd Iustin Pop
1666 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1667 e557bae9 Guido Trotter
  if reinstall:
1668 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1669 a8083063 Iustin Pop
1670 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1671 decd5f45 Iustin Pop
1672 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1673 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1674 decd5f45 Iustin Pop
  if result.failed:
1675 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1676 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1677 18682bca Iustin Pop
                  result.output)
1678 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1679 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1680 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1681 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1682 decd5f45 Iustin Pop
1683 decd5f45 Iustin Pop
1684 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1685 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1686 decd5f45 Iustin Pop

1687 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1688 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1689 d15a9ad3 Guido Trotter
  @type old_name: string
1690 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1691 4a0e011f Iustin Pop
  @type debug: integer
1692 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1693 10c2650b Iustin Pop
  @rtype: boolean
1694 10c2650b Iustin Pop
  @return: the success of the operation
1695 decd5f45 Iustin Pop

1696 decd5f45 Iustin Pop
  """
1697 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1698 decd5f45 Iustin Pop
1699 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1700 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1701 decd5f45 Iustin Pop
1702 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1703 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1704 a8083063 Iustin Pop
1705 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1706 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1707 a8083063 Iustin Pop
1708 a8083063 Iustin Pop
  if result.failed:
1709 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1710 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1711 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1712 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1713 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1714 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1715 a8083063 Iustin Pop
1716 a8083063 Iustin Pop
1717 3b721842 Michael Hanselmann
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1718 3b721842 Michael Hanselmann
  """Returns symlink path for block device.
1719 3b721842 Michael Hanselmann

1720 3b721842 Michael Hanselmann
  """
1721 3b721842 Michael Hanselmann
  if _dir is None:
1722 3b721842 Michael Hanselmann
    _dir = pathutils.DISK_LINKS_DIR
1723 3b721842 Michael Hanselmann
1724 3b721842 Michael Hanselmann
  return utils.PathJoin(_dir,
1725 3b721842 Michael Hanselmann
                        ("%s%s%s" %
1726 3b721842 Michael Hanselmann
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1727 5282084b Iustin Pop
1728 5282084b Iustin Pop
1729 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1730 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1731 9332fd8a Iustin Pop

1732 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1733 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1734 9332fd8a Iustin Pop

1735 9332fd8a Iustin Pop

1736 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1737 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1738 5282084b Iustin Pop
  @param idx: the disk index
1739 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1740 9332fd8a Iustin Pop

1741 9332fd8a Iustin Pop
  """
1742 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1743 9332fd8a Iustin Pop
  try:
1744 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1745 5282084b Iustin Pop
  except OSError, err:
1746 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1747 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1748 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1749 9332fd8a Iustin Pop
        os.remove(link_name)
1750 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1751 9332fd8a Iustin Pop
    else:
1752 9332fd8a Iustin Pop
      raise
1753 9332fd8a Iustin Pop
1754 9332fd8a Iustin Pop
  return link_name
1755 9332fd8a Iustin Pop
1756 9332fd8a Iustin Pop
1757 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1758 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1759 3c9c571d Iustin Pop

1760 3c9c571d Iustin Pop
  """
1761 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1762 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1763 5282084b Iustin Pop
    if os.path.islink(link_name):
1764 3c9c571d Iustin Pop
      try:
1765 03dfa658 Iustin Pop
        os.remove(link_name)
1766 03dfa658 Iustin Pop
      except OSError:
1767 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1768 3c9c571d Iustin Pop
1769 3c9c571d Iustin Pop
1770 66d3d195 Dimitris Aragiorgis
def _CalculateDeviceURI(instance, disk, device):
1771 66d3d195 Dimitris Aragiorgis
  """Get the URI for the device.
1772 66d3d195 Dimitris Aragiorgis

1773 66d3d195 Dimitris Aragiorgis
  @type instance: L{objects.Instance}
1774 66d3d195 Dimitris Aragiorgis
  @param instance: the instance which disk belongs to
1775 66d3d195 Dimitris Aragiorgis
  @type disk: L{objects.Disk}
1776 66d3d195 Dimitris Aragiorgis
  @param disk: the target disk object
1777 66d3d195 Dimitris Aragiorgis
  @type device: L{bdev.BlockDev}
1778 66d3d195 Dimitris Aragiorgis
  @param device: the corresponding BlockDevice
1779 66d3d195 Dimitris Aragiorgis
  @rtype: string
1780 66d3d195 Dimitris Aragiorgis
  @return: the device uri if any else None
1781 66d3d195 Dimitris Aragiorgis

1782 66d3d195 Dimitris Aragiorgis
  """
1783 66d3d195 Dimitris Aragiorgis
  access_mode = disk.params.get(constants.LDP_ACCESS,
1784 66d3d195 Dimitris Aragiorgis
                                constants.DISK_KERNELSPACE)
1785 66d3d195 Dimitris Aragiorgis
  if access_mode == constants.DISK_USERSPACE:
1786 66d3d195 Dimitris Aragiorgis
    # This can raise errors.BlockDeviceError
1787 66d3d195 Dimitris Aragiorgis
    return device.GetUserspaceAccessUri(instance.hypervisor)
1788 66d3d195 Dimitris Aragiorgis
  else:
1789 66d3d195 Dimitris Aragiorgis
    return None
1790 66d3d195 Dimitris Aragiorgis
1791 66d3d195 Dimitris Aragiorgis
1792 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1793 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1794 a8083063 Iustin Pop

1795 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1796 a8083063 Iustin Pop
  devices must be already assembled.
1797 a8083063 Iustin Pop

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

1803 a8083063 Iustin Pop
  """
1804 a8083063 Iustin Pop
  block_devices = []
1805 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1806 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1807 a8083063 Iustin Pop
    if device is None:
1808 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1809 a8083063 Iustin Pop
                                    str(disk))
1810 a8083063 Iustin Pop
    device.Open()
1811 9332fd8a Iustin Pop
    try:
1812 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1813 9332fd8a Iustin Pop
    except OSError, e:
1814 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1815 9332fd8a Iustin Pop
                                    e.strerror)
1816 66d3d195 Dimitris Aragiorgis
    uri = _CalculateDeviceURI(instance, disk, device)
1817 9332fd8a Iustin Pop
1818 66d3d195 Dimitris Aragiorgis
    block_devices.append((disk, link_name, uri))
1819 9332fd8a Iustin Pop
1820 a8083063 Iustin Pop
  return block_devices
1821 a8083063 Iustin Pop
1822 a8083063 Iustin Pop
1823 1fa6fcba Michele Tartara
def StartInstance(instance, startup_paused, reason, store_reason=True):
1824 a8083063 Iustin Pop
  """Start an instance.
1825 a8083063 Iustin Pop

1826 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1827 e69d05fd Iustin Pop
  @param instance: the instance object
1828 323f9095 Stephen Shirley
  @type startup_paused: bool
1829 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1830 1fa6fcba Michele Tartara
  @type reason: list of reasons
1831 1fa6fcba Michele Tartara
  @param reason: the reason trail for this startup
1832 1fa6fcba Michele Tartara
  @type store_reason: boolean
1833 1fa6fcba Michele Tartara
  @param store_reason: whether to store the shutdown reason trail on file
1834 c26a6bd2 Iustin Pop
  @rtype: None
1835 a8083063 Iustin Pop

1836 098c0958 Michael Hanselmann
  """
1837 3361ab37 Helga Velroyen
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1838 3361ab37 Helga Velroyen
                                                   instance.hvparams)
1839 a8083063 Iustin Pop
1840 a8083063 Iustin Pop
  if instance.name in running_instances:
1841 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1842 c26a6bd2 Iustin Pop
    return
1843 a8083063 Iustin Pop
1844 a8083063 Iustin Pop
  try:
1845 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1846 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1847 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1848 1fa6fcba Michele Tartara
    if store_reason:
1849 1fa6fcba Michele Tartara
      _StoreInstReasonTrail(instance.name, reason)
1850 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1851 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1852 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1853 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1854 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1855 a8083063 Iustin Pop
1856 a8083063 Iustin Pop
1857 1f350e0f Michele Tartara
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1858 a8083063 Iustin Pop
  """Shut an instance down.
1859 a8083063 Iustin Pop

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

1862 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1863 e69d05fd Iustin Pop
  @param instance: the instance object
1864 6263189c Guido Trotter
  @type timeout: integer
1865 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1866 1f350e0f Michele Tartara
  @type reason: list of reasons
1867 1f350e0f Michele Tartara
  @param reason: the reason trail for this shutdown
1868 1f350e0f Michele Tartara
  @type store_reason: boolean
1869 1f350e0f Michele Tartara
  @param store_reason: whether to store the shutdown reason trail on file
1870 c26a6bd2 Iustin Pop
  @rtype: None
1871 a8083063 Iustin Pop

1872 098c0958 Michael Hanselmann
  """
1873 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1874 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1875 c26a6bd2 Iustin Pop
  iname = instance.name
1876 a8083063 Iustin Pop
1877 3361ab37 Helga Velroyen
  if instance.name not in hyper.ListInstances(instance.hvparams):
1878 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1879 c26a6bd2 Iustin Pop
    return
1880 a8083063 Iustin Pop
1881 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1882 3c0cdc83 Michael Hanselmann
    def __init__(self):
1883 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1884 a8083063 Iustin Pop
1885 3c0cdc83 Michael Hanselmann
    def __call__(self):
1886 3361ab37 Helga Velroyen
      if iname not in hyper.ListInstances(instance.hvparams):
1887 3c0cdc83 Michael Hanselmann
        return
1888 3c0cdc83 Michael Hanselmann
1889 3c0cdc83 Michael Hanselmann
      try:
1890 874f6148 Michele Tartara
        hyper.StopInstance(instance, retry=self.tried_once, timeout=timeout)
1891 1f350e0f Michele Tartara
        if store_reason:
1892 1f350e0f Michele Tartara
          _StoreInstReasonTrail(instance.name, reason)
1893 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1894 3361ab37 Helga Velroyen
        if iname not in hyper.ListInstances(instance.hvparams):
1895 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1896 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1897 3c0cdc83 Michael Hanselmann
          return
1898 3c0cdc83 Michael Hanselmann
1899 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1900 3c0cdc83 Michael Hanselmann
1901 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1902 3c0cdc83 Michael Hanselmann
1903 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1904 3c0cdc83 Michael Hanselmann
1905 3c0cdc83 Michael Hanselmann
  try:
1906 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1907 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1908 a8083063 Iustin Pop
    # the shutdown did not succeed
1909 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1910 a8083063 Iustin Pop
1911 a8083063 Iustin Pop
    try:
1912 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1913 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1914 3361ab37 Helga Velroyen
      if iname in hyper.ListInstances(instance.hvparams):
1915 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1916 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1917 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1918 a8083063 Iustin Pop
1919 a8083063 Iustin Pop
    time.sleep(1)
1920 3c0cdc83 Michael Hanselmann
1921 3361ab37 Helga Velroyen
    if iname in hyper.ListInstances(instance.hvparams):
1922 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1923 3c9c571d Iustin Pop
1924 f28ec899 Guido Trotter
  try:
1925 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1926 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1927 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1928 f28ec899 Guido Trotter
1929 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1930 a8083063 Iustin Pop
1931 a8083063 Iustin Pop
1932 55cec070 Michele Tartara
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1933 007a2f3e Alexander Schreiber
  """Reboot an instance.
1934 007a2f3e Alexander Schreiber

1935 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1936 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1937 10c2650b Iustin Pop
  @type reboot_type: str
1938 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1939 10c2650b Iustin Pop
    constants:
1940 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1941 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1942 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1943 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1944 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1945 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1946 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1947 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1948 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1949 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1950 55cec070 Michele Tartara
  @type reason: list of reasons
1951 55cec070 Michele Tartara
  @param reason: the reason trail for this reboot
1952 c26a6bd2 Iustin Pop
  @rtype: None
1953 007a2f3e Alexander Schreiber

1954 007a2f3e Alexander Schreiber
  """
1955 3361ab37 Helga Velroyen
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1956 3361ab37 Helga Velroyen
                                                   instance.hvparams)
1957 007a2f3e Alexander Schreiber
1958 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1959 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1960 007a2f3e Alexander Schreiber
1961 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1962 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1963 007a2f3e Alexander Schreiber
    try:
1964 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1965 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1966 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1967 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1968 007a2f3e Alexander Schreiber
    try:
1969 1f350e0f Michele Tartara
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1970 1fa6fcba Michele Tartara
      result = StartInstance(instance, False, reason, store_reason=False)
1971 55cec070 Michele Tartara
      _StoreInstReasonTrail(instance.name, reason)
1972 4a90bd4f Michele Tartara
      return result
1973 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1974 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1975 007a2f3e Alexander Schreiber
  else:
1976 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1977 007a2f3e Alexander Schreiber
1978 007a2f3e Alexander Schreiber
1979 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1980 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1981 ebe466d8 Guido Trotter

1982 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1983 ebe466d8 Guido Trotter
  @param instance: the instance object
1984 ebe466d8 Guido Trotter
  @type memory: int
1985 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1986 ebe466d8 Guido Trotter
  @rtype: None
1987 ebe466d8 Guido Trotter

1988 ebe466d8 Guido Trotter
  """
1989 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1990 3361ab37 Helga Velroyen
  running = hyper.ListInstances(instance.hvparams)
1991 ebe466d8 Guido Trotter
  if instance.name not in running:
1992 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1993 ebe466d8 Guido Trotter
    return
1994 ebe466d8 Guido Trotter
  try:
1995 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1996 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1997 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1998 ebe466d8 Guido Trotter
1999 ebe466d8 Guido Trotter
2000 6906a9d8 Guido Trotter
def MigrationInfo(instance):
2001 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
2002 6906a9d8 Guido Trotter

2003 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
2004 6906a9d8 Guido Trotter
  @param instance: the instance definition
2005 6906a9d8 Guido Trotter

2006 6906a9d8 Guido Trotter
  """
2007 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2008 cd42d0ad Guido Trotter
  try:
2009 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
2010 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
2011 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
2012 c26a6bd2 Iustin Pop
  return info
2013 6906a9d8 Guido Trotter
2014 6906a9d8 Guido Trotter
2015 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
2016 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
2017 6906a9d8 Guido Trotter

2018 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
2019 6906a9d8 Guido Trotter
  @param instance: the instance definition
2020 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
2021 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
2022 6906a9d8 Guido Trotter
  @type target: string
2023 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
2024 6906a9d8 Guido Trotter

2025 6906a9d8 Guido Trotter
  """
2026 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
2027 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
2028 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
2029 77fcff4a Apollon Oikonomopoulos
    # in any way
2030 77fcff4a Apollon Oikonomopoulos
    try:
2031 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
2032 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
2033 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
2034 77fcff4a Apollon Oikonomopoulos
2035 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2036 cd42d0ad Guido Trotter
  try:
2037 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
2038 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
2039 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
2040 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
2041 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
2042 6906a9d8 Guido Trotter
2043 6906a9d8 Guido Trotter
2044 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
2045 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
2046 6906a9d8 Guido Trotter

2047 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
2048 6906a9d8 Guido Trotter
  @param instance: the instance definition
2049 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
2050 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
2051 6906a9d8 Guido Trotter
  @type success: boolean
2052 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
2053 6906a9d8 Guido Trotter

2054 6906a9d8 Guido Trotter
  """
2055 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2056 cd42d0ad Guido Trotter
  try:
2057 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
2058 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
2059 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
2060 6906a9d8 Guido Trotter
2061 6906a9d8 Guido Trotter
2062 bc0a2284 Helga Velroyen
def MigrateInstance(cluster_name, instance, target, live):
2063 2a10865c Iustin Pop
  """Migrates an instance to another node.
2064 2a10865c Iustin Pop

2065 bc0a2284 Helga Velroyen
  @type cluster_name: string
2066 bc0a2284 Helga Velroyen
  @param cluster_name: name of the cluster
2067 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
2068 9f0e6b37 Iustin Pop
  @param instance: the instance definition
2069 9f0e6b37 Iustin Pop
  @type target: string
2070 9f0e6b37 Iustin Pop
  @param target: the target node name
2071 9f0e6b37 Iustin Pop
  @type live: boolean
2072 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
2073 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
2074 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
2075 9f0e6b37 Iustin Pop

2076 2a10865c Iustin Pop
  """
2077 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2078 2a10865c Iustin Pop
2079 2a10865c Iustin Pop
  try:
2080 bc0a2284 Helga Velroyen
    hyper.MigrateInstance(cluster_name, instance, target, live)
2081 2a10865c Iustin Pop
  except errors.HypervisorError, err:
2082 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
2083 2a10865c Iustin Pop
2084 2a10865c Iustin Pop
2085 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
2086 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
2087 6a1434d7 Andrea Spadaccini

2088 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
2089 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
2090 6a1434d7 Andrea Spadaccini
  @type success: bool
2091 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
2092 6a1434d7 Andrea Spadaccini
  @type live: bool
2093 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
2094 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
2095 6a1434d7 Andrea Spadaccini

2096 6a1434d7 Andrea Spadaccini
  """
2097 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2098 6a1434d7 Andrea Spadaccini
2099 6a1434d7 Andrea Spadaccini
  try:
2100 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
2101 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
2102 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
2103 6a1434d7 Andrea Spadaccini
          exc=True)
2104 6a1434d7 Andrea Spadaccini
2105 6a1434d7 Andrea Spadaccini
2106 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
2107 6a1434d7 Andrea Spadaccini
  """Get the migration status
2108 6a1434d7 Andrea Spadaccini

2109 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
2110 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
2111 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
2112 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
2113 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
2114 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
2115 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
2116 6a1434d7 Andrea Spadaccini

2117 6a1434d7 Andrea Spadaccini
  """
2118 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2119 6a1434d7 Andrea Spadaccini
  try:
2120 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
2121 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
2122 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
2123 6a1434d7 Andrea Spadaccini
2124 6a1434d7 Andrea Spadaccini
2125 c5708931 Dimitris Aragiorgis
def HotplugDevice(instance, action, dev_type, device, extra, seq):
2126 c5708931 Dimitris Aragiorgis
  """Hotplug a device
2127 c5708931 Dimitris Aragiorgis

2128 c5708931 Dimitris Aragiorgis
  Hotplug is currently supported only for KVM Hypervisor.
2129 c5708931 Dimitris Aragiorgis
  @type instance: L{objects.Instance}
2130 c5708931 Dimitris Aragiorgis
  @param instance: the instance to which we hotplug a device
2131 c5708931 Dimitris Aragiorgis
  @type action: string
2132 c5708931 Dimitris Aragiorgis
  @param action: the hotplug action to perform
2133 c5708931 Dimitris Aragiorgis
  @type dev_type: string
2134 c5708931 Dimitris Aragiorgis
  @param dev_type: the device type to hotplug
2135 c5708931 Dimitris Aragiorgis
  @type device: either L{objects.NIC} or L{objects.Disk}
2136 c5708931 Dimitris Aragiorgis
  @param device: the device object to hotplug
2137 c5708931 Dimitris Aragiorgis
  @type extra: string
2138 c5708931 Dimitris Aragiorgis
  @param extra: extra info used by hotplug code (e.g. disk link)
2139 c5708931 Dimitris Aragiorgis
  @type seq: int
2140 c5708931 Dimitris Aragiorgis
  @param seq: the index of the device from master perspective
2141 c5708931 Dimitris Aragiorgis
  @raise RPCFail: in case instance does not have KVM hypervisor
2142 c5708931 Dimitris Aragiorgis

2143 c5708931 Dimitris Aragiorgis
  """
2144 c5708931 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2145 c5708931 Dimitris Aragiorgis
  try:
2146 50e0f1d9 Dimitris Aragiorgis
    hyper.VerifyHotplugSupport(instance, action, dev_type)
2147 50e0f1d9 Dimitris Aragiorgis
  except errors.HotplugError, err:
2148 c5708931 Dimitris Aragiorgis
    _Fail("Hotplug is not supported: %s", err)
2149 c5708931 Dimitris Aragiorgis
2150 c5708931 Dimitris Aragiorgis
  if action == constants.HOTPLUG_ACTION_ADD:
2151 c5708931 Dimitris Aragiorgis
    fn = hyper.HotAddDevice
2152 c5708931 Dimitris Aragiorgis
  elif action == constants.HOTPLUG_ACTION_REMOVE:
2153 c5708931 Dimitris Aragiorgis
    fn = hyper.HotDelDevice
2154 c5708931 Dimitris Aragiorgis
  elif action == constants.HOTPLUG_ACTION_MODIFY:
2155 c5708931 Dimitris Aragiorgis
    fn = hyper.HotModDevice
2156 c5708931 Dimitris Aragiorgis
  else:
2157 c5708931 Dimitris Aragiorgis
    assert action in constants.HOTPLUG_ALL_ACTIONS
2158 c5708931 Dimitris Aragiorgis
2159 c5708931 Dimitris Aragiorgis
  return fn(instance, dev_type, device, extra, seq)
2160 c5708931 Dimitris Aragiorgis
2161 c5708931 Dimitris Aragiorgis
2162 24711492 Dimitris Aragiorgis
def HotplugSupported(instance):
2163 24711492 Dimitris Aragiorgis
  """Checks if hotplug is generally supported.
2164 24711492 Dimitris Aragiorgis

2165 24711492 Dimitris Aragiorgis
  """
2166 24711492 Dimitris Aragiorgis
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2167 24711492 Dimitris Aragiorgis
  try:
2168 24711492 Dimitris Aragiorgis
    hyper.HotplugSupported(instance)
2169 24711492 Dimitris Aragiorgis
  except errors.HotplugError, err:
2170 24711492 Dimitris Aragiorgis
    _Fail("Hotplug is not supported: %s", err)
2171 24711492 Dimitris Aragiorgis
2172 24711492 Dimitris Aragiorgis
2173 ee1478e5 Bernardo Dal Seno
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
2174 a8083063 Iustin Pop
  """Creates a block device for an instance.
2175 a8083063 Iustin Pop

2176 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
2177 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
2178 b1206984 Iustin Pop
  @type size: int
2179 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
2180 b1206984 Iustin Pop
  @type owner: str
2181 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
2182 b1206984 Iustin Pop
      used for device cache data
2183 b1206984 Iustin Pop
  @type on_primary: boolean
2184 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
2185 b1206984 Iustin Pop
  @type info: string
2186 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
2187 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
2188 ee1478e5 Bernardo Dal Seno
  @type excl_stor: boolean
2189 ee1478e5 Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
2190 b1206984 Iustin Pop

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

2195 a8083063 Iustin Pop
  """
2196 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
2197 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
2198 a8083063 Iustin Pop
  clist = []
2199 a8083063 Iustin Pop
  if disk.children:
2200 a8083063 Iustin Pop
    for child in disk.children:
2201 1063abd1 Iustin Pop
      try:
2202 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
2203 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
2204 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
2205 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
2206 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
2207 a8083063 Iustin Pop
        # be assembled
2208 1063abd1 Iustin Pop
        try:
2209 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
2210 1063abd1 Iustin Pop
          crdev.Open()
2211 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
2212 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
2213 a8083063 Iustin Pop
      clist.append(crdev)
2214 a8083063 Iustin Pop
2215 dab69e97 Iustin Pop
  try:
2216 ee1478e5 Bernardo Dal Seno
    device = bdev.Create(disk, clist, excl_stor)
2217 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
2218 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
2219 6c626518 Iustin Pop
2220 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
2221 1063abd1 Iustin Pop
    try:
2222 1063abd1 Iustin Pop
      device.Assemble()
2223 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
2224 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
2225 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
2226 1063abd1 Iustin Pop
      try:
2227 1063abd1 Iustin Pop
        device.Open(force=True)
2228 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
2229 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
2230 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
2231 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
2232 a0c3fea1 Michael Hanselmann
2233 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
2234 a0c3fea1 Michael Hanselmann
2235 c26a6bd2 Iustin Pop
  return device.unique_id
2236 a8083063 Iustin Pop
2237 a8083063 Iustin Pop
2238 326e0925 Jose A. Lopes
def _DumpDevice(source_path, target_path, offset, size, truncate):
2239 229fb4ea Jose A. Lopes
  """This function images/wipes the device using a local file.
2240 69dd363f René Nussbaumer

2241 229fb4ea Jose A. Lopes
  @type source_path: string
2242 229fb4ea Jose A. Lopes
  @param source_path: path of the image or data source (e.g., "/dev/zero")
2243 229fb4ea Jose A. Lopes

2244 229fb4ea Jose A. Lopes
  @type target_path: string
2245 229fb4ea Jose A. Lopes
  @param target_path: path of the device to image/wipe
2246 229fb4ea Jose A. Lopes

2247 229fb4ea Jose A. Lopes
  @type offset: int
2248 229fb4ea Jose A. Lopes
  @param offset: offset in MiB in the output file
2249 229fb4ea Jose A. Lopes

2250 229fb4ea Jose A. Lopes
  @type size: int
2251 229fb4ea Jose A. Lopes
  @param size: maximum size in MiB to write (data source might be smaller)
2252 229fb4ea Jose A. Lopes

2253 326e0925 Jose A. Lopes
  @type truncate: bool
2254 326e0925 Jose A. Lopes
  @param truncate: whether the file should be truncated
2255 326e0925 Jose A. Lopes

2256 229fb4ea Jose A. Lopes
  @return: None
2257 229fb4ea Jose A. Lopes
  @raise RPCFail: in case of failure
2258 69dd363f René Nussbaumer

2259 69dd363f René Nussbaumer
  """
2260 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
2261 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
2262 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
2263 0188611b Michael Hanselmann
  block_size = 1024 * 1024
2264 0188611b Michael Hanselmann
2265 229fb4ea Jose A. Lopes
  cmd = [constants.DD_CMD, "if=%s" % source_path, "seek=%d" % offset,
2266 229fb4ea Jose A. Lopes
         "bs=%s" % block_size, "oflag=direct", "of=%s" % target_path,
2267 da63bb4e René Nussbaumer
         "count=%d" % size]
2268 326e0925 Jose A. Lopes
2269 326e0925 Jose A. Lopes
  if not truncate:
2270 326e0925 Jose A. Lopes
    cmd.append("conv=notrunc")
2271 326e0925 Jose A. Lopes
2272 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
2273 69dd363f René Nussbaumer
2274 69dd363f René Nussbaumer
  if result.failed:
2275 229fb4ea Jose A. Lopes
    _Fail("Dump command '%s' exited with error: %s; output: %s", result.cmd,
2276 69dd363f René Nussbaumer
          result.fail_reason, result.output)
2277 69dd363f René Nussbaumer
2278 69dd363f René Nussbaumer
2279 c89622cd Jose A. Lopes
def _DownloadAndDumpDevice(source_url, target_path, size):
2280 c89622cd Jose A. Lopes
  """This function images a device using a downloaded image file.
2281 c89622cd Jose A. Lopes

2282 c89622cd Jose A. Lopes
  @type source_url: string
2283 c89622cd Jose A. Lopes
  @param source_url: URL of image to dump to disk
2284 c89622cd Jose A. Lopes

2285 c89622cd Jose A. Lopes
  @type target_path: string
2286 c89622cd Jose A. Lopes
  @param target_path: path of the device to image
2287 c89622cd Jose A. Lopes

2288 c89622cd Jose A. Lopes
  @type size: int
2289 c89622cd Jose A. Lopes
  @param size: maximum size in MiB to write (data source might be smaller)
2290 c89622cd Jose A. Lopes

2291 c89622cd Jose A. Lopes
  @rtype: NoneType
2292 c89622cd Jose A. Lopes
  @return: None
2293 c89622cd Jose A. Lopes
  @raise RPCFail: in case of download or write failures
2294 c89622cd Jose A. Lopes

2295 c89622cd Jose A. Lopes
  """
2296 c89622cd Jose A. Lopes
  class DDParams(object):
2297 c89622cd Jose A. Lopes
    def __init__(self, current_size, total_size):
2298 c89622cd Jose A. Lopes
      self.current_size = current_size
2299 c89622cd Jose A. Lopes
      self.total_size = total_size
2300 c89622cd Jose A. Lopes
      self.image_size_error = False
2301 c89622cd Jose A. Lopes
2302 c89622cd Jose A. Lopes
  def dd_write(ddparams, out):
2303 c89622cd Jose A. Lopes
    if ddparams.current_size < ddparams.total_size:
2304 c89622cd Jose A. Lopes
      ddparams.current_size += len(out)
2305 c89622cd Jose A. Lopes
      target_file.write(out)
2306 c89622cd Jose A. Lopes
    else:
2307 c89622cd Jose A. Lopes
      ddparams.image_size_error = True
2308 c89622cd Jose A. Lopes
      return -1
2309 c89622cd Jose A. Lopes
2310 ee6106f0 Jose A. Lopes
  target_file = open(target_path, "r+")
2311 c89622cd Jose A. Lopes
  ddparams = DDParams(0, 1024 * 1024 * size)
2312 c89622cd Jose A. Lopes
2313 c89622cd Jose A. Lopes
  curl = pycurl.Curl()
2314 c89622cd Jose A. Lopes
  curl.setopt(pycurl.VERBOSE, True)
2315 c89622cd Jose A. Lopes
  curl.setopt(pycurl.NOSIGNAL, True)
2316 c89622cd Jose A. Lopes
  curl.setopt(pycurl.USERAGENT, http.HTTP_GANETI_VERSION)
2317 c89622cd Jose A. Lopes
  curl.setopt(pycurl.URL, source_url)
2318 c89622cd Jose A. Lopes
  curl.setopt(pycurl.WRITEFUNCTION, lambda out: dd_write(ddparams, out))
2319 c89622cd Jose A. Lopes
2320 c89622cd Jose A. Lopes
  try:
2321 c89622cd Jose A. Lopes
    curl.perform()
2322 c89622cd Jose A. Lopes
  except pycurl.error:
2323 c89622cd Jose A. Lopes
    if ddparams.image_size_error:
2324 c89622cd Jose A. Lopes
      _Fail("Disk image larger than the disk")
2325 c89622cd Jose A. Lopes
    else:
2326 c89622cd Jose A. Lopes
      raise
2327 c89622cd Jose A. Lopes
2328 c89622cd Jose A. Lopes
  target_file.close()
2329 c89622cd Jose A. Lopes
2330 c89622cd Jose A. Lopes
2331 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
2332 69dd363f René Nussbaumer
  """Wipes a block device.
2333 69dd363f René Nussbaumer

2334 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
2335 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
2336 da63bb4e René Nussbaumer
  @type offset: int
2337 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
2338 da63bb4e René Nussbaumer
  @type size: int
2339 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
2340 69dd363f René Nussbaumer

2341 69dd363f René Nussbaumer
  """
2342 69dd363f René Nussbaumer
  try:
2343 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
2344 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
2345 da63bb4e René Nussbaumer
    rdev = None
2346 da63bb4e René Nussbaumer
2347 da63bb4e René Nussbaumer
  if not rdev:
2348 229fb4ea Jose A. Lopes
    _Fail("Cannot wipe device %s: device not found", disk.iv_name)
2349 0188611b Michael Hanselmann
  if offset < 0:
2350 0188611b Michael Hanselmann
    _Fail("Negative offset")
2351 0188611b Michael Hanselmann
  if size < 0:
2352 0188611b Michael Hanselmann
    _Fail("Negative size")
2353 da63bb4e René Nussbaumer
  if offset > rdev.size:
2354 229fb4ea Jose A. Lopes
    _Fail("Wipe offset is bigger than device size")
2355 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
2356 229fb4ea Jose A. Lopes
    _Fail("Wipe offset and size are bigger than device size")
2357 229fb4ea Jose A. Lopes
2358 326e0925 Jose A. Lopes
  _DumpDevice("/dev/zero", rdev.dev_path, offset, size, True)
2359 69dd363f René Nussbaumer
2360 69dd363f René Nussbaumer
2361 2b8322f7 Jose A. Lopes
def BlockdevImage(disk, image, size):
2362 2b8322f7 Jose A. Lopes
  """Images a block device either by dumping a local file or
2363 2b8322f7 Jose A. Lopes
  downloading a URL.
2364 2b8322f7 Jose A. Lopes

2365 2b8322f7 Jose A. Lopes
  @type disk: L{objects.Disk}
2366 2b8322f7 Jose A. Lopes
  @param disk: the disk object we want to image
2367 2b8322f7 Jose A. Lopes

2368 2b8322f7 Jose A. Lopes
  @type image: string
2369 2b8322f7 Jose A. Lopes
  @param image: file path to the disk image be dumped
2370 2b8322f7 Jose A. Lopes

2371 2b8322f7 Jose A. Lopes
  @type size: int
2372 2b8322f7 Jose A. Lopes
  @param size: The size in MiB to write
2373 2b8322f7 Jose A. Lopes

2374 2b8322f7 Jose A. Lopes
  @rtype: NoneType
2375 2b8322f7 Jose A. Lopes
  @return: None
2376 2b8322f7 Jose A. Lopes
  @raise RPCFail: in case of failure
2377 2b8322f7 Jose A. Lopes

2378 2b8322f7 Jose A. Lopes
  """
2379 d00e49f6 Jose A. Lopes
  if not (utils.IsUrl(image) or os.path.exists(image)):
2380 d00e49f6 Jose A. Lopes
    _Fail("Image '%s' not found", image)
2381 d00e49f6 Jose A. Lopes
2382 2b8322f7 Jose A. Lopes
  try:
2383 2b8322f7 Jose A. Lopes
    rdev = _RecursiveFindBD(disk)
2384 2b8322f7 Jose A. Lopes
  except errors.BlockDeviceError:
2385 2b8322f7 Jose A. Lopes
    rdev = None
2386 2b8322f7 Jose A. Lopes
2387 2b8322f7 Jose A. Lopes
  if not rdev:
2388 2b8322f7 Jose A. Lopes
    _Fail("Cannot image device %s: device not found", disk.iv_name)
2389 2b8322f7 Jose A. Lopes
  if size < 0:
2390 2b8322f7 Jose A. Lopes
    _Fail("Negative size")
2391 2b8322f7 Jose A. Lopes
  if size > rdev.size:
2392 2b8322f7 Jose A. Lopes
    _Fail("Image size is bigger than device size")
2393 2b8322f7 Jose A. Lopes
2394 2b8322f7 Jose A. Lopes
  if utils.IsUrl(image):
2395 2b8322f7 Jose A. Lopes
    _DownloadAndDumpDevice(image, rdev.dev_path, size)
2396 2b8322f7 Jose A. Lopes
  else:
2397 326e0925 Jose A. Lopes
    _DumpDevice(image, rdev.dev_path, 0, size, False)
2398 2b8322f7 Jose A. Lopes
2399 69dd363f René Nussbaumer
2400 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
2401 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
2402 5119c79e René Nussbaumer

2403 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
2404 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
2405 5119c79e René Nussbaumer
  @type pause: bool
2406 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
2407 5119c79e René Nussbaumer

2408 5119c79e René Nussbaumer
  """
2409 5119c79e René Nussbaumer
  success = []
2410 5119c79e René Nussbaumer
  for disk in disks:
2411 5119c79e René Nussbaumer
    try:
2412 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
2413 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
2414 5119c79e René Nussbaumer
      rdev = None
2415 5119c79e René Nussbaumer
2416 5119c79e René Nussbaumer
    if not rdev:
2417 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
2418 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
2419 5119c79e René Nussbaumer
      continue
2420 5119c79e René Nussbaumer
2421 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
2422 5119c79e René Nussbaumer
2423 5119c79e René Nussbaumer
    if result:
2424 5119c79e René Nussbaumer
      success.append((result, None))
2425 5119c79e René Nussbaumer
    else:
2426 5119c79e René Nussbaumer
      if pause:
2427 5119c79e René Nussbaumer
        msg = "Pause"
2428 5119c79e René Nussbaumer
      else:
2429 5119c79e René Nussbaumer
        msg = "Resume"
2430 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2431 5119c79e René Nussbaumer
2432 5119c79e René Nussbaumer
  return success
2433 5119c79e René Nussbaumer
2434 5119c79e René Nussbaumer
2435 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
2436 a8083063 Iustin Pop
  """Remove a block device.
2437 a8083063 Iustin Pop

2438 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
2439 10c2650b Iustin Pop

2440 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
2441 10c2650b Iustin Pop
  @param disk: the disk object we should remove
2442 10c2650b Iustin Pop
  @rtype: boolean
2443 10c2650b Iustin Pop
  @return: the success of the operation
2444 a8083063 Iustin Pop

2445 a8083063 Iustin Pop
  """
2446 e1bc0878 Iustin Pop
  msgs = []
2447 a8083063 Iustin Pop
  try:
2448 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
2449 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
2450 a8083063 Iustin Pop
    # probably can't attach
2451 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
2452 a8083063 Iustin Pop
    rdev = None
2453 a8083063 Iustin Pop
  if rdev is not None:
2454 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
2455 b3ae67d7 Dimitris Aragiorgis
2456 b3ae67d7 Dimitris Aragiorgis
    def _TryRemove():
2457 b3ae67d7 Dimitris Aragiorgis
      try:
2458 b3ae67d7 Dimitris Aragiorgis
        rdev.Remove()
2459 b3ae67d7 Dimitris Aragiorgis
        return []
2460 b3ae67d7 Dimitris Aragiorgis
      except errors.BlockDeviceError, err:
2461 b3ae67d7 Dimitris Aragiorgis
        return [str(err)]
2462 b3ae67d7 Dimitris Aragiorgis
2463 b3ae67d7 Dimitris Aragiorgis
    msgs.extend(utils.SimpleRetry([], _TryRemove,
2464 b3ae67d7 Dimitris Aragiorgis
                                  constants.DISK_REMOVE_RETRY_INTERVAL,
2465 b3ae67d7 Dimitris Aragiorgis
                                  constants.DISK_REMOVE_RETRY_TIMEOUT))
2466 b3ae67d7 Dimitris Aragiorgis
2467 c26a6bd2 Iustin Pop
    if not msgs:
2468 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
2469 e1bc0878 Iustin Pop
2470 a8083063 Iustin Pop
  if disk.children:
2471 a8083063 Iustin Pop
    for child in disk.children:
2472 c26a6bd2 Iustin Pop
      try:
2473 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
2474 c26a6bd2 Iustin Pop
      except RPCFail, err:
2475 c26a6bd2 Iustin Pop
        msgs.append(str(err))
2476 e1bc0878 Iustin Pop
2477 c26a6bd2 Iustin Pop
  if msgs:
2478 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2479 afdc3985 Iustin Pop
2480 a8083063 Iustin Pop
2481 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
2482 a8083063 Iustin Pop
  """Activate a block device for an instance.
2483 a8083063 Iustin Pop

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

2486 10c2650b Iustin Pop
  @note: this function is called recursively.
2487 a8083063 Iustin Pop

2488 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2489 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
2490 10c2650b Iustin Pop
  @type owner: str
2491 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
2492 10c2650b Iustin Pop
  @type as_primary: boolean
2493 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
2494 10c2650b Iustin Pop
      read/write
2495 a8083063 Iustin Pop

2496 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
2497 10c2650b Iustin Pop
      was assembled)
2498 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
2499 10c2650b Iustin Pop
      during the activation of the children or the device
2500 10c2650b Iustin Pop
      itself
2501 a8083063 Iustin Pop

2502 a8083063 Iustin Pop
  """
2503 a8083063 Iustin Pop
  children = []
2504 a8083063 Iustin Pop
  if disk.children:
2505 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
2506 fc1dc9d7 Iustin Pop
    if mcn == -1:
2507 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
2508 fc1dc9d7 Iustin Pop
    else:
2509 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
2510 a8083063 Iustin Pop
    for chld_disk in disk.children:
2511 fc1dc9d7 Iustin Pop
      try:
2512 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2513 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
2514 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
2515 fc1dc9d7 Iustin Pop
          raise
2516 fc1dc9d7 Iustin Pop
        cdev = None
2517 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
2518 1063abd1 Iustin Pop
                      str(err))
2519 fc1dc9d7 Iustin Pop
      children.append(cdev)
2520 a8083063 Iustin Pop
2521 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
2522 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
2523 a8083063 Iustin Pop
    result = r_dev
2524 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
2525 a8083063 Iustin Pop
      r_dev.Open()
2526 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2527 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
2528 3f78eef2 Iustin Pop
2529 a8083063 Iustin Pop
  else:
2530 a8083063 Iustin Pop
    result = True
2531 a8083063 Iustin Pop
  return result
2532 a8083063 Iustin Pop
2533 a8083063 Iustin Pop
2534 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
2535 a8083063 Iustin Pop
  """Activate a block device for an instance.
2536 a8083063 Iustin Pop

2537 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
2538 a8083063 Iustin Pop

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

2543 a8083063 Iustin Pop
  """
2544 53c14ef1 Iustin Pop
  try:
2545 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2546 89ff748d Thomas Thrainer
    if isinstance(result, BlockDev):
2547 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
2548 ff5def9b Dimitris Aragiorgis
      dev_path = result.dev_path
2549 ff5def9b Dimitris Aragiorgis
      link_name = None
2550 c417e115 Iustin Pop
      if as_primary:
2551 ff5def9b Dimitris Aragiorgis
        link_name = _SymlinkBlockDev(owner, dev_path, idx)
2552 ff5def9b Dimitris Aragiorgis
    elif result:
2553 ff5def9b Dimitris Aragiorgis
      return result, result
2554 ff5def9b Dimitris Aragiorgis
    else:
2555 ff5def9b Dimitris Aragiorgis
      _Fail("Unexpected result from _RecursiveAssembleBD")
2556 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
2557 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
2558 c417e115 Iustin Pop
  except OSError, err:
2559 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
2560 afdc3985 Iustin Pop
2561 ff5def9b Dimitris Aragiorgis
  return dev_path, link_name
2562 a8083063 Iustin Pop
2563 a8083063 Iustin Pop
2564 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
2565 a8083063 Iustin Pop
  """Shut down a block device.
2566 a8083063 Iustin Pop

2567 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
2568 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
2569 c41eea6e Iustin Pop
  shutdown.
2570 a8083063 Iustin Pop

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

2575 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2576 10c2650b Iustin Pop
  @param disk: the description of the disk we should
2577 10c2650b Iustin Pop
      shutdown
2578 c26a6bd2 Iustin Pop
  @rtype: None
2579 10c2650b Iustin Pop

2580 a8083063 Iustin Pop
  """
2581 cacfd1fd Iustin Pop
  msgs = []
2582 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2583 a8083063 Iustin Pop
  if r_dev is not None:
2584 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
2585 cacfd1fd Iustin Pop
    try:
2586 746f7476 Iustin Pop
      r_dev.Shutdown()
2587 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
2588 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
2589 cacfd1fd Iustin Pop
      msgs.append(str(err))
2590 746f7476 Iustin Pop
2591 a8083063 Iustin Pop
  if disk.children:
2592 a8083063 Iustin Pop
    for child in disk.children:
2593 c26a6bd2 Iustin Pop
      try:
2594 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
2595 c26a6bd2 Iustin Pop
      except RPCFail, err:
2596 c26a6bd2 Iustin Pop
        msgs.append(str(err))
2597 746f7476 Iustin Pop
2598 c26a6bd2 Iustin Pop
  if msgs:
2599 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2600 a8083063 Iustin Pop
2601 a8083063 Iustin Pop
2602 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
2603 153d9724 Iustin Pop
  """Extend a mirrored block device.
2604 a8083063 Iustin Pop

2605 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
2606 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
2607 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
2608 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
2609 c26a6bd2 Iustin Pop
  @rtype: None
2610 10c2650b Iustin Pop

2611 a8083063 Iustin Pop
  """
2612 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
2613 153d9724 Iustin Pop
  if parent_bdev is None:
2614 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2615 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2616 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
2617 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2618 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
2619 a8083063 Iustin Pop
2620 a8083063 Iustin Pop
2621 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2622 153d9724 Iustin Pop
  """Shrink a mirrored block device.
2623 a8083063 Iustin Pop

2624 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
2625 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
2626 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
2627 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
2628 c26a6bd2 Iustin Pop
  @rtype: None
2629 10c2650b Iustin Pop

2630 a8083063 Iustin Pop
  """
2631 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
2632 153d9724 Iustin Pop
  if parent_bdev is None:
2633 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2634 e739bd57 Iustin Pop
  devs = []
2635 e739bd57 Iustin Pop
  for disk in new_cdevs:
2636 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
2637 e739bd57 Iustin Pop
    if rpath is None:
2638 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
2639 e739bd57 Iustin Pop
      if bd is None:
2640 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
2641 e739bd57 Iustin Pop
      else:
2642 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
2643 e739bd57 Iustin Pop
    else:
2644 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
2645 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2646 e739bd57 Iustin Pop
      devs.append(rpath)
2647 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
2648 a8083063 Iustin Pop
2649 a8083063 Iustin Pop
2650 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
2651 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
2652 a8083063 Iustin Pop

2653 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2654 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
2655 10c2650b Iustin Pop
  @rtype: disk
2656 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
2657 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
2658 10c2650b Iustin Pop
      found
2659 a8083063 Iustin Pop

2660 a8083063 Iustin Pop
  """
2661 a8083063 Iustin Pop
  stats = []
2662 a8083063 Iustin Pop
  for dsk in disks:
2663 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
2664 a8083063 Iustin Pop
    if rbd is None:
2665 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
2666 96acbc09 Michael Hanselmann
2667 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
2668 96acbc09 Michael Hanselmann
2669 c26a6bd2 Iustin Pop
  return stats
2670 a8083063 Iustin Pop
2671 a8083063 Iustin Pop
2672 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
2673 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
2674 c6a9dffa Michael Hanselmann

2675 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
2676 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
2677 c6a9dffa Michael Hanselmann
  @rtype: disk
2678 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2679 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
2680 c6a9dffa Michael Hanselmann
    otherwise
2681 c6a9dffa Michael Hanselmann

2682 c6a9dffa Michael Hanselmann
  """
2683 c6a9dffa Michael Hanselmann
  result = []
2684 c6a9dffa Michael Hanselmann
  for disk in disks:
2685 c6a9dffa Michael Hanselmann
    try:
2686 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
2687 c6a9dffa Michael Hanselmann
      if rbd is None:
2688 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
2689 c6a9dffa Michael Hanselmann
        continue
2690 c6a9dffa Michael Hanselmann
2691 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
2692 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
2693 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
2694 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
2695 c6a9dffa Michael Hanselmann
    else:
2696 c6a9dffa Michael Hanselmann
      result.append((True, status))
2697 c6a9dffa Michael Hanselmann
2698 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
2699 c6a9dffa Michael Hanselmann
2700 c6a9dffa Michael Hanselmann
  return result
2701 c6a9dffa Michael Hanselmann
2702 c6a9dffa Michael Hanselmann
2703 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
2704 a8083063 Iustin Pop
  """Check if a device is activated.
2705 a8083063 Iustin Pop

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

2708 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2709 10c2650b Iustin Pop
  @param disk: the disk object we need to find
2710 a8083063 Iustin Pop

2711 10c2650b Iustin Pop
  @return: None if the device can't be found,
2712 10c2650b Iustin Pop
      otherwise the device instance
2713 a8083063 Iustin Pop

2714 a8083063 Iustin Pop
  """
2715 a8083063 Iustin Pop
  children = []
2716 a8083063 Iustin Pop
  if disk.children:
2717 a8083063 Iustin Pop
    for chdisk in disk.children:
2718 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
2719 a8083063 Iustin Pop
2720 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
2721 a8083063 Iustin Pop
2722 a8083063 Iustin Pop
2723 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
2724 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
2725 f2e07bb4 Michael Hanselmann

2726 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
2727 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
2728 f2e07bb4 Michael Hanselmann

2729 f2e07bb4 Michael Hanselmann
  """
2730 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
2731 f2e07bb4 Michael Hanselmann
  if real_disk is None:
2732 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
2733 f2e07bb4 Michael Hanselmann
2734 f2e07bb4 Michael Hanselmann
  real_disk.Open()
2735 f2e07bb4 Michael Hanselmann
2736 f2e07bb4 Michael Hanselmann
  return real_disk
2737 f2e07bb4 Michael Hanselmann
2738 f2e07bb4 Michael Hanselmann
2739 821d1bd1 Iustin Pop
def BlockdevFind(disk):
2740 a8083063 Iustin Pop
  """Check if a device is activated.
2741 a8083063 Iustin Pop

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

2744 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2745 10c2650b Iustin Pop
  @param disk: the disk to find
2746 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2747 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2748 96acbc09 Michael Hanselmann
           information
2749 a8083063 Iustin Pop

2750 a8083063 Iustin Pop
  """
2751 23829f6f Iustin Pop
  try:
2752 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
2753 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
2754 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
2755 96acbc09 Michael Hanselmann
2756 a8083063 Iustin Pop
  if rbd is None:
2757 c26a6bd2 Iustin Pop
    return None
2758 96acbc09 Michael Hanselmann
2759 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2760 a8083063 Iustin Pop
2761 a8083063 Iustin Pop
2762 6ef8077e Bernardo Dal Seno
def BlockdevGetdimensions(disks):
2763 968a7623 Iustin Pop
  """Computes the size of the given disks.
2764 968a7623 Iustin Pop

2765 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2766 968a7623 Iustin Pop

2767 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2768 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2769 968a7623 Iustin Pop
  @rtype: list
2770 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2771 6ef8077e Bernardo Dal Seno
      otherwise the pair (size, spindles), where spindles is None if the
2772 6ef8077e Bernardo Dal Seno
      device doesn't support that
2773 968a7623 Iustin Pop

2774 968a7623 Iustin Pop
  """
2775 968a7623 Iustin Pop
  result = []
2776 968a7623 Iustin Pop
  for cf in disks:
2777 968a7623 Iustin Pop
    try:
2778 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2779 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2780 968a7623 Iustin Pop
      result.append(None)
2781 968a7623 Iustin Pop
      continue
2782 968a7623 Iustin Pop
    if rbd is None:
2783 968a7623 Iustin Pop
      result.append(None)
2784 968a7623 Iustin Pop
    else:
2785 6ef8077e Bernardo Dal Seno
      result.append(rbd.GetActualDimensions())
2786 968a7623 Iustin Pop
  return result
2787 968a7623 Iustin Pop
2788 968a7623 Iustin Pop
2789 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2790 a8083063 Iustin Pop
  """Write a file to the filesystem.
2791 a8083063 Iustin Pop

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

2795 10c2650b Iustin Pop
  @type file_name: str
2796 10c2650b Iustin Pop
  @param file_name: the target file name
2797 10c2650b Iustin Pop
  @type data: str
2798 10c2650b Iustin Pop
  @param data: the new contents of the file
2799 10c2650b Iustin Pop
  @type mode: int
2800 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2801 9a914f7a René Nussbaumer
  @type uid: string
2802 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2803 9a914f7a René Nussbaumer
  @type gid: string
2804 9a914f7a René Nussbaumer
  @param gid: the group of the file
2805 10c2650b Iustin Pop
  @type atime: float
2806 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2807 10c2650b Iustin Pop
  @type mtime: float
2808 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2809 c26a6bd2 Iustin Pop
  @rtype: None
2810 10c2650b Iustin Pop

2811 a8083063 Iustin Pop
  """
2812 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2813 cffbbae7 Michael Hanselmann
2814 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2815 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2816 a8083063 Iustin Pop
2817 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2818 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2819 2cc6781a Iustin Pop
          file_name)
2820 a8083063 Iustin Pop
2821 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2822 12bce260 Michael Hanselmann
2823 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2824 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2825 9a914f7a René Nussbaumer
2826 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2827 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2828 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2829 9a914f7a René Nussbaumer
2830 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2831 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2832 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2833 a8083063 Iustin Pop
2834 386b57af Iustin Pop
2835 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2836 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2837 b2f29800 René Nussbaumer

2838 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2839 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2840 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2841 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2842 b2f29800 René Nussbaumer

2843 b2f29800 René Nussbaumer
  @return: stdout
2844 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2845 b2f29800 René Nussbaumer

2846 b2f29800 René Nussbaumer
  """
2847 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2848 b2f29800 René Nussbaumer
2849 b2f29800 René Nussbaumer
  if result.failed:
2850 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2851 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2852 b2f29800 René Nussbaumer
2853 b2f29800 René Nussbaumer
  return result.stdout
2854 b2f29800 René Nussbaumer
2855 b2f29800 René Nussbaumer
2856 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2857 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2858 a8083063 Iustin Pop

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

2862 10c2650b Iustin Pop
  @type os_dir: str
2863 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2864 8e70b181 Iustin Pop
  @rtype: tuple
2865 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2866 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2867 a8083063 Iustin Pop

2868 a8083063 Iustin Pop
  """
2869 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2870 a8083063 Iustin Pop
2871 a8083063 Iustin Pop
  try:
2872 a8083063 Iustin Pop
    st = os.stat(api_file)
2873 a8083063 Iustin Pop
  except EnvironmentError, err:
2874 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2875 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2876 a8083063 Iustin Pop
2877 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2878 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2879 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2880 a8083063 Iustin Pop
2881 a8083063 Iustin Pop
  try:
2882 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2883 a8083063 Iustin Pop
  except EnvironmentError, err:
2884 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2885 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2886 a8083063 Iustin Pop
2887 a8083063 Iustin Pop
  try:
2888 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2889 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2890 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2891 255dcebd Iustin Pop
                   str(err))
2892 a8083063 Iustin Pop
2893 255dcebd Iustin Pop
  return True, api_versions
2894 a8083063 Iustin Pop
2895 386b57af Iustin Pop
2896 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2897 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2898 a8083063 Iustin Pop

2899 10c2650b Iustin Pop
  @type top_dirs: list
2900 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2901 10c2650b Iustin Pop
      search (if not given defaults to
2902 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2903 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2904 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2905 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2906 bad78e66 Iustin Pop
      search paths, where:
2907 255dcebd Iustin Pop
          - name is the (potential) OS name
2908 255dcebd Iustin Pop
          - path is the full path to the OS
2909 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2910 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2911 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2912 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2913 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2914 a8083063 Iustin Pop

2915 a8083063 Iustin Pop
  """
2916 7c3d51d4 Guido Trotter
  if top_dirs is None:
2917 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2918 a8083063 Iustin Pop
2919 a8083063 Iustin Pop
  result = []
2920 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2921 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2922 7c3d51d4 Guido Trotter
      try:
2923 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2924 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2925 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2926 7c3d51d4 Guido Trotter
        break
2927 7c3d51d4 Guido Trotter
      for name in f_names:
2928 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2929 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2930 255dcebd Iustin Pop
        if status:
2931 255dcebd Iustin Pop
          diagnose = ""
2932 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2933 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2934 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2935 255dcebd Iustin Pop
        else:
2936 255dcebd Iustin Pop
          diagnose = os_inst
2937 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2938 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2939 bad78e66 Iustin Pop
                       parameters, api_versions))
2940 a8083063 Iustin Pop
2941 c26a6bd2 Iustin Pop
  return result
2942 a8083063 Iustin Pop
2943 a8083063 Iustin Pop
2944 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2945 a8083063 Iustin Pop
  """Create an OS instance from disk.
2946 a8083063 Iustin Pop

2947 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2948 8e70b181 Iustin Pop
  valid OS name.
2949 a8083063 Iustin Pop

2950 8ee4dc80 Guido Trotter
  @type base_dir: string
2951 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2952 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2953 255dcebd Iustin Pop
  @rtype: tuple
2954 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2955 255dcebd Iustin Pop
      or error message
2956 7c3d51d4 Guido Trotter

2957 a8083063 Iustin Pop
  """
2958 56bcd3f4 Guido Trotter
  if base_dir is None:
2959 710f30ec Michael Hanselmann
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2960 c34c0cfd Iustin Pop
  else:
2961 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2962 f95c81bf Iustin Pop
2963 f95c81bf Iustin Pop
  if os_dir is None:
2964 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
2965 a8083063 Iustin Pop
2966 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2967 255dcebd Iustin Pop
  if not status:
2968 255dcebd Iustin Pop
    # push the error up
2969 255dcebd Iustin Pop
    return status, api_versions
2970 a8083063 Iustin Pop
2971 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2972 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2973 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2974 a8083063 Iustin Pop
2975 35007011 Iustin Pop
  # OS Files dictionary, we will populate it with the absolute path
2976 35007011 Iustin Pop
  # names; if the value is True, then it is a required file, otherwise
2977 35007011 Iustin Pop
  # an optional one
2978 35007011 Iustin Pop
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2979 a8083063 Iustin Pop
2980 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
2981 35007011 Iustin Pop
    os_files[constants.OS_VARIANTS_FILE] = False
2982 95075fba Guido Trotter
2983 c7d04a6b Iustin Pop
  if max(api_versions) >= constants.OS_API_V20:
2984 35007011 Iustin Pop
    os_files[constants.OS_PARAMETERS_FILE] = True
2985 c7d04a6b Iustin Pop
  else:
2986 c7d04a6b Iustin Pop
    del os_files[constants.OS_SCRIPT_VERIFY]
2987 c7d04a6b Iustin Pop
2988 35007011 Iustin Pop
  for (filename, required) in os_files.items():
2989 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
2990 a8083063 Iustin Pop
2991 a8083063 Iustin Pop
    try:
2992 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
2993 a8083063 Iustin Pop
    except EnvironmentError, err:
2994 35007011 Iustin Pop
      if err.errno == errno.ENOENT and not required:
2995 35007011 Iustin Pop
        del os_files[filename]
2996 35007011 Iustin Pop
        continue
2997 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
2998 eb93b673 Guido Trotter
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2999 a8083063 Iustin Pop
3000 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
3001 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
3002 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
3003 255dcebd Iustin Pop
3004 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
3005 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
3006 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
3007 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
3008 0757c107 Guido Trotter
3009 845da3e8 Iustin Pop
  variants = []
3010 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
3011 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
3012 95075fba Guido Trotter
    try:
3013 5a7cb9d3 Iustin Pop
      variants = \
3014 5a7cb9d3 Iustin Pop
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
3015 95075fba Guido Trotter
    except EnvironmentError, err:
3016 35007011 Iustin Pop
      # we accept missing files, but not other errors
3017 35007011 Iustin Pop
      if err.errno != errno.ENOENT:
3018 35007011 Iustin Pop
        return False, ("Error while reading the OS variants file at %s: %s" %
3019 eb93b673 Guido Trotter
                       (variants_file, utils.ErrnoOrStr(err)))
3020 0757c107 Guido Trotter
3021 c7d04a6b Iustin Pop
  parameters = []
3022 c7d04a6b Iustin Pop
  if constants.OS_PARAMETERS_FILE in os_files:
3023 c7d04a6b Iustin Pop
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
3024 c7d04a6b Iustin Pop
    try:
3025 c7d04a6b Iustin Pop
      parameters = utils.ReadFile(parameters_file).splitlines()
3026 c7d04a6b Iustin Pop
    except EnvironmentError, err:
3027 c7d04a6b Iustin Pop
      return False, ("Error while reading the OS parameters file at %s: %s" %
3028 eb93b673 Guido Trotter
                     (parameters_file, utils.ErrnoOrStr(err)))
3029 c7d04a6b Iustin Pop
    parameters = [v.split(None, 1) for v in parameters]
3030 c7d04a6b Iustin Pop
3031 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
3032 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
3033 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
3034 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
3035 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
3036 40684c3a Iustin Pop
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
3037 40684c3a Iustin Pop
                                                 None),
3038 95075fba Guido Trotter
                      supported_variants=variants,
3039 c7d04a6b Iustin Pop
                      supported_parameters=parameters,
3040 255dcebd Iustin Pop
                      api_versions=api_versions)
3041 255dcebd Iustin Pop
  return True, os_obj
3042 255dcebd Iustin Pop
3043 255dcebd Iustin Pop
3044 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
3045 255dcebd Iustin Pop
  """Create an OS instance from disk.
3046 255dcebd Iustin Pop

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

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

3054 255dcebd Iustin Pop
  @type base_dir: string
3055 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
3056 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
3057 255dcebd Iustin Pop
  @rtype: L{objects.OS}
3058 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
3059 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
3060 255dcebd Iustin Pop

3061 255dcebd Iustin Pop
  """
3062 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
3063 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
3064 255dcebd Iustin Pop
3065 255dcebd Iustin Pop
  if not status:
3066 255dcebd Iustin Pop
    _Fail(payload)
3067 a8083063 Iustin Pop
3068 255dcebd Iustin Pop
  return payload
3069 a8083063 Iustin Pop
3070 a8083063 Iustin Pop
3071 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
3072 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
3073 2266edb2 Guido Trotter

3074 a025e535 Vitaly Kuznetsov
  @type os_name: str
3075 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
3076 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
3077 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
3078 1bdcbbab Iustin Pop
  @type os_params: dict
3079 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
3080 2266edb2 Guido Trotter
  @type debug: integer
3081 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
3082 2266edb2 Guido Trotter
  @rtype: dict
3083 2266edb2 Guido Trotter
  @return: dict of environment variables
3084 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
3085 10c2650b Iustin Pop
      cannot be found
3086 2266edb2 Guido Trotter

3087 2266edb2 Guido Trotter
  """
3088 2266edb2 Guido Trotter
  result = {}
3089 099c52ad Iustin Pop
  api_version = \
3090 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
3091 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
3092 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
3093 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
3094 efaa9b06 Iustin Pop
3095 efaa9b06 Iustin Pop
  # OS variants
3096 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
3097 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
3098 870dc44c Iustin Pop
    if not variant:
3099 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
3100 35007011 Iustin Pop
  else:
3101 35007011 Iustin Pop
    variant = ""
3102 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
3103 efaa9b06 Iustin Pop
3104 1bdcbbab Iustin Pop
  # OS params
3105 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
3106 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
3107 1bdcbbab Iustin Pop
3108 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
3109 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
3110 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
3111 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
3112 9a6ade06 Iustin Pop
3113 efaa9b06 Iustin Pop
  return result
3114 efaa9b06 Iustin Pop
3115 efaa9b06 Iustin Pop
3116 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
3117 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
3118 efaa9b06 Iustin Pop

3119 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
3120 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
3121 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
3122 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
3123 efaa9b06 Iustin Pop
  @type debug: integer
3124 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
3125 efaa9b06 Iustin Pop
  @rtype: dict
3126 efaa9b06 Iustin Pop
  @return: dict of environment variables
3127 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
3128 efaa9b06 Iustin Pop
      cannot be found
3129 efaa9b06 Iustin Pop

3130 efaa9b06 Iustin Pop
  """
3131 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
3132 efaa9b06 Iustin Pop
3133 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
3134 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
3135 f2165b8a Iustin Pop
3136 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
3137 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
3138 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
3139 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
3140 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
3141 efaa9b06 Iustin Pop
3142 efaa9b06 Iustin Pop
  # Disks
3143 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
3144 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3145 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
3146 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
3147 8a348b15 Christos Stavrakakis
    result["DISK_%d_UUID" % idx] = disk.uuid
3148 8a348b15 Christos Stavrakakis
    if disk.name:
3149 8a348b15 Christos Stavrakakis
      result["DISK_%d_NAME" % idx] = disk.name
3150 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
3151 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
3152 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
3153 cd3b4ff4 Helga Velroyen
    if disk.dev_type in constants.DTS_BLOCK:
3154 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
3155 a09639d1 Santi Raffa
    elif disk.dev_type in constants.DTS_FILEBASED:
3156 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
3157 a57e502a Thomas Thrainer
        "file:%s" % disk.logical_id[0]
3158 efaa9b06 Iustin Pop
3159 efaa9b06 Iustin Pop
  # NICs
3160 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
3161 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
3162 8a348b15 Christos Stavrakakis
    result["NIC_%d_UUID" % idx] = nic.uuid
3163 8a348b15 Christos Stavrakakis
    if nic.name:
3164 8a348b15 Christos Stavrakakis
      result["NIC_%d_NAME" % idx] = nic.name
3165 2266edb2 Guido Trotter
    if nic.ip:
3166 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
3167 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
3168 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
3169 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
3170 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
3171 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
3172 d89168ff Guido Trotter
    if nic.netinfo:
3173 d89168ff Guido Trotter
      nobj = objects.Network.FromDict(nic.netinfo)
3174 d89168ff Guido Trotter
      result.update(nobj.HooksDict("NIC_%d_" % idx))
3175 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
3176 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
3177 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
3178 2266edb2 Guido Trotter
3179 efaa9b06 Iustin Pop
  # HV/BE params
3180 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
3181 67fc3042 Iustin Pop
    for key, value in source.items():
3182 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
3183 67fc3042 Iustin Pop
3184 2266edb2 Guido Trotter
  return result
3185 a8083063 Iustin Pop
3186 f2e07bb4 Michael Hanselmann
3187 b954f097 Constantinos Venetsanopoulos
def DiagnoseExtStorage(top_dirs=None):
3188 b954f097 Constantinos Venetsanopoulos
  """Compute the validity for all ExtStorage Providers.
3189 b954f097 Constantinos Venetsanopoulos

3190 b954f097 Constantinos Venetsanopoulos
  @type top_dirs: list
3191 b954f097 Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
3192 b954f097 Constantinos Venetsanopoulos
      search (if not given defaults to
3193 b954f097 Constantinos Venetsanopoulos
      L{pathutils.ES_SEARCH_PATH})
3194 b954f097 Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
3195 b954f097 Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
3196 b954f097 Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
3197 b954f097 Constantinos Venetsanopoulos
      search paths, where:
3198 b954f097 Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
3199 b954f097 Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
3200 b954f097 Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
3201 b954f097 Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
3202 b954f097 Constantinos Venetsanopoulos
            otherwise empty
3203 b954f097 Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
3204 b954f097 Constantinos Venetsanopoulos

3205 b954f097 Constantinos Venetsanopoulos
  """
3206 b954f097 Constantinos Venetsanopoulos
  if top_dirs is None:
3207 b954f097 Constantinos Venetsanopoulos
    top_dirs = pathutils.ES_SEARCH_PATH
3208 b954f097 Constantinos Venetsanopoulos
3209 b954f097 Constantinos Venetsanopoulos
  result = []
3210 b954f097 Constantinos Venetsanopoulos
  for dir_name in top_dirs:
3211 b954f097 Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
3212 b954f097 Constantinos Venetsanopoulos
      try:
3213 b954f097 Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
3214 b954f097 Constantinos Venetsanopoulos
      except EnvironmentError, err:
3215 b954f097 Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
3216 b954f097 Constantinos Venetsanopoulos
                          dir_name, err)
3217 b954f097 Constantinos Venetsanopoulos
        break
3218 b954f097 Constantinos Venetsanopoulos
      for name in f_names:
3219 b954f097 Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
3220 b954f097 Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
3221 b954f097 Constantinos Venetsanopoulos
        if status:
3222 b954f097 Constantinos Venetsanopoulos
          diagnose = ""
3223 b954f097 Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
3224 b954f097 Constantinos Venetsanopoulos
        else:
3225 b954f097 Constantinos Venetsanopoulos
          diagnose = es_inst
3226 b954f097 Constantinos Venetsanopoulos
          parameters = []
3227 b954f097 Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
3228 b954f097 Constantinos Venetsanopoulos
3229 b954f097 Constantinos Venetsanopoulos
  return result
3230 b954f097 Constantinos Venetsanopoulos
3231 b954f097 Constantinos Venetsanopoulos
3232 be9150ea Bernardo Dal Seno
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
3233 594609c0 Iustin Pop
  """Grow a stack of block devices.
3234 594609c0 Iustin Pop

3235 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
3236 10c2650b Iustin Pop
  first ones to resize.
3237 594609c0 Iustin Pop

3238 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
3239 10c2650b Iustin Pop
  @param disk: the disk to be grown
3240 a59faf4b Iustin Pop
  @type amount: integer
3241 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
3242 a59faf4b Iustin Pop
  @type dryrun: boolean
3243 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
3244 a59faf4b Iustin Pop
      only, without actually increasing the size
3245 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
3246 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
3247 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
3248 10c2650b Iustin Pop
  @rtype: (status, result)
3249 be9150ea Bernardo Dal Seno
  @type excl_stor: boolean
3250 be9150ea Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
3251 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
3252 a59faf4b Iustin Pop
      the errors message if status is False
3253 594609c0 Iustin Pop

3254 594609c0 Iustin Pop
  """
3255 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
3256 594609c0 Iustin Pop
  if r_dev is None:
3257 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
3258 594609c0 Iustin Pop
3259 594609c0 Iustin Pop
  try:
3260 be9150ea Bernardo Dal Seno
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
3261 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
3262 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
3263 594609c0 Iustin Pop
3264 594609c0 Iustin Pop
3265 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
3266 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
3267 a8083063 Iustin Pop

3268 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
3269 a8083063 Iustin Pop
  just for the leaf lvm backend device.
3270 a8083063 Iustin Pop

3271 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
3272 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
3273 e9e9263d Guido Trotter
  @rtype: string
3274 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
3275 a8083063 Iustin Pop

3276 098c0958 Michael Hanselmann
  """
3277 cd3b4ff4 Helga Velroyen
  if disk.dev_type == constants.DT_DRBD8:
3278 433c63aa Iustin Pop
    if not disk.children:
3279 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
3280 433c63aa Iustin Pop
            disk.unique_id)
3281 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
3282 cd3b4ff4 Helga Velroyen
  elif disk.dev_type == constants.DT_PLAIN:
3283 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
3284 a8083063 Iustin Pop
    if r_dev is not None:
3285 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
3286 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
3287 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
3288 a8083063 Iustin Pop
    else:
3289 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
3290 a8083063 Iustin Pop
  else:
3291 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
3292 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
3293 a8083063 Iustin Pop
3294 a8083063 Iustin Pop
3295 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
3296 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
3297 48e175a2 Iustin Pop

3298 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
3299 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
3300 48e175a2 Iustin Pop
  for example after renames.
3301 48e175a2 Iustin Pop

3302 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
3303 48e175a2 Iustin Pop
  @param disk: the disk to be grown
3304 48e175a2 Iustin Pop
  @type info: string
3305 48e175a2 Iustin Pop
  @param info: new 'info' metadata
3306 48e175a2 Iustin Pop
  @rtype: (status, result)
3307 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
3308 48e175a2 Iustin Pop
      the errors message if status is False
3309 48e175a2 Iustin Pop

3310 48e175a2 Iustin Pop
  """
3311 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
3312 48e175a2 Iustin Pop
  if r_dev is None:
3313 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
3314 48e175a2 Iustin Pop
3315 48e175a2 Iustin Pop
  try:
3316 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
3317 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
3318 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
3319 48e175a2 Iustin Pop
3320 48e175a2 Iustin Pop
3321 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
3322 a8083063 Iustin Pop
  """Write out the export configuration information.
3323 a8083063 Iustin Pop

3324 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
3325 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
3326 10c2650b Iustin Pop
      saving configuration
3327 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
3328 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
3329 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
3330 a8083063 Iustin Pop

3331 c26a6bd2 Iustin Pop
  @rtype: None
3332 a8083063 Iustin Pop

3333 098c0958 Michael Hanselmann
  """
3334 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3335 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3336 a8083063 Iustin Pop
3337 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
3338 a8083063 Iustin Pop
3339 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
3340 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
3341 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3342 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3343 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
3344 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
3345 a8083063 Iustin Pop
3346 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
3347 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
3348 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3349 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
3350 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
3351 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
3352 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3353 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
3354 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
3355 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3356 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
3357 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3358 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3359 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3360 66f93869 Manuel Franceschini
3361 95268cc3 Iustin Pop
  nic_total = 0
3362 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
3363 95268cc3 Iustin Pop
    nic_total += 1
3364 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
3365 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
3366 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3367 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3368 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
3369 0f68f7fa Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_name" % nic_count,
3370 0f68f7fa Dimitris Aragiorgis
               "%s" % nic.name)
3371 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
3372 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3373 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
3374 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
3375 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3376 a8083063 Iustin Pop
3377 726d7d68 Iustin Pop
  disk_total = 0
3378 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
3379 19d7f90a Guido Trotter
    if disk:
3380 726d7d68 Iustin Pop
      disk_total += 1
3381 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3382 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
3383 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3384 a57e502a Thomas Thrainer
                 ("%s" % disk.logical_id[1]))
3385 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3386 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
3387 0f68f7fa Dimitris Aragiorgis
      config.set(constants.INISECT_INS, "disk%d_name" % disk_count,
3388 0f68f7fa Dimitris Aragiorgis
                 "%s" % disk.name)
3389 d0c8c01d Iustin Pop
3390 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3391 a8083063 Iustin Pop
3392 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
3393 3c8954ad Iustin Pop
3394 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
3395 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
3396 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
3397 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
3398 3c8954ad Iustin Pop
3399 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
3400 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
3401 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
3402 3c8954ad Iustin Pop
3403 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
3404 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
3405 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
3406 535b49cb Iustin Pop
3407 6bce7ba2 Santi Raffa
  config.add_section(constants.INISECT_OSP_PRIVATE)
3408 6bce7ba2 Santi Raffa
  for name, value in instance.osparams_private.items():
3409 6bce7ba2 Santi Raffa
    config.set(constants.INISECT_OSP_PRIVATE, name, str(value.Get()))
3410 6bce7ba2 Santi Raffa
3411 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3412 726d7d68 Iustin Pop
                  data=config.Dumps())
3413 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
3414 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
3415 a8083063 Iustin Pop
3416 a8083063 Iustin Pop
3417 a8083063 Iustin Pop
def ExportInfo(dest):
3418 a8083063 Iustin Pop
  """Get export configuration information.
3419 a8083063 Iustin Pop

3420 10c2650b Iustin Pop
  @type dest: str
3421 10c2650b Iustin Pop
  @param dest: directory containing the export
3422 a8083063 Iustin Pop

3423 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
3424 10c2650b Iustin Pop
  @return: a serializable config file containing the
3425 10c2650b Iustin Pop
      export info
3426 a8083063 Iustin Pop

3427 a8083063 Iustin Pop
  """
3428 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3429 a8083063 Iustin Pop
3430 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
3431 a8083063 Iustin Pop
  config.read(cff)
3432 a8083063 Iustin Pop
3433 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
3434 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
3435 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
3436 a8083063 Iustin Pop
3437 c26a6bd2 Iustin Pop
  return config.Dumps()
3438 a8083063 Iustin Pop
3439 a8083063 Iustin Pop
3440 a8083063 Iustin Pop
def ListExports():
3441 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
3442 098c0958 Michael Hanselmann

3443 10c2650b Iustin Pop
  @rtype: list
3444 10c2650b Iustin Pop
  @return: list of the exports
3445 10c2650b Iustin Pop

3446 a8083063 Iustin Pop
  """
3447 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
3448 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3449 a8083063 Iustin Pop
  else:
3450 afdc3985 Iustin Pop
    _Fail("No exports directory")
3451 a8083063 Iustin Pop
3452 a8083063 Iustin Pop
3453 a8083063 Iustin Pop
def RemoveExport(export):
3454 a8083063 Iustin Pop
  """Remove an existing export from the node.
3455 a8083063 Iustin Pop

3456 10c2650b Iustin Pop
  @type export: str
3457 10c2650b Iustin Pop
  @param export: the name of the export to remove
3458 c26a6bd2 Iustin Pop
  @rtype: None
3459 a8083063 Iustin Pop

3460 098c0958 Michael Hanselmann
  """
3461 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3462 a8083063 Iustin Pop
3463 35fbcd11 Iustin Pop
  try:
3464 35fbcd11 Iustin Pop
    shutil.rmtree(target)
3465 35fbcd11 Iustin Pop
  except EnvironmentError, err:
3466 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
3467 a8083063 Iustin Pop
3468 a8083063 Iustin Pop
3469 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
3470 f3e513ad Iustin Pop
  """Rename a list of block devices.
3471 f3e513ad Iustin Pop

3472 10c2650b Iustin Pop
  @type devlist: list of tuples
3473 a57e502a Thomas Thrainer
  @param devlist: list of tuples of the form  (disk, new_unique_id); disk is
3474 a57e502a Thomas Thrainer
      an L{objects.Disk} object describing the current disk, and new
3475 a57e502a Thomas Thrainer
      unique_id is the name we rename it to
3476 10c2650b Iustin Pop
  @rtype: boolean
3477 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
3478 f3e513ad Iustin Pop

3479 f3e513ad Iustin Pop
  """
3480 6b5e3f70 Iustin Pop
  msgs = []
3481 f3e513ad Iustin Pop
  result = True
3482 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
3483 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
3484 f3e513ad Iustin Pop
    if dev is None:
3485 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
3486 f3e513ad Iustin Pop
      result = False
3487 f3e513ad Iustin Pop
      continue
3488 f3e513ad Iustin Pop
    try:
3489 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
3490 f3e513ad Iustin Pop
      dev.Rename(unique_id)
3491 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
3492 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
3493 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
3494 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
3495 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3496 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
3497 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
3498 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
3499 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
3500 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
3501 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
3502 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3503 f3e513ad Iustin Pop
      result = False
3504 afdc3985 Iustin Pop
  if not result:
3505 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
3506 f3e513ad Iustin Pop
3507 f3e513ad Iustin Pop
3508 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
3509 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
3510 778b75bb Manuel Franceschini

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

3515 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
3516 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
3517 d61cbe76 Iustin Pop

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

3520 778b75bb Manuel Franceschini
  """
3521 13a6c760 Helga Velroyen
  filestorage.CheckFileStoragePath(fs_dir)
3522 5e09a309 Michael Hanselmann
3523 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
3524 778b75bb Manuel Franceschini
3525 778b75bb Manuel Franceschini
3526 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
3527 778b75bb Manuel Franceschini
  """Create file storage directory.
3528 778b75bb Manuel Franceschini

3529 b1206984 Iustin Pop
  @type file_storage_dir: str
3530 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
3531 778b75bb Manuel Franceschini

3532 b1206984 Iustin Pop
  @rtype: tuple
3533 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
3534 b1206984 Iustin Pop
      creation was successful or not
3535 778b75bb Manuel Franceschini

3536 778b75bb Manuel Franceschini
  """
3537 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3538 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
3539 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
3540 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
3541 b2b8bcce Iustin Pop
            file_storage_dir)
3542 778b75bb Manuel Franceschini
  else:
3543 b2b8bcce Iustin Pop
    try:
3544 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
3545 b2b8bcce Iustin Pop
    except OSError, err:
3546 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
3547 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
3548 778b75bb Manuel Franceschini
3549 778b75bb Manuel Franceschini
3550 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
3551 778b75bb Manuel Franceschini
  """Remove file storage directory.
3552 778b75bb Manuel Franceschini

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

3555 10c2650b Iustin Pop
  @type file_storage_dir: str
3556 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
3557 10c2650b Iustin Pop
  @rtype: tuple (success,)
3558 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
3559 5bbd3f7f Michael Hanselmann
      whether the operation was successful
3560 778b75bb Manuel Franceschini

3561 778b75bb Manuel Franceschini
  """
3562 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3563 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
3564 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
3565 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
3566 b2b8bcce Iustin Pop
            file_storage_dir)
3567 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
3568 b2b8bcce Iustin Pop
    try:
3569 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
3570 b2b8bcce Iustin Pop
    except OSError, err:
3571 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
3572 b2b8bcce Iustin Pop
            file_storage_dir, err)
3573 b2b8bcce Iustin Pop
3574 778b75bb Manuel Franceschini
3575 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3576 778b75bb Manuel Franceschini
  """Rename the file storage directory.
3577 778b75bb Manuel Franceschini

3578 10c2650b Iustin Pop
  @type old_file_storage_dir: str
3579 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
3580 10c2650b Iustin Pop
  @type new_file_storage_dir: str
3581 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
3582 10c2650b Iustin Pop
  @rtype: tuple (success,)
3583 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
3584 10c2650b Iustin Pop
      whether the operation was successful
3585 778b75bb Manuel Franceschini

3586 778b75bb Manuel Franceschini
  """
3587 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3588 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3589 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
3590 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
3591 b2b8bcce Iustin Pop
      try:
3592 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
3593 b2b8bcce Iustin Pop
      except OSError, err:
3594 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
3595 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
3596 778b75bb Manuel Franceschini
    else:
3597 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
3598 b2b8bcce Iustin Pop
            old_file_storage_dir)
3599 b2b8bcce Iustin Pop
  else:
3600 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
3601 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3602 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
3603 778b75bb Manuel Franceschini
3604 778b75bb Manuel Franceschini
3605 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
3606 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
3607 ca52cdeb Michael Hanselmann

3608 10c2650b Iustin Pop
  @type file_name: str
3609 10c2650b Iustin Pop
  @param file_name: the file name we should check
3610 c8457ce7 Iustin Pop
  @rtype: None
3611 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
3612 10c2650b Iustin Pop

3613 ca52cdeb Michael Hanselmann
  """
3614 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3615 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
3616 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3617 dc31eae3 Michael Hanselmann
3618 dc31eae3 Michael Hanselmann
3619 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
3620 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
3621 dc31eae3 Michael Hanselmann

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

3625 10c2650b Iustin Pop
  @type file_name: str
3626 10c2650b Iustin Pop
  @param file_name: the job file name
3627 10c2650b Iustin Pop
  @type content: str
3628 10c2650b Iustin Pop
  @param content: the new job contents
3629 10c2650b Iustin Pop
  @rtype: boolean
3630 10c2650b Iustin Pop
  @return: the success of the operation
3631 10c2650b Iustin Pop

3632 dc31eae3 Michael Hanselmann
  """
3633 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
3634 cffbbae7 Michael Hanselmann
3635 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
3636 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
3637 ca52cdeb Michael Hanselmann
3638 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
3639 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3640 fe05a931 Michele Tartara
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3641 ca52cdeb Michael Hanselmann
3642 ca52cdeb Michael Hanselmann
3643 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
3644 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
3645 af5ebcb1 Michael Hanselmann

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

3648 10c2650b Iustin Pop
  @type old: str
3649 10c2650b Iustin Pop
  @param old: the old (actual) file name
3650 10c2650b Iustin Pop
  @type new: str
3651 10c2650b Iustin Pop
  @param new: the desired file name
3652 c8457ce7 Iustin Pop
  @rtype: tuple
3653 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
3654 10c2650b Iustin Pop

3655 af5ebcb1 Michael Hanselmann
  """
3656 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
3657 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
3658 cffbbae7 Michael Hanselmann
3659 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
3660 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
3661 af5ebcb1 Michael Hanselmann
3662 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
3663 8e5a705d René Nussbaumer
3664 fe05a931 Michele Tartara
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3665 fe05a931 Michele Tartara
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3666 af5ebcb1 Michael Hanselmann
3667 af5ebcb1 Michael Hanselmann
3668 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
3669 d61cbe76 Iustin Pop
  """Closes the given block devices.
3670 d61cbe76 Iustin Pop

3671 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
3672 10c2650b Iustin Pop
  DRBD).
3673 10c2650b Iustin Pop

3674 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
3675 b2e7666a Iustin Pop
      of this instance will be removed
3676 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
3677 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
3678 10c2650b Iustin Pop
  @rtype: tuple (success, message)
3679 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
3680 10c2650b Iustin Pop
      indicates the succes of the operation, and message
3681 10c2650b Iustin Pop
      which will contain the error details in case we
3682 10c2650b Iustin Pop
      failed
3683 d61cbe76 Iustin Pop

3684 d61cbe76 Iustin Pop
  """
3685 d61cbe76 Iustin Pop
  bdevs = []
3686 d61cbe76 Iustin Pop
  for cf in disks:
3687 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
3688 d61cbe76 Iustin Pop
    if rd is None:
3689 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
3690 d61cbe76 Iustin Pop
    bdevs.append(rd)
3691 d61cbe76 Iustin Pop
3692 d61cbe76 Iustin Pop
  msg = []
3693 d61cbe76 Iustin Pop
  for rd in bdevs:
3694 d61cbe76 Iustin Pop
    try:
3695 d61cbe76 Iustin Pop
      rd.Close()
3696 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
3697 d61cbe76 Iustin Pop
      msg.append(str(err))
3698 d61cbe76 Iustin Pop
  if msg:
3699 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3700 d61cbe76 Iustin Pop
  else:
3701 b2e7666a Iustin Pop
    if instance_name:
3702 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
3703 d61cbe76 Iustin Pop
3704 d61cbe76 Iustin Pop
3705 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
3706 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
3707 6217e295 Iustin Pop

3708 6217e295 Iustin Pop
  @type hvname: string
3709 6217e295 Iustin Pop
  @param hvname: the hypervisor name
3710 6217e295 Iustin Pop
  @type hvparams: dict
3711 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
3712 c26a6bd2 Iustin Pop
  @rtype: None
3713 6217e295 Iustin Pop

3714 6217e295 Iustin Pop
  """
3715 6217e295 Iustin Pop
  try:
3716 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
3717 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
3718 6217e295 Iustin Pop
  except errors.HypervisorError, err:
3719 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
3720 6217e295 Iustin Pop
3721 6217e295 Iustin Pop
3722 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
3723 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
3724 acd9ff9e Iustin Pop

3725 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
3726 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
3727 acd9ff9e Iustin Pop
  @type parameters: list
3728 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
3729 acd9ff9e Iustin Pop

3730 acd9ff9e Iustin Pop
  """
3731 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
3732 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
3733 acd9ff9e Iustin Pop
  if delta:
3734 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
3735 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3736 acd9ff9e Iustin Pop
3737 acd9ff9e Iustin Pop
3738 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
3739 3cf06dd4 Jose A. Lopes
  """Validate the given OS parameters.
3740 acd9ff9e Iustin Pop

3741 acd9ff9e Iustin Pop
  @type required: boolean
3742 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3743 acd9ff9e Iustin Pop
      failure or not
3744 acd9ff9e Iustin Pop
  @type osname: string
3745 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3746 acd9ff9e Iustin Pop
  @type checks: list
3747 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3748 acd9ff9e Iustin Pop
  @type osparams: dict
3749 1a182390 Santi Raffa
  @param osparams: dictionary with OS parameters, some of which may be
3750 1a182390 Santi Raffa
                   private.
3751 acd9ff9e Iustin Pop
  @rtype: boolean
3752 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3753 acd9ff9e Iustin Pop
      found and L{required} was false
3754 acd9ff9e Iustin Pop

3755 acd9ff9e Iustin Pop
  """
3756 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3757 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3758 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3759 acd9ff9e Iustin Pop
3760 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3761 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3762 acd9ff9e Iustin Pop
3763 acd9ff9e Iustin Pop
  if not status:
3764 acd9ff9e Iustin Pop
    if required:
3765 acd9ff9e Iustin Pop
      _Fail(tbv)
3766 acd9ff9e Iustin Pop
    else:
3767 acd9ff9e Iustin Pop
      return False
3768 acd9ff9e Iustin Pop
3769 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3770 72db3fd7 Iustin Pop
    return True
3771 72db3fd7 Iustin Pop
3772 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3773 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3774 acd9ff9e Iustin Pop
3775 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3776 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3777 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3778 acd9ff9e Iustin Pop
  if result.failed:
3779 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3780 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3781 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3782 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3783 acd9ff9e Iustin Pop
3784 acd9ff9e Iustin Pop
  return True
3785 acd9ff9e Iustin Pop
3786 acd9ff9e Iustin Pop
3787 56aa9fd5 Iustin Pop
def DemoteFromMC():
3788 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3789 56aa9fd5 Iustin Pop

3790 56aa9fd5 Iustin Pop
  """
3791 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3792 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3793 56aa9fd5 Iustin Pop
  if master == myself:
3794 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3795 f154a7a3 Michael Hanselmann
3796 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3797 f154a7a3 Michael Hanselmann
  if not result.failed:
3798 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3799 f154a7a3 Michael Hanselmann
3800 56aa9fd5 Iustin Pop
  try:
3801 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3802 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3803 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3804 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3805 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3806 f154a7a3 Michael Hanselmann
3807 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3808 56aa9fd5 Iustin Pop
3809 56aa9fd5 Iustin Pop
3810 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3811 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3812 f942a838 Michael Hanselmann

3813 f942a838 Michael Hanselmann
  """
3814 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3815 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3816 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3817 f942a838 Michael Hanselmann
3818 f942a838 Michael Hanselmann
3819 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3820 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3821 f942a838 Michael Hanselmann

3822 f942a838 Michael Hanselmann
  @type validity: int
3823 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3824 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3825 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3826 f942a838 Michael Hanselmann

3827 f942a838 Michael Hanselmann
  """
3828 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3829 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3830 ab4b1cf2 Helga Velroyen
                                     min(validity, _MAX_SSL_CERT_VALIDITY), 1)
3831 f942a838 Michael Hanselmann
3832 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3833 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3834 f942a838 Michael Hanselmann
  try:
3835 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3836 f942a838 Michael Hanselmann
    assert len(name) > 5
3837 f942a838 Michael Hanselmann
3838 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3839 f942a838 Michael Hanselmann
3840 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3841 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3842 f942a838 Michael Hanselmann
3843 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3844 f942a838 Michael Hanselmann
    return (name, cert_pem)
3845 f942a838 Michael Hanselmann
  except Exception:
3846 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3847 f942a838 Michael Hanselmann
    raise
3848 f942a838 Michael Hanselmann
3849 f942a838 Michael Hanselmann
3850 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3851 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3852 f942a838 Michael Hanselmann

3853 f942a838 Michael Hanselmann
  @type name: string
3854 f942a838 Michael Hanselmann
  @param name: Certificate name
3855 f942a838 Michael Hanselmann

3856 f942a838 Michael Hanselmann
  """
3857 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3858 f942a838 Michael Hanselmann
3859 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3860 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3861 f942a838 Michael Hanselmann
3862 f942a838 Michael Hanselmann
  try:
3863 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3864 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3865 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3866 f942a838 Michael Hanselmann
          cert_dir, err)
3867 f942a838 Michael Hanselmann
3868 f942a838 Michael Hanselmann
3869 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3870 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3871 1651d116 Michael Hanselmann

3872 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3873 1651d116 Michael Hanselmann
  @param instance: The instance object
3874 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3875 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3876 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3877 1651d116 Michael Hanselmann

3878 1651d116 Michael Hanselmann
  """
3879 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3880 1651d116 Michael Hanselmann
3881 1651d116 Michael Hanselmann
  env = None
3882 1651d116 Michael Hanselmann
  prefix = None
3883 1651d116 Michael Hanselmann
  suffix = None
3884 2ad5550d Michael Hanselmann
  exp_size = None
3885 1651d116 Michael Hanselmann
3886 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
3887 1651d116 Michael Hanselmann
    (filename, ) = ieargs
3888 1651d116 Michael Hanselmann
3889 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
3890 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
3891 1651d116 Michael Hanselmann
3892 748c9884 René Nussbaumer
    real_filename = os.path.realpath(filename)
3893 748c9884 René Nussbaumer
    directory = os.path.dirname(real_filename)
3894 1651d116 Michael Hanselmann
3895 710f30ec Michael Hanselmann
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3896 748c9884 René Nussbaumer
      _Fail("File '%s' is not under exports directory '%s': %s",
3897 710f30ec Michael Hanselmann
            filename, pathutils.EXPORT_DIR, real_filename)
3898 1651d116 Michael Hanselmann
3899 1651d116 Michael Hanselmann
    # Create directory
3900 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
3901 1651d116 Michael Hanselmann
3902 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
3903 1651d116 Michael Hanselmann
3904 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3905 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
3906 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3907 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
3908 1651d116 Michael Hanselmann
3909 2ad5550d Michael Hanselmann
      # Retrieve file size
3910 2ad5550d Michael Hanselmann
      try:
3911 2ad5550d Michael Hanselmann
        st = os.stat(filename)
3912 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
3913 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
3914 2ad5550d Michael Hanselmann
      else:
3915 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
3916 2ad5550d Michael Hanselmann
3917 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
3918 1651d116 Michael Hanselmann
    (disk, ) = ieargs
3919 1651d116 Michael Hanselmann
3920 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
3921 1651d116 Michael Hanselmann
3922 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3923 a986a581 Thomas Thrainer
      # we use nocreat to fail if the device is not already there or we pass a
3924 a986a581 Thomas Thrainer
      # wrong path; we use notrunc to no attempt truncate on an LV device
3925 a986a581 Thomas Thrainer
      suffix = utils.BuildShellCmd("| dd of=%s conv=nocreat,notrunc bs=%s",
3926 a986a581 Thomas Thrainer
                                   real_disk.dev_path,
3927 a986a581 Thomas Thrainer
                                   str(1024 * 1024)) # 1 MB
3928 1651d116 Michael Hanselmann
3929 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3930 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
3931 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3932 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
3933 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
3934 1651d116 Michael Hanselmann
                                   str(disk.size))
3935 2ad5550d Michael Hanselmann
      exp_size = disk.size
3936 1651d116 Michael Hanselmann
3937 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
3938 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
3939 1651d116 Michael Hanselmann
3940 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
3941 1651d116 Michael Hanselmann
3942 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
3943 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
3944 1651d116 Michael Hanselmann
3945 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3946 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3947 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
3948 1651d116 Michael Hanselmann
      script = inst_os.import_script
3949 1651d116 Michael Hanselmann
3950 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3951 0c3d9c7c Thomas Thrainer
      real_disk = _OpenRealBD(disk)
3952 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
3953 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
3954 1651d116 Michael Hanselmann
      script = inst_os.export_script
3955 1651d116 Michael Hanselmann
3956 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
3957 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3958 1651d116 Michael Hanselmann
3959 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
3960 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
3961 1651d116 Michael Hanselmann
3962 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
3963 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
3964 1651d116 Michael Hanselmann
3965 2ad5550d Michael Hanselmann
    # Let script predict size
3966 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
3967 2ad5550d Michael Hanselmann
3968 1651d116 Michael Hanselmann
  else:
3969 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3970 1651d116 Michael Hanselmann
3971 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
3972 1651d116 Michael Hanselmann
3973 1651d116 Michael Hanselmann
3974 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
3975 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
3976 1651d116 Michael Hanselmann

3977 1651d116 Michael Hanselmann
  """
3978 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3979 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3980 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3981 1651d116 Michael Hanselmann
3982 1651d116 Michael Hanselmann
3983 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3984 6613661a Iustin Pop
                            ieio, ieioargs):
3985 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3986 1651d116 Michael Hanselmann

3987 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3988 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3989 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3990 1651d116 Michael Hanselmann
  @type host: string
3991 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3992 1651d116 Michael Hanselmann
  @type port: int
3993 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3994 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3995 1651d116 Michael Hanselmann
  @param instance: Instance object
3996 6613661a Iustin Pop
  @type component: string
3997 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3998 6613661a Iustin Pop
      e.g. 'disk/0'
3999 1651d116 Michael Hanselmann
  @param ieio: Input/output type
4000 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
4001 1651d116 Michael Hanselmann

4002 1651d116 Michael Hanselmann
  """
4003 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
4004 1651d116 Michael Hanselmann
    prefix = "import"
4005 1651d116 Michael Hanselmann
4006 1651d116 Michael Hanselmann
    if not (host is None and port is None):
4007 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
4008 1651d116 Michael Hanselmann
4009 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
4010 1651d116 Michael Hanselmann
    prefix = "export"
4011 1651d116 Michael Hanselmann
4012 1651d116 Michael Hanselmann
    if host is None or port is None:
4013 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
4014 1651d116 Michael Hanselmann
4015 1651d116 Michael Hanselmann
  else:
4016 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
4017 1651d116 Michael Hanselmann
4018 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
4019 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
4020 1651d116 Michael Hanselmann
4021 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
4022 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
4023 1651d116 Michael Hanselmann
4024 eb630f50 Michael Hanselmann
  if opts.key_name is None:
4025 1651d116 Michael Hanselmann
    # Use server.pem
4026 710f30ec Michael Hanselmann
    key_path = pathutils.NODED_CERT_FILE
4027 710f30ec Michael Hanselmann
    cert_path = pathutils.NODED_CERT_FILE
4028 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
4029 1651d116 Michael Hanselmann
  else:
4030 710f30ec Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
4031 eb630f50 Michael Hanselmann
                                                 opts.key_name)
4032 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
4033 1651d116 Michael Hanselmann
4034 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
4035 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
4036 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
4037 63bcea2a Michael Hanselmann
4038 6613661a Iustin Pop
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
4039 1651d116 Michael Hanselmann
  try:
4040 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
4041 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
4042 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
4043 1651d116 Michael Hanselmann
4044 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
4045 1651d116 Michael Hanselmann
      # Use server.pem
4046 710f30ec Michael Hanselmann
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
4047 eb630f50 Michael Hanselmann
    else:
4048 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
4049 63bcea2a Michael Hanselmann
4050 eb630f50 Michael Hanselmann
    # Write CA file
4051 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
4052 1651d116 Michael Hanselmann
4053 1651d116 Michael Hanselmann
    cmd = [
4054 710f30ec Michael Hanselmann
      pathutils.IMPORT_EXPORT_DAEMON,
4055 1651d116 Michael Hanselmann
      status_file, mode,
4056 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
4057 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
4058 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
4059 1651d116 Michael Hanselmann
      ]
4060 1651d116 Michael Hanselmann
4061 1651d116 Michael Hanselmann
    if host:
4062 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
4063 1651d116 Michael Hanselmann
4064 1651d116 Michael Hanselmann
    if port:
4065 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
4066 1651d116 Michael Hanselmann
4067 855d2fc7 Michael Hanselmann
    if opts.ipv6:
4068 855d2fc7 Michael Hanselmann
      cmd.append("--ipv6")
4069 855d2fc7 Michael Hanselmann
    else:
4070 855d2fc7 Michael Hanselmann
      cmd.append("--ipv4")
4071 855d2fc7 Michael Hanselmann
4072 a5310c2a Michael Hanselmann
    if opts.compress:
4073 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
4074 a5310c2a Michael Hanselmann
4075 af1d39b1 Michael Hanselmann
    if opts.magic:
4076 af1d39b1 Michael Hanselmann
      cmd.append("--magic=%s" % opts.magic)
4077 af1d39b1 Michael Hanselmann
4078 2ad5550d Michael Hanselmann
    if exp_size is not None:
4079 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
4080 2ad5550d Michael Hanselmann
4081 1651d116 Michael Hanselmann
    if cmd_prefix:
4082 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
4083 1651d116 Michael Hanselmann
4084 1651d116 Michael Hanselmann
    if cmd_suffix:
4085 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
4086 1651d116 Michael Hanselmann
4087 4478301b Michael Hanselmann
    if mode == constants.IEM_EXPORT:
4088 4478301b Michael Hanselmann
      # Retry connection a few times when connecting to remote peer
4089 4478301b Michael Hanselmann
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
4090 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
4091 4478301b Michael Hanselmann
    elif opts.connect_timeout is not None:
4092 4478301b Michael Hanselmann
      assert mode == constants.IEM_IMPORT
4093 4478301b Michael Hanselmann
      # Overall timeout for establishing connection while listening
4094 4478301b Michael Hanselmann
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
4095 4478301b Michael Hanselmann
4096 6aa7a354 Iustin Pop
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
4097 1651d116 Michael Hanselmann
4098 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
4099 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
4100 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
4101 1651d116 Michael Hanselmann
                      output=logfile)
4102 1651d116 Michael Hanselmann
4103 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
4104 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
4105 1651d116 Michael Hanselmann
4106 1651d116 Michael Hanselmann
  except Exception:
4107 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
4108 1651d116 Michael Hanselmann
    raise
4109 1651d116 Michael Hanselmann
4110 1651d116 Michael Hanselmann
4111 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
4112 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
4113 1651d116 Michael Hanselmann

4114 1651d116 Michael Hanselmann
  @type names: sequence
4115 1651d116 Michael Hanselmann
  @param names: List of names
4116 1651d116 Michael Hanselmann
  @rtype: List of dicts
4117 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
4118 1651d116 Michael Hanselmann
           status couldn't be read
4119 1651d116 Michael Hanselmann

4120 1651d116 Michael Hanselmann
  """
4121 1651d116 Michael Hanselmann
  result = []
4122 1651d116 Michael Hanselmann
4123 1651d116 Michael Hanselmann
  for name in names:
4124 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
4125 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
4126 1651d116 Michael Hanselmann
4127 1651d116 Michael Hanselmann
    try:
4128 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
4129 1651d116 Michael Hanselmann
    except EnvironmentError, err:
4130 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
4131 1651d116 Michael Hanselmann
        raise
4132 1651d116 Michael Hanselmann
      data = None
4133 1651d116 Michael Hanselmann
4134 1651d116 Michael Hanselmann
    if not data:
4135 1651d116 Michael Hanselmann
      result.append(None)
4136 1651d116 Michael Hanselmann
      continue
4137 1651d116 Michael Hanselmann
4138 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
4139 1651d116 Michael Hanselmann
4140 1651d116 Michael Hanselmann
  return result
4141 1651d116 Michael Hanselmann
4142 1651d116 Michael Hanselmann
4143 f81c4737 Michael Hanselmann
def AbortImportExport(name):
4144 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
4145 f81c4737 Michael Hanselmann

4146 f81c4737 Michael Hanselmann
  """
4147 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
4148 f81c4737 Michael Hanselmann
4149 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
4150 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
4151 f81c4737 Michael Hanselmann
4152 f81c4737 Michael Hanselmann
  if pid:
4153 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
4154 f81c4737 Michael Hanselmann
                 name, pid)
4155 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
4156 f81c4737 Michael Hanselmann
4157 f81c4737 Michael Hanselmann
4158 1651d116 Michael Hanselmann
def CleanupImportExport(name):
4159 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
4160 1651d116 Michael Hanselmann

4161 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
4162 1651d116 Michael Hanselmann
  whole status directory is removed.
4163 1651d116 Michael Hanselmann

4164 1651d116 Michael Hanselmann
  """
4165 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
4166 1651d116 Michael Hanselmann
4167 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
4168 1651d116 Michael Hanselmann
4169 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
4170 1651d116 Michael Hanselmann
4171 1651d116 Michael Hanselmann
  if pid:
4172 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
4173 1651d116 Michael Hanselmann
                 name, pid)
4174 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
4175 1651d116 Michael Hanselmann
4176 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
4177 1651d116 Michael Hanselmann
4178 1651d116 Michael Hanselmann
4179 0c3d9c7c Thomas Thrainer
def _FindDisks(disks):
4180 0c3d9c7c Thomas Thrainer
  """Finds attached L{BlockDev}s for the given disks.
4181 6b93ec9d Iustin Pop

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

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

4188 235a6b29 Thomas Thrainer
  """
4189 6b93ec9d Iustin Pop
  bdevs = []
4190 6b93ec9d Iustin Pop
4191 0c3d9c7c Thomas Thrainer
  for disk in disks:
4192 0c3d9c7c Thomas Thrainer
    rd = _RecursiveFindBD(disk)
4193 6b93ec9d Iustin Pop
    if rd is None:
4194 0c3d9c7c Thomas Thrainer
      _Fail("Can't find device %s", disk)
4195 6b93ec9d Iustin Pop
    bdevs.append(rd)
4196 5a533f8a Iustin Pop
  return bdevs
4197 6b93ec9d Iustin Pop
4198 6b93ec9d Iustin Pop
4199 0c3d9c7c Thomas Thrainer
def DrbdDisconnectNet(disks):
4200 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
4201 6b93ec9d Iustin Pop

4202 6b93ec9d Iustin Pop
  """
4203 0c3d9c7c Thomas Thrainer
  bdevs = _FindDisks(disks)
4204 6b93ec9d Iustin Pop
4205 6b93ec9d Iustin Pop
  # disconnect disks
4206 6b93ec9d Iustin Pop
  for rd in bdevs:
4207 6b93ec9d Iustin Pop
    try:
4208 6b93ec9d Iustin Pop
      rd.DisconnectNet()
4209 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
4210 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
4211 2cc6781a Iustin Pop
            err, exc=True)
4212 6b93ec9d Iustin Pop
4213 6b93ec9d Iustin Pop
4214 0c3d9c7c Thomas Thrainer
def DrbdAttachNet(disks, instance_name, multimaster):
4215 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
4216 6b93ec9d Iustin Pop

4217 6b93ec9d Iustin Pop
  """
4218 0c3d9c7c Thomas Thrainer
  bdevs = _FindDisks(disks)
4219 6b93ec9d Iustin Pop
4220 6b93ec9d Iustin Pop
  if multimaster:
4221 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
4222 6b93ec9d Iustin Pop
      try:
4223 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
4224 6b93ec9d Iustin Pop
      except EnvironmentError, err:
4225 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
4226 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
4227 6b93ec9d Iustin Pop
  # needed primary mode
4228 6b93ec9d Iustin Pop
  for rd in bdevs:
4229 6b93ec9d Iustin Pop
    try:
4230 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
4231 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
4232 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
4233 3c0cdc83 Michael Hanselmann
4234 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
4235 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
4236 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
4237 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
4238 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
4239 3c0cdc83 Michael Hanselmann
4240 3c0cdc83 Michael Hanselmann
  def _Attach():
4241 6b93ec9d Iustin Pop
    all_connected = True
4242 3c0cdc83 Michael Hanselmann
4243 6b93ec9d Iustin Pop
    for rd in bdevs:
4244 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
4245 3c0cdc83 Michael Hanselmann
4246 73e15b5e Apollon Oikonomopoulos
      if multimaster:
4247 73e15b5e Apollon Oikonomopoulos
        # In the multimaster case we have to wait explicitly until
4248 73e15b5e Apollon Oikonomopoulos
        # the resource is Connected and UpToDate/UpToDate, because
4249 73e15b5e Apollon Oikonomopoulos
        # we promote *both nodes* to primary directly afterwards.
4250 73e15b5e Apollon Oikonomopoulos
        # Being in resync is not enough, since there is a race during which we
4251 73e15b5e Apollon Oikonomopoulos
        # may promote a node with an Outdated disk to primary, effectively
4252 73e15b5e Apollon Oikonomopoulos
        # tearing down the connection.
4253 73e15b5e Apollon Oikonomopoulos
        all_connected = (all_connected and
4254 73e15b5e Apollon Oikonomopoulos
                         stats.is_connected and
4255 73e15b5e Apollon Oikonomopoulos
                         stats.is_disk_uptodate and
4256 73e15b5e Apollon Oikonomopoulos
                         stats.peer_disk_uptodate)
4257 73e15b5e Apollon Oikonomopoulos
      else:
4258 73e15b5e Apollon Oikonomopoulos
        all_connected = (all_connected and
4259 73e15b5e Apollon Oikonomopoulos
                         (stats.is_connected or stats.is_in_resync))
4260 3c0cdc83 Michael Hanselmann
4261 6b93ec9d Iustin Pop
      if stats.is_standalone:
4262 6b93ec9d Iustin Pop
        # peer had different config info and this node became
4263 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
4264 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
4265 6b93ec9d Iustin Pop
        try:
4266 c738375b Iustin Pop
          rd.AttachNet(multimaster)
4267 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
4268 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
4269 3c0cdc83 Michael Hanselmann
4270 3c0cdc83 Michael Hanselmann
    if not all_connected:
4271 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
4272 3c0cdc83 Michael Hanselmann
4273 3c0cdc83 Michael Hanselmann
  try:
4274 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
4275 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
4276 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
4277 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
4278 3c0cdc83 Michael Hanselmann
4279 6b93ec9d Iustin Pop
  if multimaster:
4280 6b93ec9d Iustin Pop
    # change to primary mode
4281 6b93ec9d Iustin Pop
    for rd in bdevs:
4282 d3da87b8 Iustin Pop
      try:
4283 d3da87b8 Iustin Pop
        rd.Open()
4284 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
4285 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
4286 6b93ec9d Iustin Pop
4287 6b93ec9d Iustin Pop
4288 0c3d9c7c Thomas Thrainer
def DrbdWaitSync(disks):
4289 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
4290 6b93ec9d Iustin Pop

4291 6b93ec9d Iustin Pop
  """
4292 db8667b7 Iustin Pop
  def _helper(rd):
4293 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
4294 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
4295 db8667b7 Iustin Pop
      raise utils.RetryAgain()
4296 db8667b7 Iustin Pop
    return stats
4297 db8667b7 Iustin Pop
4298 0c3d9c7c Thomas Thrainer
  bdevs = _FindDisks(disks)
4299 6b93ec9d Iustin Pop
4300 6b93ec9d Iustin Pop
  min_resync = 100
4301 6b93ec9d Iustin Pop
  alldone = True
4302 6b93ec9d Iustin Pop
  for rd in bdevs:
4303 db8667b7 Iustin Pop
    try:
4304 db8667b7 Iustin Pop
      # poll each second for 15 seconds
4305 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
4306 db8667b7 Iustin Pop
    except utils.RetryTimeout:
4307 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
4308 db8667b7 Iustin Pop
      # last check
4309 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
4310 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
4311 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
4312 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
4313 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
4314 afdc3985 Iustin Pop
4315 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
4316 6b93ec9d Iustin Pop
4317 6b93ec9d Iustin Pop
4318 0c3d9c7c Thomas Thrainer
def DrbdNeedsActivation(disks):
4319 235a6b29 Thomas Thrainer
  """Checks which of the passed disks needs activation and returns their UUIDs.
4320 235a6b29 Thomas Thrainer

4321 235a6b29 Thomas Thrainer
  """
4322 235a6b29 Thomas Thrainer
  faulty_disks = []
4323 235a6b29 Thomas Thrainer
4324 235a6b29 Thomas Thrainer
  for disk in disks:
4325 235a6b29 Thomas Thrainer
    rd = _RecursiveFindBD(disk)
4326 235a6b29 Thomas Thrainer
    if rd is None:
4327 235a6b29 Thomas Thrainer
      faulty_disks.append(disk)
4328 235a6b29 Thomas Thrainer
      continue
4329 235a6b29 Thomas Thrainer
4330 235a6b29 Thomas Thrainer
    stats = rd.GetProcStatus()
4331 235a6b29 Thomas Thrainer
    if stats.is_standalone or stats.is_diskless:
4332 235a6b29 Thomas Thrainer
      faulty_disks.append(disk)
4333 235a6b29 Thomas Thrainer
4334 235a6b29 Thomas Thrainer
  return [disk.uuid for disk in faulty_disks]
4335 235a6b29 Thomas Thrainer
4336 235a6b29 Thomas Thrainer
4337 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
4338 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
4339 c46b9782 Luca Bigliardi

4340 c46b9782 Luca Bigliardi
  """
4341 c46b9782 Luca Bigliardi
  try:
4342 47e0abee Thomas Thrainer
    return drbd.DRBD8.GetUsermodeHelper()
4343 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
4344 c46b9782 Luca Bigliardi
    _Fail(str(err))
4345 c46b9782 Luca Bigliardi
4346 c46b9782 Luca Bigliardi
4347 8ef418bb Helga Velroyen
def PowercycleNode(hypervisor_type, hvparams=None):
4348 f5118ade Iustin Pop
  """Hard-powercycle the node.
4349 f5118ade Iustin Pop

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

4353 f5118ade Iustin Pop
  """
4354 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4355 f5118ade Iustin Pop
  try:
4356 f5118ade Iustin Pop
    pid = os.fork()
4357 29921401 Iustin Pop
  except OSError:
4358 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
4359 f5118ade Iustin Pop
    pid = 0
4360 f5118ade Iustin Pop
  if pid > 0:
4361 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
4362 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
4363 1af6ac0f Luca Bigliardi
  try:
4364 1af6ac0f Luca Bigliardi
    utils.Mlockall()
4365 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
4366 1af6ac0f Luca Bigliardi
    pass
4367 f5118ade Iustin Pop
  time.sleep(5)
4368 8ef418bb Helga Velroyen
  hyper.PowercycleNode(hvparams=hvparams)
4369 f5118ade Iustin Pop
4370 f5118ade Iustin Pop
4371 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
4372 45bc4635 Iustin Pop
  """Verifies a restricted command name.
4373 1a2eb2dc Michael Hanselmann

4374 1a2eb2dc Michael Hanselmann
  @type cmd: string
4375 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4376 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
4377 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4378 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
4379 1a2eb2dc Michael Hanselmann

4380 1a2eb2dc Michael Hanselmann
  """
4381 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
4382 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
4383 1a2eb2dc Michael Hanselmann
4384 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
4385 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
4386 1a2eb2dc Michael Hanselmann
4387 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4388 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
4389 1a2eb2dc Michael Hanselmann
4390 1a2eb2dc Michael Hanselmann
  return (True, None)
4391 1a2eb2dc Michael Hanselmann
4392 1a2eb2dc Michael Hanselmann
4393 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
4394 45bc4635 Iustin Pop
  """Common checks for restricted command file system directories and files.
4395 1a2eb2dc Michael Hanselmann

4396 1a2eb2dc Michael Hanselmann
  @type path: string
4397 1a2eb2dc Michael Hanselmann
  @param path: Path to check
4398 1a2eb2dc Michael Hanselmann
  @param owner: C{None} or tuple containing UID and GID
4399 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or C{os.stat} result)
4400 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4401 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's the result of C{os.stat}
4402 1a2eb2dc Michael Hanselmann

4403 1a2eb2dc Michael Hanselmann
  """
4404 1a2eb2dc Michael Hanselmann
  if owner is None:
4405 1a2eb2dc Michael Hanselmann
    # Default to root as owner
4406 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
4407 1a2eb2dc Michael Hanselmann
4408 1a2eb2dc Michael Hanselmann
  try:
4409 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
4410 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
4411 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4412 1a2eb2dc Michael Hanselmann
4413 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
4414 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
4415 1a2eb2dc Michael Hanselmann
4416 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
4417 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
4418 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4419 1a2eb2dc Michael Hanselmann
4420 1a2eb2dc Michael Hanselmann
  return (True, st)
4421 1a2eb2dc Michael Hanselmann
4422 1a2eb2dc Michael Hanselmann
4423 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4424 45bc4635 Iustin Pop
  """Verifies restricted command directory.
4425 1a2eb2dc Michael Hanselmann

4426 1a2eb2dc Michael Hanselmann
  @type path: string
4427 1a2eb2dc Michael Hanselmann
  @param path: Path to check
4428 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
4429 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4430 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
4431 1a2eb2dc Michael Hanselmann

4432 1a2eb2dc Michael Hanselmann
  """
4433 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4434 1a2eb2dc Michael Hanselmann
4435 1a2eb2dc Michael Hanselmann
  if not status:
4436 1a2eb2dc Michael Hanselmann
    return (False, value)
4437 1a2eb2dc Michael Hanselmann
4438 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
4439 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
4440 1a2eb2dc Michael Hanselmann
4441 1a2eb2dc Michael Hanselmann
  return (True, None)
4442 1a2eb2dc Michael Hanselmann
4443 1a2eb2dc Michael Hanselmann
4444 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4445 45bc4635 Iustin Pop
  """Verifies a whole restricted command and returns its executable filename.
4446 1a2eb2dc Michael Hanselmann

4447 1a2eb2dc Michael Hanselmann
  @type path: string
4448 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
4449 1a2eb2dc Michael Hanselmann
  @type cmd: string
4450 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4451 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
4452 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
4453 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
4454 1a2eb2dc Michael Hanselmann
    absolute path to the executable
4455 1a2eb2dc Michael Hanselmann

4456 1a2eb2dc Michael Hanselmann
  """
4457 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
4458 1a2eb2dc Michael Hanselmann
4459 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4460 1a2eb2dc Michael Hanselmann
4461 1a2eb2dc Michael Hanselmann
  if not status:
4462 1a2eb2dc Michael Hanselmann
    return (False, msg)
4463 1a2eb2dc Michael Hanselmann
4464 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
4465 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4466 1a2eb2dc Michael Hanselmann
4467 1a2eb2dc Michael Hanselmann
  return (True, executable)
4468 1a2eb2dc Michael Hanselmann
4469 1a2eb2dc Michael Hanselmann
4470 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
4471 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4472 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
4473 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
4474 45bc4635 Iustin Pop
  """Performs a number of tests on a restricted command.
4475 1a2eb2dc Michael Hanselmann

4476 1a2eb2dc Michael Hanselmann
  @type path: string
4477 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
4478 1a2eb2dc Michael Hanselmann
  @type cmd: string
4479 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4480 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
4481 1a2eb2dc Michael Hanselmann

4482 1a2eb2dc Michael Hanselmann
  """
4483 1a2eb2dc Michael Hanselmann
  # Verify the directory first
4484 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
4485 1a2eb2dc Michael Hanselmann
  if status:
4486 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
4487 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
4488 1a2eb2dc Michael Hanselmann
4489 1a2eb2dc Michael Hanselmann
  if not status:
4490 1a2eb2dc Michael Hanselmann
    return (False, msg)
4491 1a2eb2dc Michael Hanselmann
4492 1a2eb2dc Michael Hanselmann
  # Check actual executable
4493 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
4494 1a2eb2dc Michael Hanselmann
4495 1a2eb2dc Michael Hanselmann
4496 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
4497 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4498 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4499 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4500 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
4501 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
4502 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
4503 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4504 45bc4635 Iustin Pop
  """Executes a restricted command after performing strict tests.
4505 1a2eb2dc Michael Hanselmann

4506 1a2eb2dc Michael Hanselmann
  @type cmd: string
4507 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
4508 1a2eb2dc Michael Hanselmann
  @rtype: string
4509 1a2eb2dc Michael Hanselmann
  @return: Command output
4510 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
4511 1a2eb2dc Michael Hanselmann

4512 1a2eb2dc Michael Hanselmann
  """
4513 45bc4635 Iustin Pop
  logging.info("Preparing to run restricted command '%s'", cmd)
4514 1a2eb2dc Michael Hanselmann
4515 1a2eb2dc Michael Hanselmann
  if not _enabled:
4516 45bc4635 Iustin Pop
    _Fail("Restricted commands disabled at configure time")
4517 1a2eb2dc Michael Hanselmann
4518 1a2eb2dc Michael Hanselmann
  lock = None
4519 1a2eb2dc Michael Hanselmann
  try:
4520 1a2eb2dc Michael Hanselmann
    cmdresult = None
4521 1a2eb2dc Michael Hanselmann
    try:
4522 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
4523 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4524 1a2eb2dc Michael Hanselmann
4525 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
4526 1a2eb2dc Michael Hanselmann
4527 1a2eb2dc Michael Hanselmann
      if status:
4528 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4529 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
4530 1a2eb2dc Michael Hanselmann
      else:
4531 1a2eb2dc Michael Hanselmann
        logging.error(value)
4532 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
4533 1a2eb2dc Michael Hanselmann
      # Keep original error in log
4534 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
4535 1a2eb2dc Michael Hanselmann
4536 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
4537 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
4538 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
4539 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
4540 1a2eb2dc Michael Hanselmann
4541 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
4542 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
4543 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
4544 45bc4635 Iustin Pop
      _Fail("Restricted command '%s' failed: %s; output: %s",
4545 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
4546 1a2eb2dc Michael Hanselmann
    else:
4547 1a2eb2dc Michael Hanselmann
      return cmdresult.output
4548 1a2eb2dc Michael Hanselmann
  finally:
4549 1a2eb2dc Michael Hanselmann
    if lock is not None:
4550 1a2eb2dc Michael Hanselmann
      # Release lock at last
4551 1a2eb2dc Michael Hanselmann
      lock.Close()
4552 1a2eb2dc Michael Hanselmann
      lock = None
4553 1a2eb2dc Michael Hanselmann
4554 1a2eb2dc Michael Hanselmann
4555 99e222b1 Michael Hanselmann
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4556 99e222b1 Michael Hanselmann
  """Creates or removes the watcher pause file.
4557 99e222b1 Michael Hanselmann

4558 99e222b1 Michael Hanselmann
  @type until: None or number
4559 99e222b1 Michael Hanselmann
  @param until: Unix timestamp saying until when the watcher shouldn't run
4560 99e222b1 Michael Hanselmann

4561 99e222b1 Michael Hanselmann
  """
4562 99e222b1 Michael Hanselmann
  if until is None:
4563 99e222b1 Michael Hanselmann
    logging.info("Received request to no longer pause watcher")
4564 99e222b1 Michael Hanselmann
    utils.RemoveFile(_filename)
4565 99e222b1 Michael Hanselmann
  else:
4566 99e222b1 Michael Hanselmann
    logging.info("Received request to pause watcher until %s", until)
4567 99e222b1 Michael Hanselmann
4568 99e222b1 Michael Hanselmann
    if not ht.TNumber(until):
4569 99e222b1 Michael Hanselmann
      _Fail("Duration must be numeric")
4570 99e222b1 Michael Hanselmann
4571 99e222b1 Michael Hanselmann
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
4572 99e222b1 Michael Hanselmann
4573 99e222b1 Michael Hanselmann
4574 4daa5eb9 Sebastian Gebhard
def ConfigureOVS(ovs_name, ovs_link):
4575 4daa5eb9 Sebastian Gebhard
  """Creates a OpenvSwitch on the node.
4576 4daa5eb9 Sebastian Gebhard

4577 4daa5eb9 Sebastian Gebhard
  This function sets up a OpenvSwitch on the node with given name nad
4578 4daa5eb9 Sebastian Gebhard
  connects it via a given eth device.
4579 4daa5eb9 Sebastian Gebhard

4580 4daa5eb9 Sebastian Gebhard
  @type ovs_name: string
4581 4daa5eb9 Sebastian Gebhard
  @param ovs_name: Name of the OpenvSwitch to create.
4582 4daa5eb9 Sebastian Gebhard
  @type ovs_link: None or string
4583 4daa5eb9 Sebastian Gebhard
  @param ovs_link: Ethernet device for outside connection (can be missing)
4584 4daa5eb9 Sebastian Gebhard

4585 4daa5eb9 Sebastian Gebhard
  """
4586 4daa5eb9 Sebastian Gebhard
  # Initialize the OpenvSwitch
4587 4daa5eb9 Sebastian Gebhard
  result = utils.RunCmd(["ovs-vsctl", "add-br", ovs_name])
4588 4daa5eb9 Sebastian Gebhard
  if result.failed:
4589 a1578ccf Sebastian Gebhard
    _Fail("Failed to create openvswitch. Script return value: %s, output: '%s'"
4590 a1578ccf Sebastian Gebhard
          % (result.exit_code, result.output), log=True)
4591 4daa5eb9 Sebastian Gebhard
4592 4daa5eb9 Sebastian Gebhard
  # And connect it to a physical interface, if given
4593 4daa5eb9 Sebastian Gebhard
  if ovs_link:
4594 4daa5eb9 Sebastian Gebhard
    result = utils.RunCmd(["ovs-vsctl", "add-port", ovs_name, ovs_link])
4595 4daa5eb9 Sebastian Gebhard
    if result.failed:
4596 4daa5eb9 Sebastian Gebhard
      _Fail("Failed to connect openvswitch to  interface %s. Script return"
4597 a1578ccf Sebastian Gebhard
            " value: %s, output: '%s'" % (ovs_link, result.exit_code,
4598 a1578ccf Sebastian Gebhard
            result.output), log=True)
4599 4daa5eb9 Sebastian Gebhard
4600 4daa5eb9 Sebastian Gebhard
4601 a8083063 Iustin Pop
class HooksRunner(object):
4602 a8083063 Iustin Pop
  """Hook runner.
4603 a8083063 Iustin Pop

4604 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
4605 10c2650b Iustin Pop
  on the master side.
4606 a8083063 Iustin Pop

4607 a8083063 Iustin Pop
  """
4608 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
4609 a8083063 Iustin Pop
    """Constructor for hooks runner.
4610 a8083063 Iustin Pop

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

4615 a8083063 Iustin Pop
    """
4616 a8083063 Iustin Pop
    if hooks_base_dir is None:
4617 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4618 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4619 fe267188 Iustin Pop
    # constant
4620 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4621 a8083063 Iustin Pop
4622 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
4623 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
4624 0fa481f5 Andrea Spadaccini

4625 0fa481f5 Andrea Spadaccini
    """
4626 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
4627 0fa481f5 Andrea Spadaccini
    node = node_list[0]
4628 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
4629 0fa481f5 Andrea Spadaccini
    assert node == myself
4630 0fa481f5 Andrea Spadaccini
4631 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
4632 0fa481f5 Andrea Spadaccini
4633 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
4634 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
4635 0fa481f5 Andrea Spadaccini
4636 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
4637 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
4638 a8083063 Iustin Pop

4639 10c2650b Iustin Pop
    @type hpath: str
4640 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
4641 10c2650b Iustin Pop
        holds the scripts
4642 10c2650b Iustin Pop
    @type phase: str
4643 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4644 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
4645 10c2650b Iustin Pop
    @type env: dict
4646 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
4647 10c2650b Iustin Pop
    @rtype: list
4648 10c2650b Iustin Pop
    @return: list of 3-element tuples:
4649 10c2650b Iustin Pop
      - script path
4650 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
4651 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
4652 10c2650b Iustin Pop
      - output of the script
4653 10c2650b Iustin Pop

4654 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
4655 10c2650b Iustin Pop
        parameters
4656 a8083063 Iustin Pop

4657 a8083063 Iustin Pop
    """
4658 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
4659 a8083063 Iustin Pop
      suffix = "pre"
4660 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
4661 a8083063 Iustin Pop
      suffix = "post"
4662 a8083063 Iustin Pop
    else:
4663 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
4664 3fb4f740 Iustin Pop
4665 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
4666 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4667 6bb65e3a Guido Trotter
4668 6bb65e3a Guido Trotter
    results = []
4669 a9b7e346 Iustin Pop
4670 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
4671 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
4672 a9b7e346 Iustin Pop
      # warning at every operation
4673 a9b7e346 Iustin Pop
      return results
4674 a9b7e346 Iustin Pop
4675 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4676 a9b7e346 Iustin Pop
4677 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
4678 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
4679 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
4680 a8083063 Iustin Pop
        output = ""
4681 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
4682 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
4683 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
4684 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
4685 6bb65e3a Guido Trotter
        if runresult.failed:
4686 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
4687 a8083063 Iustin Pop
        else:
4688 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
4689 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
4690 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4691 6bb65e3a Guido Trotter
4692 6bb65e3a Guido Trotter
    return results
4693 3f78eef2 Iustin Pop
4694 3f78eef2 Iustin Pop
4695 8d528b7c Iustin Pop
class IAllocatorRunner(object):
4696 8d528b7c Iustin Pop
  """IAllocator runner.
4697 8d528b7c Iustin Pop

4698 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
4699 8d528b7c Iustin Pop
  the master side.
4700 8d528b7c Iustin Pop

4701 8d528b7c Iustin Pop
  """
4702 7e950d31 Iustin Pop
  @staticmethod
4703 0359e5d0 Spyros Trigazis
  def Run(name, idata, ial_params):
4704 8d528b7c Iustin Pop
    """Run an iallocator script.
4705 8d528b7c Iustin Pop

4706 10c2650b Iustin Pop
    @type name: str
4707 10c2650b Iustin Pop
    @param name: the iallocator script name
4708 10c2650b Iustin Pop
    @type idata: str
4709 10c2650b Iustin Pop
    @param idata: the allocator input data
4710 0359e5d0 Spyros Trigazis
    @type ial_params: list
4711 0359e5d0 Spyros Trigazis
    @param ial_params: the iallocator parameters
4712 10c2650b Iustin Pop

4713 10c2650b Iustin Pop
    @rtype: tuple
4714 87f5c298 Iustin Pop
    @return: two element tuple of:
4715 87f5c298 Iustin Pop
       - status
4716 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
4717 8d528b7c Iustin Pop

4718 8d528b7c Iustin Pop
    """
4719 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4720 8d528b7c Iustin Pop
                                  os.path.isfile)
4721 8d528b7c Iustin Pop
    if alloc_script is None:
4722 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
4723 8d528b7c Iustin Pop
4724 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4725 8d528b7c Iustin Pop
    try:
4726 8d528b7c Iustin Pop
      os.write(fd, idata)
4727 8d528b7c Iustin Pop
      os.close(fd)
4728 0359e5d0 Spyros Trigazis
      result = utils.RunCmd([alloc_script, fin_name] + ial_params)
4729 8d528b7c Iustin Pop
      if result.failed:
4730 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4731 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
4732 8d528b7c Iustin Pop
    finally:
4733 8d528b7c Iustin Pop
      os.unlink(fin_name)
4734 8d528b7c Iustin Pop
4735 c26a6bd2 Iustin Pop
    return result.stdout
4736 8d528b7c Iustin Pop
4737 8d528b7c Iustin Pop
4738 3f78eef2 Iustin Pop
class DevCacheManager(object):
4739 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
4740 3f78eef2 Iustin Pop

4741 3f78eef2 Iustin Pop
  """
4742 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
4743 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4744 3f78eef2 Iustin Pop
4745 3f78eef2 Iustin Pop
  @classmethod
4746 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
4747 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
4748 3f78eef2 Iustin Pop

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

4752 10c2650b Iustin Pop
    @type dev_path: str
4753 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
4754 10c2650b Iustin Pop
    @rtype: str
4755 10c2650b Iustin Pop
    @return: the converted path name
4756 3f78eef2 Iustin Pop

4757 3f78eef2 Iustin Pop
    """
4758 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
4759 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4760 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
4761 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4762 3f78eef2 Iustin Pop
    return fpath
4763 3f78eef2 Iustin Pop
4764 3f78eef2 Iustin Pop
  @classmethod
4765 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4766 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
4767 3f78eef2 Iustin Pop

4768 10c2650b Iustin Pop
    @type dev_path: str
4769 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4770 10c2650b Iustin Pop
    @type owner: str
4771 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
4772 10c2650b Iustin Pop
    @type on_primary: bool
4773 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
4774 10c2650b Iustin Pop
        node nor not
4775 10c2650b Iustin Pop
    @type iv_name: str
4776 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
4777 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
4778 10c2650b Iustin Pop

4779 10c2650b Iustin Pop
    @rtype: None
4780 10c2650b Iustin Pop

4781 3f78eef2 Iustin Pop
    """
4782 cf5a8306 Iustin Pop
    if dev_path is None:
4783 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4784 cf5a8306 Iustin Pop
      return
4785 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4786 3f78eef2 Iustin Pop
    if on_primary:
4787 3f78eef2 Iustin Pop
      state = "primary"
4788 3f78eef2 Iustin Pop
    else:
4789 3f78eef2 Iustin Pop
      state = "secondary"
4790 3f78eef2 Iustin Pop
    if iv_name is None:
4791 3f78eef2 Iustin Pop
      iv_name = "not_visible"
4792 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4793 3f78eef2 Iustin Pop
    try:
4794 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
4795 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4796 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4797 3f78eef2 Iustin Pop
4798 3f78eef2 Iustin Pop
  @classmethod
4799 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
4800 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
4801 3f78eef2 Iustin Pop

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

4805 10c2650b Iustin Pop
    @type dev_path: str
4806 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4807 10c2650b Iustin Pop

4808 10c2650b Iustin Pop
    @rtype: None
4809 10c2650b Iustin Pop

4810 3f78eef2 Iustin Pop
    """
4811 cf5a8306 Iustin Pop
    if dev_path is None:
4812 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4813 cf5a8306 Iustin Pop
      return
4814 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4815 3f78eef2 Iustin Pop
    try:
4816 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
4817 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4818 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)