Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ dbae804a

History | View | Annotate | Download (124.6 kB)

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

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

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

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

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

116 a59d5fa1 Michele Tartara
  @type instance_name: string
117 a59d5fa1 Michele Tartara
  @param instance_name: The name of the instance
118 a59d5fa1 Michele Tartara
  @rtype: string
119 a59d5fa1 Michele Tartara
  @return: The path of the file
120 a59d5fa1 Michele Tartara

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

128 584ea340 Michele Tartara
  The exact location of the file depends on the name of the instance and on
129 584ea340 Michele Tartara
  the configuration of the Ganeti cluster defined at deploy time.
130 584ea340 Michele Tartara

131 584ea340 Michele Tartara
  @type instance_name: string
132 584ea340 Michele Tartara
  @param instance_name: The name of the instance
133 584ea340 Michele Tartara
  @rtype: None
134 584ea340 Michele Tartara

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

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

149 2cc6781a Iustin Pop
  @type msg: string
150 2cc6781a Iustin Pop
  @param msg: the text of the exception
151 2cc6781a Iustin Pop
  @raise RPCFail
152 2cc6781a Iustin Pop

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

167 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
168 93384844 Iustin Pop
  @return: a SimpleStore instance
169 10c2650b Iustin Pop

170 10c2650b Iustin Pop
  """
171 93384844 Iustin Pop
  return ssconf.SimpleStore()
172 c657dcc9 Michael Hanselmann
173 c657dcc9 Michael Hanselmann
174 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
175 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
176 10c2650b Iustin Pop

177 10c2650b Iustin Pop
  @type cluster_name: str
178 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
179 10c2650b Iustin Pop
      by the SshRunner constructor
180 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
181 10c2650b Iustin Pop
  @return: an SshRunner instance
182 10c2650b Iustin Pop

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

190 12bce260 Michael Hanselmann
  @type data: list or tuple
191 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
192 12bce260 Michael Hanselmann
  @rtype: str
193 12bce260 Michael Hanselmann
  @return: Decompressed data
194 12bce260 Michael Hanselmann

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

210 10c2650b Iustin Pop
  @type path: str
211 10c2650b Iustin Pop
  @param path: the directory to clean
212 76ab5558 Michael Hanselmann
  @type exclude: list
213 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
214 10c2650b Iustin Pop
      to the empty list
215 76ab5558 Michael Hanselmann

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

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

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

272 c8457ce7 Iustin Pop
  @rtype: tuple
273 c8457ce7 Iustin Pop
  @return: True, None
274 24fc781f Michael Hanselmann

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

283 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
284 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
285 bd1e4562 Iustin Pop

286 bd1e4562 Iustin Pop
  @rtype: tuple
287 909b3a0e Andrea Spadaccini
  @return: master_netdev, master_ip, master_name, primary_ip_family,
288 909b3a0e Andrea Spadaccini
    master_netmask
289 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
290 b1b6ea87 Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

575 78519c10 Michael Hanselmann
  """
576 78519c10 Michael Hanselmann
  # TODO: GetVGInfo supports returning information for multiple VGs at once
577 1a3c5d4e Bernardo Dal Seno
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
578 78519c10 Michael Hanselmann
  if vginfo:
579 78519c10 Michael Hanselmann
    vg_free = int(round(vginfo[0][0], 0))
580 78519c10 Michael Hanselmann
    vg_size = int(round(vginfo[0][1], 0))
581 78519c10 Michael Hanselmann
  else:
582 78519c10 Michael Hanselmann
    vg_free = None
583 78519c10 Michael Hanselmann
    vg_size = None
584 78519c10 Michael Hanselmann
585 78519c10 Michael Hanselmann
  return {
586 78519c10 Michael Hanselmann
    "name": name,
587 1e89a135 Michael Hanselmann
    "vg_free": vg_free,
588 1e89a135 Michael Hanselmann
    "vg_size": vg_size,
589 78519c10 Michael Hanselmann
    }
590 78519c10 Michael Hanselmann
591 78519c10 Michael Hanselmann
592 78519c10 Michael Hanselmann
def _GetHvInfo(name):
593 78519c10 Michael Hanselmann
  """Retrieves node information from a hypervisor.
594 78519c10 Michael Hanselmann

595 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
596 78519c10 Michael Hanselmann

597 78519c10 Michael Hanselmann
    - vg_size is the size of the configured volume group in MiB
598 78519c10 Michael Hanselmann
    - vg_free is the free size of the volume group in MiB
599 78519c10 Michael Hanselmann
    - memory_dom0 is the memory allocated for domain0 in MiB
600 78519c10 Michael Hanselmann
    - memory_free is the currently available (free) ram in MiB
601 78519c10 Michael Hanselmann
    - memory_total is the total number of ram in MiB
602 78519c10 Michael Hanselmann
    - hv_version: the hypervisor version, if available
603 78519c10 Michael Hanselmann

604 78519c10 Michael Hanselmann
  """
605 78519c10 Michael Hanselmann
  return hypervisor.GetHypervisor(name).GetNodeInfo()
606 78519c10 Michael Hanselmann
607 78519c10 Michael Hanselmann
608 78519c10 Michael Hanselmann
def _GetNamedNodeInfo(names, fn):
609 78519c10 Michael Hanselmann
  """Calls C{fn} for all names in C{names} and returns a dictionary.
610 78519c10 Michael Hanselmann

611 78519c10 Michael Hanselmann
  @rtype: None or dict
612 78519c10 Michael Hanselmann

613 78519c10 Michael Hanselmann
  """
614 78519c10 Michael Hanselmann
  if names is None:
615 78519c10 Michael Hanselmann
    return None
616 78519c10 Michael Hanselmann
  else:
617 ff3be305 Michael Hanselmann
    return map(fn, names)
618 78519c10 Michael Hanselmann
619 78519c10 Michael Hanselmann
620 1a3c5d4e Bernardo Dal Seno
def GetNodeInfo(vg_names, hv_names, excl_stor):
621 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
622 a8083063 Iustin Pop

623 78519c10 Michael Hanselmann
  @type vg_names: list of string
624 78519c10 Michael Hanselmann
  @param vg_names: Names of the volume groups to ask for disk space information
625 78519c10 Michael Hanselmann
  @type hv_names: list of string
626 78519c10 Michael Hanselmann
  @param hv_names: Names of the hypervisors to ask for node information
627 1a3c5d4e Bernardo Dal Seno
  @type excl_stor: boolean
628 1a3c5d4e Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
629 78519c10 Michael Hanselmann
  @rtype: tuple; (string, None/dict, None/dict)
630 78519c10 Michael Hanselmann
  @return: Tuple containing boot ID, volume group information and hypervisor
631 78519c10 Michael Hanselmann
    information
632 a8083063 Iustin Pop

633 098c0958 Michael Hanselmann
  """
634 78519c10 Michael Hanselmann
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
635 1a3c5d4e Bernardo Dal Seno
  vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
636 78519c10 Michael Hanselmann
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
637 78519c10 Michael Hanselmann
638 78519c10 Michael Hanselmann
  return (bootid, vg_info, hv_info)
639 a8083063 Iustin Pop
640 a8083063 Iustin Pop
641 d5a690cb Bernardo Dal Seno
def _CheckExclusivePvs(pvi_list):
642 d5a690cb Bernardo Dal Seno
  """Check that PVs are not shared among LVs
643 d5a690cb Bernardo Dal Seno

644 d5a690cb Bernardo Dal Seno
  @type pvi_list: list of L{objects.LvmPvInfo} objects
645 d5a690cb Bernardo Dal Seno
  @param pvi_list: information about the PVs
646 d5a690cb Bernardo Dal Seno

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

650 d5a690cb Bernardo Dal Seno
  """
651 d5a690cb Bernardo Dal Seno
  res = []
652 d5a690cb Bernardo Dal Seno
  for pvi in pvi_list:
653 d5a690cb Bernardo Dal Seno
    if len(pvi.lv_list) > 1:
654 d5a690cb Bernardo Dal Seno
      res.append((pvi.name, pvi.lv_list))
655 d5a690cb Bernardo Dal Seno
  return res
656 d5a690cb Bernardo Dal Seno
657 d5a690cb Bernardo Dal Seno
658 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
659 a8083063 Iustin Pop
  """Verify the status of the local node.
660 a8083063 Iustin Pop

661 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
662 e69d05fd Iustin Pop
  local node.
663 e69d05fd Iustin Pop

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

667 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
668 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
669 e69d05fd Iustin Pop
  report).
670 a8083063 Iustin Pop

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

675 e69d05fd Iustin Pop
  @type what: C{dict}
676 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
677 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
678 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
679 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
680 e69d05fd Iustin Pop
        connectivity with
681 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
682 10c2650b Iustin Pop
  @rtype: dict
683 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
684 10c2650b Iustin Pop
      values representing the result of the checks
685 a8083063 Iustin Pop

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

882 2be7273c Apollon Oikonomopoulos
  @type devices: list
883 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
884 2be7273c Apollon Oikonomopoulos
  @rtype: dict
885 2be7273c Apollon Oikonomopoulos
  @return:
886 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
887 2be7273c Apollon Oikonomopoulos
    size in MiB.
888 2be7273c Apollon Oikonomopoulos

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

891 2be7273c Apollon Oikonomopoulos
  """
892 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
893 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
894 2be7273c Apollon Oikonomopoulos
895 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
896 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
897 2be7273c Apollon Oikonomopoulos
      continue
898 2be7273c Apollon Oikonomopoulos
899 2be7273c Apollon Oikonomopoulos
    try:
900 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
901 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
902 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
903 2be7273c Apollon Oikonomopoulos
      continue
904 2be7273c Apollon Oikonomopoulos
905 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
906 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
907 2be7273c Apollon Oikonomopoulos
      if result.failed:
908 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
909 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
910 2be7273c Apollon Oikonomopoulos
        continue
911 2be7273c Apollon Oikonomopoulos
912 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
913 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
914 2be7273c Apollon Oikonomopoulos
  return blockdevs
915 2be7273c Apollon Oikonomopoulos
916 2be7273c Apollon Oikonomopoulos
917 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
918 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
919 a8083063 Iustin Pop

920 84d7e26b Dmitry Chernyak
  @type vg_names: list
921 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
922 397693d3 Iustin Pop
      empty for all volume groups
923 10c2650b Iustin Pop
  @rtype: dict
924 10c2650b Iustin Pop
  @return:
925 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
926 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
927 10c2650b Iustin Pop

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

930 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
931 10c2650b Iustin Pop
      details.
932 a8083063 Iustin Pop

933 a8083063 Iustin Pop
  """
934 cb2037a2 Iustin Pop
  lvs = {}
935 d0c8c01d Iustin Pop
  sep = "|"
936 397693d3 Iustin Pop
  if not vg_names:
937 397693d3 Iustin Pop
    vg_names = []
938 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
939 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
940 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
941 a8083063 Iustin Pop
  if result.failed:
942 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
943 cb2037a2 Iustin Pop
944 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
945 df4c2628 Iustin Pop
    line = line.strip()
946 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
947 df4c2628 Iustin Pop
    if not match:
948 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
949 df4c2628 Iustin Pop
      continue
950 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
951 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
952 d0c8c01d Iustin Pop
    online = attr[5] == "o"
953 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
954 33f2a81a Iustin Pop
    if virtual:
955 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
956 33f2a81a Iustin Pop
      # don't really hold data
957 33f2a81a Iustin Pop
      continue
958 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
959 cb2037a2 Iustin Pop
960 cb2037a2 Iustin Pop
  return lvs
961 a8083063 Iustin Pop
962 a8083063 Iustin Pop
963 a8083063 Iustin Pop
def ListVolumeGroups():
964 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
965 a8083063 Iustin Pop

966 10c2650b Iustin Pop
  @rtype: dict
967 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
968 10c2650b Iustin Pop
      size of the volume
969 a8083063 Iustin Pop

970 a8083063 Iustin Pop
  """
971 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
972 a8083063 Iustin Pop
973 a8083063 Iustin Pop
974 dcb93971 Michael Hanselmann
def NodeVolumes():
975 dcb93971 Michael Hanselmann
  """List all volumes on this node.
976 dcb93971 Michael Hanselmann

977 10c2650b Iustin Pop
  @rtype: list
978 10c2650b Iustin Pop
  @return:
979 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
980 10c2650b Iustin Pop
      - name: the logical volume name,
981 10c2650b Iustin Pop
      - size: the size of the logical volume
982 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
983 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
984 10c2650b Iustin Pop

985 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
986 10c2650b Iustin Pop
    error.
987 10c2650b Iustin Pop

988 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
989 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
990 10c2650b Iustin Pop
    multiple times.
991 10c2650b Iustin Pop

992 dcb93971 Michael Hanselmann
  """
993 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
994 dcb93971 Michael Hanselmann
                         "--separator=|",
995 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
996 dcb93971 Michael Hanselmann
  if result.failed:
997 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
998 10bfe6cb Iustin Pop
          result.output)
999 dcb93971 Michael Hanselmann
1000 dcb93971 Michael Hanselmann
  def parse_dev(dev):
1001 d0c8c01d Iustin Pop
    return dev.split("(")[0]
1002 89e5ab02 Iustin Pop
1003 89e5ab02 Iustin Pop
  def handle_dev(dev):
1004 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
1005 dcb93971 Michael Hanselmann
1006 dcb93971 Michael Hanselmann
  def map_line(line):
1007 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
1008 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
1009 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1010 89e5ab02 Iustin Pop
1011 89e5ab02 Iustin Pop
  all_devs = []
1012 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
1013 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
1014 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
1015 89e5ab02 Iustin Pop
    else:
1016 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
1017 89e5ab02 Iustin Pop
  return all_devs
1018 dcb93971 Michael Hanselmann
1019 dcb93971 Michael Hanselmann
1020 a8083063 Iustin Pop
def BridgesExist(bridges_list):
1021 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
1022 a8083063 Iustin Pop

1023 b1206984 Iustin Pop
  @rtype: boolean
1024 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
1025 a8083063 Iustin Pop

1026 a8083063 Iustin Pop
  """
1027 35c0c8da Iustin Pop
  missing = []
1028 a8083063 Iustin Pop
  for bridge in bridges_list:
1029 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
1030 35c0c8da Iustin Pop
      missing.append(bridge)
1031 a8083063 Iustin Pop
1032 35c0c8da Iustin Pop
  if missing:
1033 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1034 35c0c8da Iustin Pop
1035 a8083063 Iustin Pop
1036 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
1037 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
1038 a8083063 Iustin Pop

1039 e69d05fd Iustin Pop
  @type hypervisor_list: list
1040 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
1041 e69d05fd Iustin Pop

1042 e69d05fd Iustin Pop
  @rtype: list
1043 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
1044 10c2650b Iustin Pop
    - instance1.example.com
1045 10c2650b Iustin Pop
    - instance2.example.com
1046 a8083063 Iustin Pop

1047 098c0958 Michael Hanselmann
  """
1048 e69d05fd Iustin Pop
  results = []
1049 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1050 e69d05fd Iustin Pop
    try:
1051 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
1052 e69d05fd Iustin Pop
      results.extend(names)
1053 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
1054 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
1055 aca13712 Iustin Pop
            hname, err, exc=True)
1056 a8083063 Iustin Pop
1057 e69d05fd Iustin Pop
  return results
1058 a8083063 Iustin Pop
1059 a8083063 Iustin Pop
1060 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
1061 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
1062 a8083063 Iustin Pop

1063 e69d05fd Iustin Pop
  @type instance: string
1064 e69d05fd Iustin Pop
  @param instance: the instance name
1065 e69d05fd Iustin Pop
  @type hname: string
1066 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1067 a8083063 Iustin Pop

1068 e69d05fd Iustin Pop
  @rtype: dict
1069 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1070 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1071 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1072 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1073 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1074 a8083063 Iustin Pop

1075 098c0958 Michael Hanselmann
  """
1076 a8083063 Iustin Pop
  output = {}
1077 a8083063 Iustin Pop
1078 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1079 a8083063 Iustin Pop
  if iinfo is not None:
1080 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1081 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1082 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1083 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1084 a8083063 Iustin Pop
1085 c26a6bd2 Iustin Pop
  return output
1086 a8083063 Iustin Pop
1087 a8083063 Iustin Pop
1088 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1089 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
1090 56e7640c Iustin Pop

1091 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1092 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1093 56e7640c Iustin Pop

1094 56e7640c Iustin Pop
  @rtype: tuple
1095 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1096 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1097 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1098 56e7640c Iustin Pop

1099 56e7640c Iustin Pop
  """
1100 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1101 afdc3985 Iustin Pop
  iname = instance.name
1102 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
1103 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1104 56e7640c Iustin Pop
1105 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1106 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1107 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1108 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1109 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1110 56e7640c Iustin Pop
1111 56e7640c Iustin Pop
1112 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
1113 a8083063 Iustin Pop
  """Gather data about all instances.
1114 a8083063 Iustin Pop

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

1119 e69d05fd Iustin Pop
  @type hypervisor_list: list
1120 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1121 e69d05fd Iustin Pop

1122 955db481 Guido Trotter
  @rtype: dict
1123 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1124 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1125 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1126 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1127 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1128 a8083063 Iustin Pop

1129 098c0958 Michael Hanselmann
  """
1130 a8083063 Iustin Pop
  output = {}
1131 a8083063 Iustin Pop
1132 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1133 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1134 e69d05fd Iustin Pop
    if iinfo:
1135 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1136 f23b5ae8 Iustin Pop
        value = {
1137 d0c8c01d Iustin Pop
          "memory": memory,
1138 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1139 d0c8c01d Iustin Pop
          "state": state,
1140 d0c8c01d Iustin Pop
          "time": times,
1141 e69d05fd Iustin Pop
          }
1142 b33b6f55 Iustin Pop
        if name in output:
1143 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1144 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1145 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1146 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1147 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1148 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1149 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1150 f23b5ae8 Iustin Pop
        output[name] = value
1151 a8083063 Iustin Pop
1152 c26a6bd2 Iustin Pop
  return output
1153 a8083063 Iustin Pop
1154 a8083063 Iustin Pop
1155 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1156 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1157 81a3406c Iustin Pop

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

1161 81a3406c Iustin Pop
  @type kind: string
1162 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1163 81a3406c Iustin Pop
  @type os_name: string
1164 81a3406c Iustin Pop
  @param os_name: the os name
1165 81a3406c Iustin Pop
  @type instance: string
1166 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1167 6aa7a354 Iustin Pop
  @type component: string or None
1168 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1169 6aa7a354 Iustin Pop
      transferred
1170 81a3406c Iustin Pop

1171 81a3406c Iustin Pop
  """
1172 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1173 6aa7a354 Iustin Pop
  if component:
1174 6aa7a354 Iustin Pop
    assert "/" not in component
1175 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1176 6aa7a354 Iustin Pop
  else:
1177 6aa7a354 Iustin Pop
    c_msg = ""
1178 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1179 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1180 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1181 81a3406c Iustin Pop
1182 81a3406c Iustin Pop
1183 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1184 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1185 a8083063 Iustin Pop

1186 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1187 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1188 e557bae9 Guido Trotter
  @type reinstall: boolean
1189 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1190 4a0e011f Iustin Pop
  @type debug: integer
1191 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1192 c26a6bd2 Iustin Pop
  @rtype: None
1193 a8083063 Iustin Pop

1194 a8083063 Iustin Pop
  """
1195 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1196 255dcebd Iustin Pop
1197 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1198 e557bae9 Guido Trotter
  if reinstall:
1199 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1200 a8083063 Iustin Pop
1201 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1202 decd5f45 Iustin Pop
1203 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1204 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1205 decd5f45 Iustin Pop
  if result.failed:
1206 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1207 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1208 18682bca Iustin Pop
                  result.output)
1209 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1210 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1211 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1212 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1213 decd5f45 Iustin Pop
1214 decd5f45 Iustin Pop
1215 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1216 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1217 decd5f45 Iustin Pop

1218 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1219 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1220 d15a9ad3 Guido Trotter
  @type old_name: string
1221 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1222 4a0e011f Iustin Pop
  @type debug: integer
1223 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1224 10c2650b Iustin Pop
  @rtype: boolean
1225 10c2650b Iustin Pop
  @return: the success of the operation
1226 decd5f45 Iustin Pop

1227 decd5f45 Iustin Pop
  """
1228 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1229 decd5f45 Iustin Pop
1230 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1231 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1232 decd5f45 Iustin Pop
1233 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1234 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1235 a8083063 Iustin Pop
1236 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1237 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1238 a8083063 Iustin Pop
1239 a8083063 Iustin Pop
  if result.failed:
1240 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1241 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1242 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1243 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1244 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1245 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1246 a8083063 Iustin Pop
1247 a8083063 Iustin Pop
1248 3b721842 Michael Hanselmann
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1249 3b721842 Michael Hanselmann
  """Returns symlink path for block device.
1250 3b721842 Michael Hanselmann

1251 3b721842 Michael Hanselmann
  """
1252 3b721842 Michael Hanselmann
  if _dir is None:
1253 3b721842 Michael Hanselmann
    _dir = pathutils.DISK_LINKS_DIR
1254 3b721842 Michael Hanselmann
1255 3b721842 Michael Hanselmann
  return utils.PathJoin(_dir,
1256 3b721842 Michael Hanselmann
                        ("%s%s%s" %
1257 3b721842 Michael Hanselmann
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1258 5282084b Iustin Pop
1259 5282084b Iustin Pop
1260 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1261 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1262 9332fd8a Iustin Pop

1263 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1264 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1265 9332fd8a Iustin Pop

1266 9332fd8a Iustin Pop

1267 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1268 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1269 5282084b Iustin Pop
  @param idx: the disk index
1270 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1271 9332fd8a Iustin Pop

1272 9332fd8a Iustin Pop
  """
1273 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1274 9332fd8a Iustin Pop
  try:
1275 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1276 5282084b Iustin Pop
  except OSError, err:
1277 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1278 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1279 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1280 9332fd8a Iustin Pop
        os.remove(link_name)
1281 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1282 9332fd8a Iustin Pop
    else:
1283 9332fd8a Iustin Pop
      raise
1284 9332fd8a Iustin Pop
1285 9332fd8a Iustin Pop
  return link_name
1286 9332fd8a Iustin Pop
1287 9332fd8a Iustin Pop
1288 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1289 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1290 3c9c571d Iustin Pop

1291 3c9c571d Iustin Pop
  """
1292 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1293 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1294 5282084b Iustin Pop
    if os.path.islink(link_name):
1295 3c9c571d Iustin Pop
      try:
1296 03dfa658 Iustin Pop
        os.remove(link_name)
1297 03dfa658 Iustin Pop
      except OSError:
1298 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1299 3c9c571d Iustin Pop
1300 3c9c571d Iustin Pop
1301 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1302 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1303 a8083063 Iustin Pop

1304 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1305 a8083063 Iustin Pop
  devices must be already assembled.
1306 a8083063 Iustin Pop

1307 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1308 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1309 069cfbf1 Iustin Pop
  @rtype: list
1310 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1311 10c2650b Iustin Pop

1312 a8083063 Iustin Pop
  """
1313 a8083063 Iustin Pop
  block_devices = []
1314 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1315 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1316 a8083063 Iustin Pop
    if device is None:
1317 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1318 a8083063 Iustin Pop
                                    str(disk))
1319 a8083063 Iustin Pop
    device.Open()
1320 9332fd8a Iustin Pop
    try:
1321 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1322 9332fd8a Iustin Pop
    except OSError, e:
1323 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1324 9332fd8a Iustin Pop
                                    e.strerror)
1325 9332fd8a Iustin Pop
1326 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1327 9332fd8a Iustin Pop
1328 a8083063 Iustin Pop
  return block_devices
1329 a8083063 Iustin Pop
1330 a8083063 Iustin Pop
1331 323f9095 Stephen Shirley
def StartInstance(instance, startup_paused):
1332 a8083063 Iustin Pop
  """Start an instance.
1333 a8083063 Iustin Pop

1334 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1335 e69d05fd Iustin Pop
  @param instance: the instance object
1336 323f9095 Stephen Shirley
  @type startup_paused: bool
1337 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1338 c26a6bd2 Iustin Pop
  @rtype: None
1339 a8083063 Iustin Pop

1340 098c0958 Michael Hanselmann
  """
1341 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1342 a8083063 Iustin Pop
1343 a8083063 Iustin Pop
  if instance.name in running_instances:
1344 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1345 c26a6bd2 Iustin Pop
    return
1346 a8083063 Iustin Pop
1347 a8083063 Iustin Pop
  try:
1348 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1349 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1350 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1351 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1352 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1353 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1354 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1355 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1356 a8083063 Iustin Pop
1357 a8083063 Iustin Pop
1358 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1359 a8083063 Iustin Pop
  """Shut an instance down.
1360 a8083063 Iustin Pop

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

1363 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1364 e69d05fd Iustin Pop
  @param instance: the instance object
1365 6263189c Guido Trotter
  @type timeout: integer
1366 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1367 c26a6bd2 Iustin Pop
  @rtype: None
1368 a8083063 Iustin Pop

1369 098c0958 Michael Hanselmann
  """
1370 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1371 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1372 c26a6bd2 Iustin Pop
  iname = instance.name
1373 a8083063 Iustin Pop
1374 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1375 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1376 c26a6bd2 Iustin Pop
    return
1377 a8083063 Iustin Pop
1378 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1379 3c0cdc83 Michael Hanselmann
    def __init__(self):
1380 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1381 a8083063 Iustin Pop
1382 3c0cdc83 Michael Hanselmann
    def __call__(self):
1383 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1384 3c0cdc83 Michael Hanselmann
        return
1385 3c0cdc83 Michael Hanselmann
1386 3c0cdc83 Michael Hanselmann
      try:
1387 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1388 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1389 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1390 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1391 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1392 3c0cdc83 Michael Hanselmann
          return
1393 3c0cdc83 Michael Hanselmann
1394 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1395 3c0cdc83 Michael Hanselmann
1396 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1397 3c0cdc83 Michael Hanselmann
1398 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1399 3c0cdc83 Michael Hanselmann
1400 3c0cdc83 Michael Hanselmann
  try:
1401 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1402 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1403 a8083063 Iustin Pop
    # the shutdown did not succeed
1404 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1405 a8083063 Iustin Pop
1406 a8083063 Iustin Pop
    try:
1407 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1408 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1409 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1410 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1411 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1412 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1413 a8083063 Iustin Pop
1414 a8083063 Iustin Pop
    time.sleep(1)
1415 3c0cdc83 Michael Hanselmann
1416 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1417 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1418 3c9c571d Iustin Pop
1419 f28ec899 Guido Trotter
  try:
1420 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1421 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1422 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1423 f28ec899 Guido Trotter
1424 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1425 a8083063 Iustin Pop
1426 a8083063 Iustin Pop
1427 aa922d64 Michele Tartara
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1428 007a2f3e Alexander Schreiber
  """Reboot an instance.
1429 007a2f3e Alexander Schreiber

1430 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1431 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1432 10c2650b Iustin Pop
  @type reboot_type: str
1433 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1434 10c2650b Iustin Pop
    constants:
1435 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1436 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1437 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1438 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1439 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1440 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1441 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1442 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1443 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1444 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1445 c26a6bd2 Iustin Pop
  @rtype: None
1446 007a2f3e Alexander Schreiber

1447 007a2f3e Alexander Schreiber
  """
1448 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1449 007a2f3e Alexander Schreiber
1450 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1451 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1452 007a2f3e Alexander Schreiber
1453 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1454 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1455 007a2f3e Alexander Schreiber
    try:
1456 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1457 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1458 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1459 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1460 007a2f3e Alexander Schreiber
    try:
1461 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1462 4a90bd4f Michele Tartara
      result = StartInstance(instance, False)
1463 4a90bd4f Michele Tartara
      return result
1464 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1465 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1466 007a2f3e Alexander Schreiber
  else:
1467 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1468 007a2f3e Alexander Schreiber
1469 007a2f3e Alexander Schreiber
1470 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1471 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1472 ebe466d8 Guido Trotter

1473 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1474 ebe466d8 Guido Trotter
  @param instance: the instance object
1475 ebe466d8 Guido Trotter
  @type memory: int
1476 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1477 ebe466d8 Guido Trotter
  @rtype: None
1478 ebe466d8 Guido Trotter

1479 ebe466d8 Guido Trotter
  """
1480 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1481 ebe466d8 Guido Trotter
  running = hyper.ListInstances()
1482 ebe466d8 Guido Trotter
  if instance.name not in running:
1483 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1484 ebe466d8 Guido Trotter
    return
1485 ebe466d8 Guido Trotter
  try:
1486 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1487 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1488 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1489 ebe466d8 Guido Trotter
1490 ebe466d8 Guido Trotter
1491 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1492 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1493 6906a9d8 Guido Trotter

1494 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1495 6906a9d8 Guido Trotter
  @param instance: the instance definition
1496 6906a9d8 Guido Trotter

1497 6906a9d8 Guido Trotter
  """
1498 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1499 cd42d0ad Guido Trotter
  try:
1500 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1501 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1502 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1503 c26a6bd2 Iustin Pop
  return info
1504 6906a9d8 Guido Trotter
1505 6906a9d8 Guido Trotter
1506 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1507 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1508 6906a9d8 Guido Trotter

1509 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1510 6906a9d8 Guido Trotter
  @param instance: the instance definition
1511 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1512 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1513 6906a9d8 Guido Trotter
  @type target: string
1514 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1515 6906a9d8 Guido Trotter

1516 6906a9d8 Guido Trotter
  """
1517 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1518 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1519 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1520 77fcff4a Apollon Oikonomopoulos
    # in any way
1521 77fcff4a Apollon Oikonomopoulos
    try:
1522 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1523 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1524 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1525 77fcff4a Apollon Oikonomopoulos
1526 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1527 cd42d0ad Guido Trotter
  try:
1528 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1529 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1530 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1531 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1532 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1533 6906a9d8 Guido Trotter
1534 6906a9d8 Guido Trotter
1535 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1536 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1537 6906a9d8 Guido Trotter

1538 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1539 6906a9d8 Guido Trotter
  @param instance: the instance definition
1540 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1541 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1542 6906a9d8 Guido Trotter
  @type success: boolean
1543 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1544 6906a9d8 Guido Trotter

1545 6906a9d8 Guido Trotter
  """
1546 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1547 cd42d0ad Guido Trotter
  try:
1548 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1549 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1550 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1551 6906a9d8 Guido Trotter
1552 6906a9d8 Guido Trotter
1553 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1554 2a10865c Iustin Pop
  """Migrates an instance to another node.
1555 2a10865c Iustin Pop

1556 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1557 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1558 9f0e6b37 Iustin Pop
  @type target: string
1559 9f0e6b37 Iustin Pop
  @param target: the target node name
1560 9f0e6b37 Iustin Pop
  @type live: boolean
1561 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1562 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1563 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1564 9f0e6b37 Iustin Pop

1565 2a10865c Iustin Pop
  """
1566 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1567 2a10865c Iustin Pop
1568 2a10865c Iustin Pop
  try:
1569 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1570 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1571 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1572 2a10865c Iustin Pop
1573 2a10865c Iustin Pop
1574 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1575 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1576 6a1434d7 Andrea Spadaccini

1577 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1578 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1579 6a1434d7 Andrea Spadaccini
  @type success: bool
1580 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1581 6a1434d7 Andrea Spadaccini
  @type live: bool
1582 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1583 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1584 6a1434d7 Andrea Spadaccini

1585 6a1434d7 Andrea Spadaccini
  """
1586 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1587 6a1434d7 Andrea Spadaccini
1588 6a1434d7 Andrea Spadaccini
  try:
1589 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1590 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1591 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1592 6a1434d7 Andrea Spadaccini
          exc=True)
1593 6a1434d7 Andrea Spadaccini
1594 6a1434d7 Andrea Spadaccini
1595 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1596 6a1434d7 Andrea Spadaccini
  """Get the migration status
1597 6a1434d7 Andrea Spadaccini

1598 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1599 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1600 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1601 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1602 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1603 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1604 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1605 6a1434d7 Andrea Spadaccini

1606 6a1434d7 Andrea Spadaccini
  """
1607 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1608 6a1434d7 Andrea Spadaccini
  try:
1609 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1610 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1611 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1612 6a1434d7 Andrea Spadaccini
1613 6a1434d7 Andrea Spadaccini
1614 ee1478e5 Bernardo Dal Seno
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1615 a8083063 Iustin Pop
  """Creates a block device for an instance.
1616 a8083063 Iustin Pop

1617 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1618 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1619 b1206984 Iustin Pop
  @type size: int
1620 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1621 b1206984 Iustin Pop
  @type owner: str
1622 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1623 b1206984 Iustin Pop
      used for device cache data
1624 b1206984 Iustin Pop
  @type on_primary: boolean
1625 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1626 b1206984 Iustin Pop
  @type info: string
1627 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1628 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1629 ee1478e5 Bernardo Dal Seno
  @type excl_stor: boolean
1630 ee1478e5 Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
1631 b1206984 Iustin Pop

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

1636 a8083063 Iustin Pop
  """
1637 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
1638 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
1639 a8083063 Iustin Pop
  clist = []
1640 a8083063 Iustin Pop
  if disk.children:
1641 a8083063 Iustin Pop
    for child in disk.children:
1642 1063abd1 Iustin Pop
      try:
1643 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1644 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1645 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1646 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1647 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1648 a8083063 Iustin Pop
        # be assembled
1649 1063abd1 Iustin Pop
        try:
1650 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
1651 1063abd1 Iustin Pop
          crdev.Open()
1652 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1653 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1654 a8083063 Iustin Pop
      clist.append(crdev)
1655 a8083063 Iustin Pop
1656 dab69e97 Iustin Pop
  try:
1657 ee1478e5 Bernardo Dal Seno
    device = bdev.Create(disk, clist, excl_stor)
1658 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1659 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1660 6c626518 Iustin Pop
1661 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1662 1063abd1 Iustin Pop
    try:
1663 1063abd1 Iustin Pop
      device.Assemble()
1664 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1665 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1666 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1667 1063abd1 Iustin Pop
      try:
1668 1063abd1 Iustin Pop
        device.Open(force=True)
1669 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1670 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1671 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1672 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1673 a0c3fea1 Michael Hanselmann
1674 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1675 a0c3fea1 Michael Hanselmann
1676 c26a6bd2 Iustin Pop
  return device.unique_id
1677 a8083063 Iustin Pop
1678 a8083063 Iustin Pop
1679 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1680 69dd363f René Nussbaumer
  """This function actually wipes the device.
1681 69dd363f René Nussbaumer

1682 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1683 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1684 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1685 69dd363f René Nussbaumer

1686 69dd363f René Nussbaumer
  """
1687 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
1688 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
1689 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
1690 0188611b Michael Hanselmann
  block_size = 1024 * 1024
1691 0188611b Michael Hanselmann
1692 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1693 0188611b Michael Hanselmann
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1694 da63bb4e René Nussbaumer
         "count=%d" % size]
1695 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1696 69dd363f René Nussbaumer
1697 69dd363f René Nussbaumer
  if result.failed:
1698 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1699 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1700 69dd363f René Nussbaumer
1701 69dd363f René Nussbaumer
1702 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1703 69dd363f René Nussbaumer
  """Wipes a block device.
1704 69dd363f René Nussbaumer

1705 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1706 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1707 da63bb4e René Nussbaumer
  @type offset: int
1708 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1709 da63bb4e René Nussbaumer
  @type size: int
1710 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1711 69dd363f René Nussbaumer

1712 69dd363f René Nussbaumer
  """
1713 69dd363f René Nussbaumer
  try:
1714 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1715 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1716 da63bb4e René Nussbaumer
    rdev = None
1717 da63bb4e René Nussbaumer
1718 da63bb4e René Nussbaumer
  if not rdev:
1719 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1720 da63bb4e René Nussbaumer
1721 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1722 0188611b Michael Hanselmann
  if offset < 0:
1723 0188611b Michael Hanselmann
    _Fail("Negative offset")
1724 0188611b Michael Hanselmann
  if size < 0:
1725 0188611b Michael Hanselmann
    _Fail("Negative size")
1726 da63bb4e René Nussbaumer
  if offset > rdev.size:
1727 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1728 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1729 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1730 69dd363f René Nussbaumer
1731 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1732 69dd363f René Nussbaumer
1733 69dd363f René Nussbaumer
1734 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1735 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1736 5119c79e René Nussbaumer

1737 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1738 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1739 5119c79e René Nussbaumer
  @type pause: bool
1740 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1741 5119c79e René Nussbaumer

1742 5119c79e René Nussbaumer
  """
1743 5119c79e René Nussbaumer
  success = []
1744 5119c79e René Nussbaumer
  for disk in disks:
1745 5119c79e René Nussbaumer
    try:
1746 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1747 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1748 5119c79e René Nussbaumer
      rdev = None
1749 5119c79e René Nussbaumer
1750 5119c79e René Nussbaumer
    if not rdev:
1751 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1752 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1753 5119c79e René Nussbaumer
      continue
1754 5119c79e René Nussbaumer
1755 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1756 5119c79e René Nussbaumer
1757 5119c79e René Nussbaumer
    if result:
1758 5119c79e René Nussbaumer
      success.append((result, None))
1759 5119c79e René Nussbaumer
    else:
1760 5119c79e René Nussbaumer
      if pause:
1761 5119c79e René Nussbaumer
        msg = "Pause"
1762 5119c79e René Nussbaumer
      else:
1763 5119c79e René Nussbaumer
        msg = "Resume"
1764 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1765 5119c79e René Nussbaumer
1766 5119c79e René Nussbaumer
  return success
1767 5119c79e René Nussbaumer
1768 5119c79e René Nussbaumer
1769 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1770 a8083063 Iustin Pop
  """Remove a block device.
1771 a8083063 Iustin Pop

1772 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1773 10c2650b Iustin Pop

1774 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1775 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1776 10c2650b Iustin Pop
  @rtype: boolean
1777 10c2650b Iustin Pop
  @return: the success of the operation
1778 a8083063 Iustin Pop

1779 a8083063 Iustin Pop
  """
1780 e1bc0878 Iustin Pop
  msgs = []
1781 a8083063 Iustin Pop
  try:
1782 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1783 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1784 a8083063 Iustin Pop
    # probably can't attach
1785 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1786 a8083063 Iustin Pop
    rdev = None
1787 a8083063 Iustin Pop
  if rdev is not None:
1788 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1789 e1bc0878 Iustin Pop
    try:
1790 0c6c04ec Iustin Pop
      rdev.Remove()
1791 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1792 e1bc0878 Iustin Pop
      msgs.append(str(err))
1793 c26a6bd2 Iustin Pop
    if not msgs:
1794 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1795 e1bc0878 Iustin Pop
1796 a8083063 Iustin Pop
  if disk.children:
1797 a8083063 Iustin Pop
    for child in disk.children:
1798 c26a6bd2 Iustin Pop
      try:
1799 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1800 c26a6bd2 Iustin Pop
      except RPCFail, err:
1801 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1802 e1bc0878 Iustin Pop
1803 c26a6bd2 Iustin Pop
  if msgs:
1804 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1805 afdc3985 Iustin Pop
1806 a8083063 Iustin Pop
1807 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1808 a8083063 Iustin Pop
  """Activate a block device for an instance.
1809 a8083063 Iustin Pop

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

1812 10c2650b Iustin Pop
  @note: this function is called recursively.
1813 a8083063 Iustin Pop

1814 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1815 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1816 10c2650b Iustin Pop
  @type owner: str
1817 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1818 10c2650b Iustin Pop
  @type as_primary: boolean
1819 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1820 10c2650b Iustin Pop
      read/write
1821 a8083063 Iustin Pop

1822 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1823 10c2650b Iustin Pop
      was assembled)
1824 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1825 10c2650b Iustin Pop
      during the activation of the children or the device
1826 10c2650b Iustin Pop
      itself
1827 a8083063 Iustin Pop

1828 a8083063 Iustin Pop
  """
1829 a8083063 Iustin Pop
  children = []
1830 a8083063 Iustin Pop
  if disk.children:
1831 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1832 fc1dc9d7 Iustin Pop
    if mcn == -1:
1833 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1834 fc1dc9d7 Iustin Pop
    else:
1835 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1836 a8083063 Iustin Pop
    for chld_disk in disk.children:
1837 fc1dc9d7 Iustin Pop
      try:
1838 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1839 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1840 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1841 fc1dc9d7 Iustin Pop
          raise
1842 fc1dc9d7 Iustin Pop
        cdev = None
1843 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1844 1063abd1 Iustin Pop
                      str(err))
1845 fc1dc9d7 Iustin Pop
      children.append(cdev)
1846 a8083063 Iustin Pop
1847 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1848 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
1849 a8083063 Iustin Pop
    result = r_dev
1850 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1851 a8083063 Iustin Pop
      r_dev.Open()
1852 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1853 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1854 3f78eef2 Iustin Pop
1855 a8083063 Iustin Pop
  else:
1856 a8083063 Iustin Pop
    result = True
1857 a8083063 Iustin Pop
  return result
1858 a8083063 Iustin Pop
1859 a8083063 Iustin Pop
1860 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
1861 a8083063 Iustin Pop
  """Activate a block device for an instance.
1862 a8083063 Iustin Pop

1863 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1864 a8083063 Iustin Pop

1865 b1206984 Iustin Pop
  @rtype: str or boolean
1866 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1867 b1206984 Iustin Pop
      C{True} for secondary nodes
1868 a8083063 Iustin Pop

1869 a8083063 Iustin Pop
  """
1870 53c14ef1 Iustin Pop
  try:
1871 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1872 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1873 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
1874 53c14ef1 Iustin Pop
      result = result.dev_path
1875 c417e115 Iustin Pop
      if as_primary:
1876 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
1877 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1878 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1879 c417e115 Iustin Pop
  except OSError, err:
1880 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
1881 afdc3985 Iustin Pop
1882 c26a6bd2 Iustin Pop
  return result
1883 a8083063 Iustin Pop
1884 a8083063 Iustin Pop
1885 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1886 a8083063 Iustin Pop
  """Shut down a block device.
1887 a8083063 Iustin Pop

1888 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1889 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1890 c41eea6e Iustin Pop
  shutdown.
1891 a8083063 Iustin Pop

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

1896 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1897 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1898 10c2650b Iustin Pop
      shutdown
1899 c26a6bd2 Iustin Pop
  @rtype: None
1900 10c2650b Iustin Pop

1901 a8083063 Iustin Pop
  """
1902 cacfd1fd Iustin Pop
  msgs = []
1903 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1904 a8083063 Iustin Pop
  if r_dev is not None:
1905 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1906 cacfd1fd Iustin Pop
    try:
1907 746f7476 Iustin Pop
      r_dev.Shutdown()
1908 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1909 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1910 cacfd1fd Iustin Pop
      msgs.append(str(err))
1911 746f7476 Iustin Pop
1912 a8083063 Iustin Pop
  if disk.children:
1913 a8083063 Iustin Pop
    for child in disk.children:
1914 c26a6bd2 Iustin Pop
      try:
1915 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1916 c26a6bd2 Iustin Pop
      except RPCFail, err:
1917 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1918 746f7476 Iustin Pop
1919 c26a6bd2 Iustin Pop
  if msgs:
1920 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1921 a8083063 Iustin Pop
1922 a8083063 Iustin Pop
1923 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1924 153d9724 Iustin Pop
  """Extend a mirrored block device.
1925 a8083063 Iustin Pop

1926 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1927 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1928 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1929 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1930 c26a6bd2 Iustin Pop
  @rtype: None
1931 10c2650b Iustin Pop

1932 a8083063 Iustin Pop
  """
1933 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1934 153d9724 Iustin Pop
  if parent_bdev is None:
1935 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1936 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1937 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1938 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1939 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1940 a8083063 Iustin Pop
1941 a8083063 Iustin Pop
1942 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1943 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1944 a8083063 Iustin Pop

1945 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1946 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1947 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1948 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1949 c26a6bd2 Iustin Pop
  @rtype: None
1950 10c2650b Iustin Pop

1951 a8083063 Iustin Pop
  """
1952 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1953 153d9724 Iustin Pop
  if parent_bdev is None:
1954 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1955 e739bd57 Iustin Pop
  devs = []
1956 e739bd57 Iustin Pop
  for disk in new_cdevs:
1957 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1958 e739bd57 Iustin Pop
    if rpath is None:
1959 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1960 e739bd57 Iustin Pop
      if bd is None:
1961 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1962 e739bd57 Iustin Pop
      else:
1963 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1964 e739bd57 Iustin Pop
    else:
1965 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1966 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1967 e739bd57 Iustin Pop
      devs.append(rpath)
1968 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1969 a8083063 Iustin Pop
1970 a8083063 Iustin Pop
1971 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1972 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1973 a8083063 Iustin Pop

1974 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1975 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1976 10c2650b Iustin Pop
  @rtype: disk
1977 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
1978 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1979 10c2650b Iustin Pop
      found
1980 a8083063 Iustin Pop

1981 a8083063 Iustin Pop
  """
1982 a8083063 Iustin Pop
  stats = []
1983 a8083063 Iustin Pop
  for dsk in disks:
1984 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1985 a8083063 Iustin Pop
    if rbd is None:
1986 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1987 96acbc09 Michael Hanselmann
1988 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1989 96acbc09 Michael Hanselmann
1990 c26a6bd2 Iustin Pop
  return stats
1991 a8083063 Iustin Pop
1992 a8083063 Iustin Pop
1993 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
1994 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
1995 c6a9dffa Michael Hanselmann

1996 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
1997 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
1998 c6a9dffa Michael Hanselmann
  @rtype: disk
1999 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2000 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
2001 c6a9dffa Michael Hanselmann
    otherwise
2002 c6a9dffa Michael Hanselmann

2003 c6a9dffa Michael Hanselmann
  """
2004 c6a9dffa Michael Hanselmann
  result = []
2005 c6a9dffa Michael Hanselmann
  for disk in disks:
2006 c6a9dffa Michael Hanselmann
    try:
2007 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
2008 c6a9dffa Michael Hanselmann
      if rbd is None:
2009 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
2010 c6a9dffa Michael Hanselmann
        continue
2011 c6a9dffa Michael Hanselmann
2012 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
2013 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
2014 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
2015 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
2016 c6a9dffa Michael Hanselmann
    else:
2017 c6a9dffa Michael Hanselmann
      result.append((True, status))
2018 c6a9dffa Michael Hanselmann
2019 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
2020 c6a9dffa Michael Hanselmann
2021 c6a9dffa Michael Hanselmann
  return result
2022 c6a9dffa Michael Hanselmann
2023 c6a9dffa Michael Hanselmann
2024 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
2025 a8083063 Iustin Pop
  """Check if a device is activated.
2026 a8083063 Iustin Pop

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

2029 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2030 10c2650b Iustin Pop
  @param disk: the disk object we need to find
2031 a8083063 Iustin Pop

2032 10c2650b Iustin Pop
  @return: None if the device can't be found,
2033 10c2650b Iustin Pop
      otherwise the device instance
2034 a8083063 Iustin Pop

2035 a8083063 Iustin Pop
  """
2036 a8083063 Iustin Pop
  children = []
2037 a8083063 Iustin Pop
  if disk.children:
2038 a8083063 Iustin Pop
    for chdisk in disk.children:
2039 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
2040 a8083063 Iustin Pop
2041 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
2042 a8083063 Iustin Pop
2043 a8083063 Iustin Pop
2044 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
2045 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
2046 f2e07bb4 Michael Hanselmann

2047 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
2048 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
2049 f2e07bb4 Michael Hanselmann

2050 f2e07bb4 Michael Hanselmann
  """
2051 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
2052 f2e07bb4 Michael Hanselmann
  if real_disk is None:
2053 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
2054 f2e07bb4 Michael Hanselmann
2055 f2e07bb4 Michael Hanselmann
  real_disk.Open()
2056 f2e07bb4 Michael Hanselmann
2057 f2e07bb4 Michael Hanselmann
  return real_disk
2058 f2e07bb4 Michael Hanselmann
2059 f2e07bb4 Michael Hanselmann
2060 821d1bd1 Iustin Pop
def BlockdevFind(disk):
2061 a8083063 Iustin Pop
  """Check if a device is activated.
2062 a8083063 Iustin Pop

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

2065 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2066 10c2650b Iustin Pop
  @param disk: the disk to find
2067 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2068 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2069 96acbc09 Michael Hanselmann
           information
2070 a8083063 Iustin Pop

2071 a8083063 Iustin Pop
  """
2072 23829f6f Iustin Pop
  try:
2073 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
2074 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
2075 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
2076 96acbc09 Michael Hanselmann
2077 a8083063 Iustin Pop
  if rbd is None:
2078 c26a6bd2 Iustin Pop
    return None
2079 96acbc09 Michael Hanselmann
2080 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2081 a8083063 Iustin Pop
2082 a8083063 Iustin Pop
2083 968a7623 Iustin Pop
def BlockdevGetsize(disks):
2084 968a7623 Iustin Pop
  """Computes the size of the given disks.
2085 968a7623 Iustin Pop

2086 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2087 968a7623 Iustin Pop

2088 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2089 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2090 968a7623 Iustin Pop
  @rtype: list
2091 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2092 968a7623 Iustin Pop
      otherwise the size
2093 968a7623 Iustin Pop

2094 968a7623 Iustin Pop
  """
2095 968a7623 Iustin Pop
  result = []
2096 968a7623 Iustin Pop
  for cf in disks:
2097 968a7623 Iustin Pop
    try:
2098 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2099 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2100 968a7623 Iustin Pop
      result.append(None)
2101 968a7623 Iustin Pop
      continue
2102 968a7623 Iustin Pop
    if rbd is None:
2103 968a7623 Iustin Pop
      result.append(None)
2104 968a7623 Iustin Pop
    else:
2105 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
2106 968a7623 Iustin Pop
  return result
2107 968a7623 Iustin Pop
2108 968a7623 Iustin Pop
2109 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2110 858f3d18 Iustin Pop
  """Export a block device to a remote node.
2111 858f3d18 Iustin Pop

2112 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
2113 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
2114 858f3d18 Iustin Pop
  @type dest_node: str
2115 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
2116 858f3d18 Iustin Pop
  @type dest_path: str
2117 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
2118 858f3d18 Iustin Pop
  @type cluster_name: str
2119 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2120 858f3d18 Iustin Pop
  @rtype: None
2121 858f3d18 Iustin Pop

2122 858f3d18 Iustin Pop
  """
2123 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
2124 858f3d18 Iustin Pop
2125 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
2126 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2127 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
2128 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
2129 858f3d18 Iustin Pop
2130 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
2131 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
2132 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
2133 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2134 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
2135 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
2136 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2137 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
2138 858f3d18 Iustin Pop
2139 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2140 052783ff Michael Hanselmann
                                                   constants.SSH_LOGIN_USER,
2141 858f3d18 Iustin Pop
                                                   destcmd)
2142 858f3d18 Iustin Pop
2143 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
2144 d0c8c01d Iustin Pop
  command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2145 858f3d18 Iustin Pop
2146 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
2147 858f3d18 Iustin Pop
2148 858f3d18 Iustin Pop
  if result.failed:
2149 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
2150 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
2151 858f3d18 Iustin Pop
2152 858f3d18 Iustin Pop
2153 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2154 a8083063 Iustin Pop
  """Write a file to the filesystem.
2155 a8083063 Iustin Pop

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

2159 10c2650b Iustin Pop
  @type file_name: str
2160 10c2650b Iustin Pop
  @param file_name: the target file name
2161 10c2650b Iustin Pop
  @type data: str
2162 10c2650b Iustin Pop
  @param data: the new contents of the file
2163 10c2650b Iustin Pop
  @type mode: int
2164 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2165 9a914f7a René Nussbaumer
  @type uid: string
2166 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2167 9a914f7a René Nussbaumer
  @type gid: string
2168 9a914f7a René Nussbaumer
  @param gid: the group of the file
2169 10c2650b Iustin Pop
  @type atime: float
2170 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2171 10c2650b Iustin Pop
  @type mtime: float
2172 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2173 c26a6bd2 Iustin Pop
  @rtype: None
2174 10c2650b Iustin Pop

2175 a8083063 Iustin Pop
  """
2176 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2177 cffbbae7 Michael Hanselmann
2178 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2179 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2180 a8083063 Iustin Pop
2181 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2182 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2183 2cc6781a Iustin Pop
          file_name)
2184 a8083063 Iustin Pop
2185 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2186 12bce260 Michael Hanselmann
2187 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2188 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2189 9a914f7a René Nussbaumer
2190 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2191 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2192 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2193 9a914f7a René Nussbaumer
2194 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2195 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2196 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2197 a8083063 Iustin Pop
2198 386b57af Iustin Pop
2199 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2200 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2201 b2f29800 René Nussbaumer

2202 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2203 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2204 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2205 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2206 b2f29800 René Nussbaumer

2207 b2f29800 René Nussbaumer
  @return: stdout
2208 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2209 b2f29800 René Nussbaumer

2210 b2f29800 René Nussbaumer
  """
2211 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2212 b2f29800 René Nussbaumer
2213 b2f29800 René Nussbaumer
  if result.failed:
2214 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2215 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2216 b2f29800 René Nussbaumer
2217 b2f29800 René Nussbaumer
  return result.stdout
2218 b2f29800 René Nussbaumer
2219 b2f29800 René Nussbaumer
2220 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2221 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2222 a8083063 Iustin Pop

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

2226 10c2650b Iustin Pop
  @type os_dir: str
2227 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2228 8e70b181 Iustin Pop
  @rtype: tuple
2229 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2230 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2231 a8083063 Iustin Pop

2232 a8083063 Iustin Pop
  """
2233 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2234 a8083063 Iustin Pop
2235 a8083063 Iustin Pop
  try:
2236 a8083063 Iustin Pop
    st = os.stat(api_file)
2237 a8083063 Iustin Pop
  except EnvironmentError, err:
2238 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2239 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2240 a8083063 Iustin Pop
2241 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2242 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2243 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2244 a8083063 Iustin Pop
2245 a8083063 Iustin Pop
  try:
2246 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2247 a8083063 Iustin Pop
  except EnvironmentError, err:
2248 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2249 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2250 a8083063 Iustin Pop
2251 a8083063 Iustin Pop
  try:
2252 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2253 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2254 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2255 255dcebd Iustin Pop
                   str(err))
2256 a8083063 Iustin Pop
2257 255dcebd Iustin Pop
  return True, api_versions
2258 a8083063 Iustin Pop
2259 386b57af Iustin Pop
2260 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2261 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2262 a8083063 Iustin Pop

2263 10c2650b Iustin Pop
  @type top_dirs: list
2264 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2265 10c2650b Iustin Pop
      search (if not given defaults to
2266 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2267 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2268 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2269 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2270 bad78e66 Iustin Pop
      search paths, where:
2271 255dcebd Iustin Pop
          - name is the (potential) OS name
2272 255dcebd Iustin Pop
          - path is the full path to the OS
2273 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2274 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2275 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2276 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2277 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2278 a8083063 Iustin Pop

2279 a8083063 Iustin Pop
  """
2280 7c3d51d4 Guido Trotter
  if top_dirs is None:
2281 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2282 a8083063 Iustin Pop
2283 a8083063 Iustin Pop
  result = []
2284 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2285 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2286 7c3d51d4 Guido Trotter
      try:
2287 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2288 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2289 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2290 7c3d51d4 Guido Trotter
        break
2291 7c3d51d4 Guido Trotter
      for name in f_names:
2292 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2293 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2294 255dcebd Iustin Pop
        if status:
2295 255dcebd Iustin Pop
          diagnose = ""
2296 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2297 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2298 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2299 255dcebd Iustin Pop
        else:
2300 255dcebd Iustin Pop
          diagnose = os_inst
2301 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2302 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2303 bad78e66 Iustin Pop
                       parameters, api_versions))
2304 a8083063 Iustin Pop
2305 c26a6bd2 Iustin Pop
  return result
2306 a8083063 Iustin Pop
2307 a8083063 Iustin Pop
2308 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2309 a8083063 Iustin Pop
  """Create an OS instance from disk.
2310 a8083063 Iustin Pop

2311 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2312 8e70b181 Iustin Pop
  valid OS name.
2313 a8083063 Iustin Pop

2314 8ee4dc80 Guido Trotter
  @type base_dir: string
2315 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2316 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2317 255dcebd Iustin Pop
  @rtype: tuple
2318 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2319 255dcebd Iustin Pop
      or error message
2320 7c3d51d4 Guido Trotter

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

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

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

2418 255dcebd Iustin Pop
  @type base_dir: string
2419 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2420 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2421 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2422 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2423 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2424 255dcebd Iustin Pop

2425 255dcebd Iustin Pop
  """
2426 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2427 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2428 255dcebd Iustin Pop
2429 255dcebd Iustin Pop
  if not status:
2430 255dcebd Iustin Pop
    _Fail(payload)
2431 a8083063 Iustin Pop
2432 255dcebd Iustin Pop
  return payload
2433 a8083063 Iustin Pop
2434 a8083063 Iustin Pop
2435 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2436 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2437 2266edb2 Guido Trotter

2438 a025e535 Vitaly Kuznetsov
  @type os_name: str
2439 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2440 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2441 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2442 1bdcbbab Iustin Pop
  @type os_params: dict
2443 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2444 2266edb2 Guido Trotter
  @type debug: integer
2445 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2446 2266edb2 Guido Trotter
  @rtype: dict
2447 2266edb2 Guido Trotter
  @return: dict of environment variables
2448 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2449 10c2650b Iustin Pop
      cannot be found
2450 2266edb2 Guido Trotter

2451 2266edb2 Guido Trotter
  """
2452 2266edb2 Guido Trotter
  result = {}
2453 099c52ad Iustin Pop
  api_version = \
2454 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2455 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2456 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2457 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2458 efaa9b06 Iustin Pop
2459 efaa9b06 Iustin Pop
  # OS variants
2460 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2461 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2462 870dc44c Iustin Pop
    if not variant:
2463 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2464 35007011 Iustin Pop
  else:
2465 35007011 Iustin Pop
    variant = ""
2466 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2467 efaa9b06 Iustin Pop
2468 1bdcbbab Iustin Pop
  # OS params
2469 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2470 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2471 1bdcbbab Iustin Pop
2472 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
2473 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
2474 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
2475 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
2476 9a6ade06 Iustin Pop
2477 efaa9b06 Iustin Pop
  return result
2478 efaa9b06 Iustin Pop
2479 efaa9b06 Iustin Pop
2480 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2481 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2482 efaa9b06 Iustin Pop

2483 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2484 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2485 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2486 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2487 efaa9b06 Iustin Pop
  @type debug: integer
2488 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2489 efaa9b06 Iustin Pop
  @rtype: dict
2490 efaa9b06 Iustin Pop
  @return: dict of environment variables
2491 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2492 efaa9b06 Iustin Pop
      cannot be found
2493 efaa9b06 Iustin Pop

2494 efaa9b06 Iustin Pop
  """
2495 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2496 efaa9b06 Iustin Pop
2497 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2498 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2499 f2165b8a Iustin Pop
2500 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2501 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2502 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2503 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2504 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2505 efaa9b06 Iustin Pop
2506 efaa9b06 Iustin Pop
  # Disks
2507 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2508 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2509 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2510 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2511 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2512 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2513 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2514 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2515 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2516 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2517 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2518 d0c8c01d Iustin Pop
        "file:%s" % disk.physical_id[0]
2519 efaa9b06 Iustin Pop
2520 efaa9b06 Iustin Pop
  # NICs
2521 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2522 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2523 2266edb2 Guido Trotter
    if nic.ip:
2524 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2525 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2526 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2527 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2528 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2529 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2530 d89168ff Guido Trotter
    if nic.netinfo:
2531 d89168ff Guido Trotter
      nobj = objects.Network.FromDict(nic.netinfo)
2532 d89168ff Guido Trotter
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2533 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2534 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2535 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2536 2266edb2 Guido Trotter
2537 efaa9b06 Iustin Pop
  # HV/BE params
2538 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2539 67fc3042 Iustin Pop
    for key, value in source.items():
2540 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2541 67fc3042 Iustin Pop
2542 2266edb2 Guido Trotter
  return result
2543 a8083063 Iustin Pop
2544 f2e07bb4 Michael Hanselmann
2545 b954f097 Constantinos Venetsanopoulos
def DiagnoseExtStorage(top_dirs=None):
2546 b954f097 Constantinos Venetsanopoulos
  """Compute the validity for all ExtStorage Providers.
2547 b954f097 Constantinos Venetsanopoulos

2548 b954f097 Constantinos Venetsanopoulos
  @type top_dirs: list
2549 b954f097 Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
2550 b954f097 Constantinos Venetsanopoulos
      search (if not given defaults to
2551 b954f097 Constantinos Venetsanopoulos
      L{pathutils.ES_SEARCH_PATH})
2552 b954f097 Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
2553 b954f097 Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
2554 b954f097 Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
2555 b954f097 Constantinos Venetsanopoulos
      search paths, where:
2556 b954f097 Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
2557 b954f097 Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
2558 b954f097 Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
2559 b954f097 Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
2560 b954f097 Constantinos Venetsanopoulos
            otherwise empty
2561 b954f097 Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
2562 b954f097 Constantinos Venetsanopoulos

2563 b954f097 Constantinos Venetsanopoulos
  """
2564 b954f097 Constantinos Venetsanopoulos
  if top_dirs is None:
2565 b954f097 Constantinos Venetsanopoulos
    top_dirs = pathutils.ES_SEARCH_PATH
2566 b954f097 Constantinos Venetsanopoulos
2567 b954f097 Constantinos Venetsanopoulos
  result = []
2568 b954f097 Constantinos Venetsanopoulos
  for dir_name in top_dirs:
2569 b954f097 Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
2570 b954f097 Constantinos Venetsanopoulos
      try:
2571 b954f097 Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
2572 b954f097 Constantinos Venetsanopoulos
      except EnvironmentError, err:
2573 b954f097 Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
2574 b954f097 Constantinos Venetsanopoulos
                          dir_name, err)
2575 b954f097 Constantinos Venetsanopoulos
        break
2576 b954f097 Constantinos Venetsanopoulos
      for name in f_names:
2577 b954f097 Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
2578 b954f097 Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2579 b954f097 Constantinos Venetsanopoulos
        if status:
2580 b954f097 Constantinos Venetsanopoulos
          diagnose = ""
2581 b954f097 Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
2582 b954f097 Constantinos Venetsanopoulos
        else:
2583 b954f097 Constantinos Venetsanopoulos
          diagnose = es_inst
2584 b954f097 Constantinos Venetsanopoulos
          parameters = []
2585 b954f097 Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
2586 b954f097 Constantinos Venetsanopoulos
2587 b954f097 Constantinos Venetsanopoulos
  return result
2588 b954f097 Constantinos Venetsanopoulos
2589 b954f097 Constantinos Venetsanopoulos
2590 cad0723b Iustin Pop
def BlockdevGrow(disk, amount, dryrun, backingstore):
2591 594609c0 Iustin Pop
  """Grow a stack of block devices.
2592 594609c0 Iustin Pop

2593 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2594 10c2650b Iustin Pop
  first ones to resize.
2595 594609c0 Iustin Pop

2596 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2597 10c2650b Iustin Pop
  @param disk: the disk to be grown
2598 a59faf4b Iustin Pop
  @type amount: integer
2599 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2600 a59faf4b Iustin Pop
  @type dryrun: boolean
2601 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2602 a59faf4b Iustin Pop
      only, without actually increasing the size
2603 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
2604 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2605 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
2606 10c2650b Iustin Pop
  @rtype: (status, result)
2607 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2608 a59faf4b Iustin Pop
      the errors message if status is False
2609 594609c0 Iustin Pop

2610 594609c0 Iustin Pop
  """
2611 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2612 594609c0 Iustin Pop
  if r_dev is None:
2613 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2614 594609c0 Iustin Pop
2615 594609c0 Iustin Pop
  try:
2616 cad0723b Iustin Pop
    r_dev.Grow(amount, dryrun, backingstore)
2617 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2618 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2619 594609c0 Iustin Pop
2620 594609c0 Iustin Pop
2621 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2622 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2623 a8083063 Iustin Pop

2624 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2625 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2626 a8083063 Iustin Pop

2627 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2628 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2629 e9e9263d Guido Trotter
  @rtype: string
2630 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2631 a8083063 Iustin Pop

2632 098c0958 Michael Hanselmann
  """
2633 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2634 433c63aa Iustin Pop
    if not disk.children:
2635 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2636 433c63aa Iustin Pop
            disk.unique_id)
2637 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2638 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2639 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2640 a8083063 Iustin Pop
    if r_dev is not None:
2641 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2642 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2643 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2644 a8083063 Iustin Pop
    else:
2645 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2646 a8083063 Iustin Pop
  else:
2647 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2648 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2649 a8083063 Iustin Pop
2650 a8083063 Iustin Pop
2651 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
2652 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
2653 48e175a2 Iustin Pop

2654 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
2655 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
2656 48e175a2 Iustin Pop
  for example after renames.
2657 48e175a2 Iustin Pop

2658 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
2659 48e175a2 Iustin Pop
  @param disk: the disk to be grown
2660 48e175a2 Iustin Pop
  @type info: string
2661 48e175a2 Iustin Pop
  @param info: new 'info' metadata
2662 48e175a2 Iustin Pop
  @rtype: (status, result)
2663 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2664 48e175a2 Iustin Pop
      the errors message if status is False
2665 48e175a2 Iustin Pop

2666 48e175a2 Iustin Pop
  """
2667 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2668 48e175a2 Iustin Pop
  if r_dev is None:
2669 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2670 48e175a2 Iustin Pop
2671 48e175a2 Iustin Pop
  try:
2672 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
2673 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
2674 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
2675 48e175a2 Iustin Pop
2676 48e175a2 Iustin Pop
2677 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2678 a8083063 Iustin Pop
  """Write out the export configuration information.
2679 a8083063 Iustin Pop

2680 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2681 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2682 10c2650b Iustin Pop
      saving configuration
2683 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2684 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2685 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2686 a8083063 Iustin Pop

2687 c26a6bd2 Iustin Pop
  @rtype: None
2688 a8083063 Iustin Pop

2689 098c0958 Michael Hanselmann
  """
2690 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2691 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2692 a8083063 Iustin Pop
2693 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2694 a8083063 Iustin Pop
2695 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2696 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
2697 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2698 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2699 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
2700 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2701 a8083063 Iustin Pop
2702 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2703 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
2704 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2705 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2706 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
2707 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
2708 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2709 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
2710 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2711 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2712 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2713 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2714 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2715 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2716 66f93869 Manuel Franceschini
2717 95268cc3 Iustin Pop
  nic_total = 0
2718 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2719 95268cc3 Iustin Pop
    nic_total += 1
2720 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
2721 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
2722 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2723 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2724 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
2725 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2726 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2727 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
2728 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2729 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2730 a8083063 Iustin Pop
2731 726d7d68 Iustin Pop
  disk_total = 0
2732 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2733 19d7f90a Guido Trotter
    if disk:
2734 726d7d68 Iustin Pop
      disk_total += 1
2735 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2736 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
2737 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2738 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
2739 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2740 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
2741 d0c8c01d Iustin Pop
2742 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2743 a8083063 Iustin Pop
2744 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2745 3c8954ad Iustin Pop
2746 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2747 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2748 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2749 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2750 3c8954ad Iustin Pop
2751 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2752 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2753 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2754 3c8954ad Iustin Pop
2755 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2756 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2757 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2758 535b49cb Iustin Pop
2759 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2760 726d7d68 Iustin Pop
                  data=config.Dumps())
2761 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2762 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2763 a8083063 Iustin Pop
2764 a8083063 Iustin Pop
2765 a8083063 Iustin Pop
def ExportInfo(dest):
2766 a8083063 Iustin Pop
  """Get export configuration information.
2767 a8083063 Iustin Pop

2768 10c2650b Iustin Pop
  @type dest: str
2769 10c2650b Iustin Pop
  @param dest: directory containing the export
2770 a8083063 Iustin Pop

2771 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2772 10c2650b Iustin Pop
  @return: a serializable config file containing the
2773 10c2650b Iustin Pop
      export info
2774 a8083063 Iustin Pop

2775 a8083063 Iustin Pop
  """
2776 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2777 a8083063 Iustin Pop
2778 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2779 a8083063 Iustin Pop
  config.read(cff)
2780 a8083063 Iustin Pop
2781 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2782 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2783 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2784 a8083063 Iustin Pop
2785 c26a6bd2 Iustin Pop
  return config.Dumps()
2786 a8083063 Iustin Pop
2787 a8083063 Iustin Pop
2788 a8083063 Iustin Pop
def ListExports():
2789 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2790 098c0958 Michael Hanselmann

2791 10c2650b Iustin Pop
  @rtype: list
2792 10c2650b Iustin Pop
  @return: list of the exports
2793 10c2650b Iustin Pop

2794 a8083063 Iustin Pop
  """
2795 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
2796 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2797 a8083063 Iustin Pop
  else:
2798 afdc3985 Iustin Pop
    _Fail("No exports directory")
2799 a8083063 Iustin Pop
2800 a8083063 Iustin Pop
2801 a8083063 Iustin Pop
def RemoveExport(export):
2802 a8083063 Iustin Pop
  """Remove an existing export from the node.
2803 a8083063 Iustin Pop

2804 10c2650b Iustin Pop
  @type export: str
2805 10c2650b Iustin Pop
  @param export: the name of the export to remove
2806 c26a6bd2 Iustin Pop
  @rtype: None
2807 a8083063 Iustin Pop

2808 098c0958 Michael Hanselmann
  """
2809 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2810 a8083063 Iustin Pop
2811 35fbcd11 Iustin Pop
  try:
2812 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2813 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2814 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2815 a8083063 Iustin Pop
2816 a8083063 Iustin Pop
2817 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2818 f3e513ad Iustin Pop
  """Rename a list of block devices.
2819 f3e513ad Iustin Pop

2820 10c2650b Iustin Pop
  @type devlist: list of tuples
2821 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2822 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2823 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2824 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2825 10c2650b Iustin Pop
      rename it to
2826 10c2650b Iustin Pop
  @rtype: boolean
2827 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2828 f3e513ad Iustin Pop

2829 f3e513ad Iustin Pop
  """
2830 6b5e3f70 Iustin Pop
  msgs = []
2831 f3e513ad Iustin Pop
  result = True
2832 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2833 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2834 f3e513ad Iustin Pop
    if dev is None:
2835 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2836 f3e513ad Iustin Pop
      result = False
2837 f3e513ad Iustin Pop
      continue
2838 f3e513ad Iustin Pop
    try:
2839 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2840 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2841 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2842 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2843 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2844 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2845 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2846 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2847 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2848 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2849 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2850 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2851 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2852 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2853 f3e513ad Iustin Pop
      result = False
2854 afdc3985 Iustin Pop
  if not result:
2855 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2856 f3e513ad Iustin Pop
2857 f3e513ad Iustin Pop
2858 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2859 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2860 778b75bb Manuel Franceschini

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

2865 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2866 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2867 d61cbe76 Iustin Pop

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

2870 778b75bb Manuel Franceschini
  """
2871 63a3d8f7 Michael Hanselmann
  if not (constants.ENABLE_FILE_STORAGE or
2872 63a3d8f7 Michael Hanselmann
          constants.ENABLE_SHARED_FILE_STORAGE):
2873 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2874 5e09a309 Michael Hanselmann
2875 5e09a309 Michael Hanselmann
  bdev.CheckFileStoragePath(fs_dir)
2876 5e09a309 Michael Hanselmann
2877 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
2878 778b75bb Manuel Franceschini
2879 778b75bb Manuel Franceschini
2880 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2881 778b75bb Manuel Franceschini
  """Create file storage directory.
2882 778b75bb Manuel Franceschini

2883 b1206984 Iustin Pop
  @type file_storage_dir: str
2884 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2885 778b75bb Manuel Franceschini

2886 b1206984 Iustin Pop
  @rtype: tuple
2887 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2888 b1206984 Iustin Pop
      creation was successful or not
2889 778b75bb Manuel Franceschini

2890 778b75bb Manuel Franceschini
  """
2891 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2892 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2893 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2894 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2895 b2b8bcce Iustin Pop
            file_storage_dir)
2896 778b75bb Manuel Franceschini
  else:
2897 b2b8bcce Iustin Pop
    try:
2898 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2899 b2b8bcce Iustin Pop
    except OSError, err:
2900 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2901 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2902 778b75bb Manuel Franceschini
2903 778b75bb Manuel Franceschini
2904 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2905 778b75bb Manuel Franceschini
  """Remove file storage directory.
2906 778b75bb Manuel Franceschini

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

2909 10c2650b Iustin Pop
  @type file_storage_dir: str
2910 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2911 10c2650b Iustin Pop
  @rtype: tuple (success,)
2912 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2913 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2914 778b75bb Manuel Franceschini

2915 778b75bb Manuel Franceschini
  """
2916 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2917 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2918 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2919 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2920 b2b8bcce Iustin Pop
            file_storage_dir)
2921 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2922 b2b8bcce Iustin Pop
    try:
2923 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2924 b2b8bcce Iustin Pop
    except OSError, err:
2925 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2926 b2b8bcce Iustin Pop
            file_storage_dir, err)
2927 b2b8bcce Iustin Pop
2928 778b75bb Manuel Franceschini
2929 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2930 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2931 778b75bb Manuel Franceschini

2932 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2933 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2934 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2935 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2936 10c2650b Iustin Pop
  @rtype: tuple (success,)
2937 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2938 10c2650b Iustin Pop
      whether the operation was successful
2939 778b75bb Manuel Franceschini

2940 778b75bb Manuel Franceschini
  """
2941 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2942 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2943 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2944 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2945 b2b8bcce Iustin Pop
      try:
2946 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2947 b2b8bcce Iustin Pop
      except OSError, err:
2948 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2949 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2950 778b75bb Manuel Franceschini
    else:
2951 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2952 b2b8bcce Iustin Pop
            old_file_storage_dir)
2953 b2b8bcce Iustin Pop
  else:
2954 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2955 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2956 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2957 778b75bb Manuel Franceschini
2958 778b75bb Manuel Franceschini
2959 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2960 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2961 ca52cdeb Michael Hanselmann

2962 10c2650b Iustin Pop
  @type file_name: str
2963 10c2650b Iustin Pop
  @param file_name: the file name we should check
2964 c8457ce7 Iustin Pop
  @rtype: None
2965 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2966 10c2650b Iustin Pop

2967 ca52cdeb Michael Hanselmann
  """
2968 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2969 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2970 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2971 dc31eae3 Michael Hanselmann
2972 dc31eae3 Michael Hanselmann
2973 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2974 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2975 dc31eae3 Michael Hanselmann

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

2979 10c2650b Iustin Pop
  @type file_name: str
2980 10c2650b Iustin Pop
  @param file_name: the job file name
2981 10c2650b Iustin Pop
  @type content: str
2982 10c2650b Iustin Pop
  @param content: the new job contents
2983 10c2650b Iustin Pop
  @rtype: boolean
2984 10c2650b Iustin Pop
  @return: the success of the operation
2985 10c2650b Iustin Pop

2986 dc31eae3 Michael Hanselmann
  """
2987 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2988 cffbbae7 Michael Hanselmann
2989 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2990 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
2991 ca52cdeb Michael Hanselmann
2992 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2993 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2994 fe05a931 Michele Tartara
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
2995 ca52cdeb Michael Hanselmann
2996 ca52cdeb Michael Hanselmann
2997 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2998 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2999 af5ebcb1 Michael Hanselmann

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

3002 10c2650b Iustin Pop
  @type old: str
3003 10c2650b Iustin Pop
  @param old: the old (actual) file name
3004 10c2650b Iustin Pop
  @type new: str
3005 10c2650b Iustin Pop
  @param new: the desired file name
3006 c8457ce7 Iustin Pop
  @rtype: tuple
3007 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
3008 10c2650b Iustin Pop

3009 af5ebcb1 Michael Hanselmann
  """
3010 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
3011 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
3012 cffbbae7 Michael Hanselmann
3013 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
3014 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
3015 af5ebcb1 Michael Hanselmann
3016 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
3017 8e5a705d René Nussbaumer
3018 fe05a931 Michele Tartara
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3019 fe05a931 Michele Tartara
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3020 af5ebcb1 Michael Hanselmann
3021 af5ebcb1 Michael Hanselmann
3022 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
3023 d61cbe76 Iustin Pop
  """Closes the given block devices.
3024 d61cbe76 Iustin Pop

3025 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
3026 10c2650b Iustin Pop
  DRBD).
3027 10c2650b Iustin Pop

3028 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
3029 b2e7666a Iustin Pop
      of this instance will be removed
3030 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
3031 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
3032 10c2650b Iustin Pop
  @rtype: tuple (success, message)
3033 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
3034 10c2650b Iustin Pop
      indicates the succes of the operation, and message
3035 10c2650b Iustin Pop
      which will contain the error details in case we
3036 10c2650b Iustin Pop
      failed
3037 d61cbe76 Iustin Pop

3038 d61cbe76 Iustin Pop
  """
3039 d61cbe76 Iustin Pop
  bdevs = []
3040 d61cbe76 Iustin Pop
  for cf in disks:
3041 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
3042 d61cbe76 Iustin Pop
    if rd is None:
3043 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
3044 d61cbe76 Iustin Pop
    bdevs.append(rd)
3045 d61cbe76 Iustin Pop
3046 d61cbe76 Iustin Pop
  msg = []
3047 d61cbe76 Iustin Pop
  for rd in bdevs:
3048 d61cbe76 Iustin Pop
    try:
3049 d61cbe76 Iustin Pop
      rd.Close()
3050 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
3051 d61cbe76 Iustin Pop
      msg.append(str(err))
3052 d61cbe76 Iustin Pop
  if msg:
3053 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3054 d61cbe76 Iustin Pop
  else:
3055 b2e7666a Iustin Pop
    if instance_name:
3056 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
3057 d61cbe76 Iustin Pop
3058 d61cbe76 Iustin Pop
3059 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
3060 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
3061 6217e295 Iustin Pop

3062 6217e295 Iustin Pop
  @type hvname: string
3063 6217e295 Iustin Pop
  @param hvname: the hypervisor name
3064 6217e295 Iustin Pop
  @type hvparams: dict
3065 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
3066 c26a6bd2 Iustin Pop
  @rtype: None
3067 6217e295 Iustin Pop

3068 6217e295 Iustin Pop
  """
3069 6217e295 Iustin Pop
  try:
3070 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
3071 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
3072 6217e295 Iustin Pop
  except errors.HypervisorError, err:
3073 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
3074 6217e295 Iustin Pop
3075 6217e295 Iustin Pop
3076 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
3077 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
3078 acd9ff9e Iustin Pop

3079 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
3080 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
3081 acd9ff9e Iustin Pop
  @type parameters: list
3082 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
3083 acd9ff9e Iustin Pop

3084 acd9ff9e Iustin Pop
  """
3085 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
3086 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
3087 acd9ff9e Iustin Pop
  if delta:
3088 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
3089 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3090 acd9ff9e Iustin Pop
3091 acd9ff9e Iustin Pop
3092 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
3093 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
3094 acd9ff9e Iustin Pop

3095 acd9ff9e Iustin Pop
  @type required: boolean
3096 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3097 acd9ff9e Iustin Pop
      failure or not
3098 acd9ff9e Iustin Pop
  @type osname: string
3099 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3100 acd9ff9e Iustin Pop
  @type checks: list
3101 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3102 acd9ff9e Iustin Pop
  @type osparams: dict
3103 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
3104 acd9ff9e Iustin Pop
  @rtype: boolean
3105 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3106 acd9ff9e Iustin Pop
      found and L{required} was false
3107 acd9ff9e Iustin Pop

3108 acd9ff9e Iustin Pop
  """
3109 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3110 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3111 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3112 acd9ff9e Iustin Pop
3113 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3114 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3115 acd9ff9e Iustin Pop
3116 acd9ff9e Iustin Pop
  if not status:
3117 acd9ff9e Iustin Pop
    if required:
3118 acd9ff9e Iustin Pop
      _Fail(tbv)
3119 acd9ff9e Iustin Pop
    else:
3120 acd9ff9e Iustin Pop
      return False
3121 acd9ff9e Iustin Pop
3122 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3123 72db3fd7 Iustin Pop
    return True
3124 72db3fd7 Iustin Pop
3125 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3126 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3127 acd9ff9e Iustin Pop
3128 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3129 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3130 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3131 acd9ff9e Iustin Pop
  if result.failed:
3132 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3133 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3134 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3135 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3136 acd9ff9e Iustin Pop
3137 acd9ff9e Iustin Pop
  return True
3138 acd9ff9e Iustin Pop
3139 acd9ff9e Iustin Pop
3140 56aa9fd5 Iustin Pop
def DemoteFromMC():
3141 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3142 56aa9fd5 Iustin Pop

3143 56aa9fd5 Iustin Pop
  """
3144 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3145 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3146 56aa9fd5 Iustin Pop
  if master == myself:
3147 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3148 f154a7a3 Michael Hanselmann
3149 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3150 f154a7a3 Michael Hanselmann
  if not result.failed:
3151 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3152 f154a7a3 Michael Hanselmann
3153 56aa9fd5 Iustin Pop
  try:
3154 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3155 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3156 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3157 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3158 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3159 f154a7a3 Michael Hanselmann
3160 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3161 56aa9fd5 Iustin Pop
3162 56aa9fd5 Iustin Pop
3163 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3164 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3165 f942a838 Michael Hanselmann

3166 f942a838 Michael Hanselmann
  """
3167 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3168 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3169 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3170 f942a838 Michael Hanselmann
3171 f942a838 Michael Hanselmann
3172 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3173 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3174 f942a838 Michael Hanselmann

3175 f942a838 Michael Hanselmann
  @type validity: int
3176 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3177 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3178 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3179 f942a838 Michael Hanselmann

3180 f942a838 Michael Hanselmann
  """
3181 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3182 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3183 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3184 f942a838 Michael Hanselmann
3185 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3186 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3187 f942a838 Michael Hanselmann
  try:
3188 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3189 f942a838 Michael Hanselmann
    assert len(name) > 5
3190 f942a838 Michael Hanselmann
3191 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3192 f942a838 Michael Hanselmann
3193 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3194 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3195 f942a838 Michael Hanselmann
3196 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3197 f942a838 Michael Hanselmann
    return (name, cert_pem)
3198 f942a838 Michael Hanselmann
  except Exception:
3199 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3200 f942a838 Michael Hanselmann
    raise
3201 f942a838 Michael Hanselmann
3202 f942a838 Michael Hanselmann
3203 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3204 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3205 f942a838 Michael Hanselmann

3206 f942a838 Michael Hanselmann
  @type name: string
3207 f942a838 Michael Hanselmann
  @param name: Certificate name
3208 f942a838 Michael Hanselmann

3209 f942a838 Michael Hanselmann
  """
3210 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3211 f942a838 Michael Hanselmann
3212 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3213 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3214 f942a838 Michael Hanselmann
3215 f942a838 Michael Hanselmann
  try:
3216 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3217 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3218 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3219 f942a838 Michael Hanselmann
          cert_dir, err)
3220 f942a838 Michael Hanselmann
3221 f942a838 Michael Hanselmann
3222 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3223 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3224 1651d116 Michael Hanselmann

3225 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3226 1651d116 Michael Hanselmann
  @param instance: The instance object
3227 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3228 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3229 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3230 1651d116 Michael Hanselmann

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

3336 1651d116 Michael Hanselmann
  """
3337 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3338 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3339 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3340 1651d116 Michael Hanselmann
3341 1651d116 Michael Hanselmann
3342 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3343 6613661a Iustin Pop
                            ieio, ieioargs):
3344 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3345 1651d116 Michael Hanselmann

3346 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3347 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3348 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3349 1651d116 Michael Hanselmann
  @type host: string
3350 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3351 1651d116 Michael Hanselmann
  @type port: int
3352 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3353 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3354 1651d116 Michael Hanselmann
  @param instance: Instance object
3355 6613661a Iustin Pop
  @type component: string
3356 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3357 6613661a Iustin Pop
      e.g. 'disk/0'
3358 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3359 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3360 1651d116 Michael Hanselmann

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

3473 1651d116 Michael Hanselmann
  @type names: sequence
3474 1651d116 Michael Hanselmann
  @param names: List of names
3475 1651d116 Michael Hanselmann
  @rtype: List of dicts
3476 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3477 1651d116 Michael Hanselmann
           status couldn't be read
3478 1651d116 Michael Hanselmann

3479 1651d116 Michael Hanselmann
  """
3480 1651d116 Michael Hanselmann
  result = []
3481 1651d116 Michael Hanselmann
3482 1651d116 Michael Hanselmann
  for name in names:
3483 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3484 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3485 1651d116 Michael Hanselmann
3486 1651d116 Michael Hanselmann
    try:
3487 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3488 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3489 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3490 1651d116 Michael Hanselmann
        raise
3491 1651d116 Michael Hanselmann
      data = None
3492 1651d116 Michael Hanselmann
3493 1651d116 Michael Hanselmann
    if not data:
3494 1651d116 Michael Hanselmann
      result.append(None)
3495 1651d116 Michael Hanselmann
      continue
3496 1651d116 Michael Hanselmann
3497 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3498 1651d116 Michael Hanselmann
3499 1651d116 Michael Hanselmann
  return result
3500 1651d116 Michael Hanselmann
3501 1651d116 Michael Hanselmann
3502 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3503 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3504 f81c4737 Michael Hanselmann

3505 f81c4737 Michael Hanselmann
  """
3506 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3507 f81c4737 Michael Hanselmann
3508 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3509 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3510 f81c4737 Michael Hanselmann
3511 f81c4737 Michael Hanselmann
  if pid:
3512 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3513 f81c4737 Michael Hanselmann
                 name, pid)
3514 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3515 f81c4737 Michael Hanselmann
3516 f81c4737 Michael Hanselmann
3517 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3518 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3519 1651d116 Michael Hanselmann

3520 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3521 1651d116 Michael Hanselmann
  whole status directory is removed.
3522 1651d116 Michael Hanselmann

3523 1651d116 Michael Hanselmann
  """
3524 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3525 1651d116 Michael Hanselmann
3526 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3527 1651d116 Michael Hanselmann
3528 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3529 1651d116 Michael Hanselmann
3530 1651d116 Michael Hanselmann
  if pid:
3531 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3532 1651d116 Michael Hanselmann
                 name, pid)
3533 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3534 1651d116 Michael Hanselmann
3535 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3536 1651d116 Michael Hanselmann
3537 1651d116 Michael Hanselmann
3538 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3539 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3540 6b93ec9d Iustin Pop

3541 6b93ec9d Iustin Pop
  """
3542 6b93ec9d Iustin Pop
  # set the correct physical ID
3543 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3544 6b93ec9d Iustin Pop
  for cf in disks:
3545 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3546 6b93ec9d Iustin Pop
3547 6b93ec9d Iustin Pop
  bdevs = []
3548 6b93ec9d Iustin Pop
3549 6b93ec9d Iustin Pop
  for cf in disks:
3550 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3551 6b93ec9d Iustin Pop
    if rd is None:
3552 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3553 6b93ec9d Iustin Pop
    bdevs.append(rd)
3554 5a533f8a Iustin Pop
  return bdevs
3555 6b93ec9d Iustin Pop
3556 6b93ec9d Iustin Pop
3557 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3558 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3559 6b93ec9d Iustin Pop

3560 6b93ec9d Iustin Pop
  """
3561 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3562 6b93ec9d Iustin Pop
3563 6b93ec9d Iustin Pop
  # disconnect disks
3564 6b93ec9d Iustin Pop
  for rd in bdevs:
3565 6b93ec9d Iustin Pop
    try:
3566 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3567 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3568 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3569 2cc6781a Iustin Pop
            err, exc=True)
3570 6b93ec9d Iustin Pop
3571 6b93ec9d Iustin Pop
3572 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3573 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3574 6b93ec9d Iustin Pop

3575 6b93ec9d Iustin Pop
  """
3576 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3577 6b93ec9d Iustin Pop
3578 6b93ec9d Iustin Pop
  if multimaster:
3579 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3580 6b93ec9d Iustin Pop
      try:
3581 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3582 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3583 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3584 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3585 6b93ec9d Iustin Pop
  # needed primary mode
3586 6b93ec9d Iustin Pop
  for rd in bdevs:
3587 6b93ec9d Iustin Pop
    try:
3588 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3589 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3590 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3591 3c0cdc83 Michael Hanselmann
3592 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3593 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3594 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3595 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3596 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3597 3c0cdc83 Michael Hanselmann
3598 3c0cdc83 Michael Hanselmann
  def _Attach():
3599 6b93ec9d Iustin Pop
    all_connected = True
3600 3c0cdc83 Michael Hanselmann
3601 6b93ec9d Iustin Pop
    for rd in bdevs:
3602 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3603 3c0cdc83 Michael Hanselmann
3604 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3605 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3606 3c0cdc83 Michael Hanselmann
3607 6b93ec9d Iustin Pop
      if stats.is_standalone:
3608 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3609 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3610 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3611 6b93ec9d Iustin Pop
        try:
3612 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3613 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3614 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3615 3c0cdc83 Michael Hanselmann
3616 3c0cdc83 Michael Hanselmann
    if not all_connected:
3617 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3618 3c0cdc83 Michael Hanselmann
3619 3c0cdc83 Michael Hanselmann
  try:
3620 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3621 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3622 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3623 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3624 3c0cdc83 Michael Hanselmann
3625 6b93ec9d Iustin Pop
  if multimaster:
3626 6b93ec9d Iustin Pop
    # change to primary mode
3627 6b93ec9d Iustin Pop
    for rd in bdevs:
3628 d3da87b8 Iustin Pop
      try:
3629 d3da87b8 Iustin Pop
        rd.Open()
3630 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3631 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3632 6b93ec9d Iustin Pop
3633 6b93ec9d Iustin Pop
3634 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3635 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3636 6b93ec9d Iustin Pop

3637 6b93ec9d Iustin Pop
  """
3638 db8667b7 Iustin Pop
  def _helper(rd):
3639 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3640 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3641 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3642 db8667b7 Iustin Pop
    return stats
3643 db8667b7 Iustin Pop
3644 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3645 6b93ec9d Iustin Pop
3646 6b93ec9d Iustin Pop
  min_resync = 100
3647 6b93ec9d Iustin Pop
  alldone = True
3648 6b93ec9d Iustin Pop
  for rd in bdevs:
3649 db8667b7 Iustin Pop
    try:
3650 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3651 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3652 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3653 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3654 db8667b7 Iustin Pop
      # last check
3655 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3656 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3657 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3658 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3659 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3660 afdc3985 Iustin Pop
3661 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3662 6b93ec9d Iustin Pop
3663 6b93ec9d Iustin Pop
3664 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3665 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3666 c46b9782 Luca Bigliardi

3667 c46b9782 Luca Bigliardi
  """
3668 c46b9782 Luca Bigliardi
  try:
3669 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3670 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3671 c46b9782 Luca Bigliardi
    _Fail(str(err))
3672 c46b9782 Luca Bigliardi
3673 c46b9782 Luca Bigliardi
3674 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3675 f5118ade Iustin Pop
  """Hard-powercycle the node.
3676 f5118ade Iustin Pop

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

3680 f5118ade Iustin Pop
  """
3681 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3682 f5118ade Iustin Pop
  try:
3683 f5118ade Iustin Pop
    pid = os.fork()
3684 29921401 Iustin Pop
  except OSError:
3685 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3686 f5118ade Iustin Pop
    pid = 0
3687 f5118ade Iustin Pop
  if pid > 0:
3688 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3689 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3690 1af6ac0f Luca Bigliardi
  try:
3691 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3692 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3693 1af6ac0f Luca Bigliardi
    pass
3694 f5118ade Iustin Pop
  time.sleep(5)
3695 f5118ade Iustin Pop
  hyper.PowercycleNode()
3696 f5118ade Iustin Pop
3697 f5118ade Iustin Pop
3698 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
3699 45bc4635 Iustin Pop
  """Verifies a restricted command name.
3700 1a2eb2dc Michael Hanselmann

3701 1a2eb2dc Michael Hanselmann
  @type cmd: string
3702 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3703 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3704 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3705 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3706 1a2eb2dc Michael Hanselmann

3707 1a2eb2dc Michael Hanselmann
  """
3708 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
3709 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
3710 1a2eb2dc Michael Hanselmann
3711 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
3712 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
3713 1a2eb2dc Michael Hanselmann
3714 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3715 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
3716 1a2eb2dc Michael Hanselmann
3717 1a2eb2dc Michael Hanselmann
  return (True, None)
3718 1a2eb2dc Michael Hanselmann
3719 1a2eb2dc Michael Hanselmann
3720 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
3721 45bc4635 Iustin Pop
  """Common checks for restricted command file system directories and files.
3722 1a2eb2dc Michael Hanselmann

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

3730 1a2eb2dc Michael Hanselmann
  """
3731 1a2eb2dc Michael Hanselmann
  if owner is None:
3732 1a2eb2dc Michael Hanselmann
    # Default to root as owner
3733 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
3734 1a2eb2dc Michael Hanselmann
3735 1a2eb2dc Michael Hanselmann
  try:
3736 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
3737 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
3738 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3739 1a2eb2dc Michael Hanselmann
3740 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3741 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
3742 1a2eb2dc Michael Hanselmann
3743 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
3744 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
3745 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3746 1a2eb2dc Michael Hanselmann
3747 1a2eb2dc Michael Hanselmann
  return (True, st)
3748 1a2eb2dc Michael Hanselmann
3749 1a2eb2dc Michael Hanselmann
3750 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3751 45bc4635 Iustin Pop
  """Verifies restricted command directory.
3752 1a2eb2dc Michael Hanselmann

3753 1a2eb2dc Michael Hanselmann
  @type path: string
3754 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3755 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3756 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3757 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3758 1a2eb2dc Michael Hanselmann

3759 1a2eb2dc Michael Hanselmann
  """
3760 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3761 1a2eb2dc Michael Hanselmann
3762 1a2eb2dc Michael Hanselmann
  if not status:
3763 1a2eb2dc Michael Hanselmann
    return (False, value)
3764 1a2eb2dc Michael Hanselmann
3765 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
3766 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
3767 1a2eb2dc Michael Hanselmann
3768 1a2eb2dc Michael Hanselmann
  return (True, None)
3769 1a2eb2dc Michael Hanselmann
3770 1a2eb2dc Michael Hanselmann
3771 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3772 45bc4635 Iustin Pop
  """Verifies a whole restricted command and returns its executable filename.
3773 1a2eb2dc Michael Hanselmann

3774 1a2eb2dc Michael Hanselmann
  @type path: string
3775 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
3776 1a2eb2dc Michael Hanselmann
  @type cmd: string
3777 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3778 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
3779 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3780 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
3781 1a2eb2dc Michael Hanselmann
    absolute path to the executable
3782 1a2eb2dc Michael Hanselmann

3783 1a2eb2dc Michael Hanselmann
  """
3784 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
3785 1a2eb2dc Michael Hanselmann
3786 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3787 1a2eb2dc Michael Hanselmann
3788 1a2eb2dc Michael Hanselmann
  if not status:
3789 1a2eb2dc Michael Hanselmann
    return (False, msg)
3790 1a2eb2dc Michael Hanselmann
3791 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
3792 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3793 1a2eb2dc Michael Hanselmann
3794 1a2eb2dc Michael Hanselmann
  return (True, executable)
3795 1a2eb2dc Michael Hanselmann
3796 1a2eb2dc Michael Hanselmann
3797 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
3798 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3799 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
3800 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
3801 45bc4635 Iustin Pop
  """Performs a number of tests on a restricted command.
3802 1a2eb2dc Michael Hanselmann

3803 1a2eb2dc Michael Hanselmann
  @type path: string
3804 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
3805 1a2eb2dc Michael Hanselmann
  @type cmd: string
3806 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3807 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
3808 1a2eb2dc Michael Hanselmann

3809 1a2eb2dc Michael Hanselmann
  """
3810 1a2eb2dc Michael Hanselmann
  # Verify the directory first
3811 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
3812 1a2eb2dc Michael Hanselmann
  if status:
3813 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
3814 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
3815 1a2eb2dc Michael Hanselmann
3816 1a2eb2dc Michael Hanselmann
  if not status:
3817 1a2eb2dc Michael Hanselmann
    return (False, msg)
3818 1a2eb2dc Michael Hanselmann
3819 1a2eb2dc Michael Hanselmann
  # Check actual executable
3820 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
3821 1a2eb2dc Michael Hanselmann
3822 1a2eb2dc Michael Hanselmann
3823 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
3824 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3825 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3826 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3827 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
3828 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
3829 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
3830 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3831 45bc4635 Iustin Pop
  """Executes a restricted command after performing strict tests.
3832 1a2eb2dc Michael Hanselmann

3833 1a2eb2dc Michael Hanselmann
  @type cmd: string
3834 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3835 1a2eb2dc Michael Hanselmann
  @rtype: string
3836 1a2eb2dc Michael Hanselmann
  @return: Command output
3837 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
3838 1a2eb2dc Michael Hanselmann

3839 1a2eb2dc Michael Hanselmann
  """
3840 45bc4635 Iustin Pop
  logging.info("Preparing to run restricted command '%s'", cmd)
3841 1a2eb2dc Michael Hanselmann
3842 1a2eb2dc Michael Hanselmann
  if not _enabled:
3843 45bc4635 Iustin Pop
    _Fail("Restricted commands disabled at configure time")
3844 1a2eb2dc Michael Hanselmann
3845 1a2eb2dc Michael Hanselmann
  lock = None
3846 1a2eb2dc Michael Hanselmann
  try:
3847 1a2eb2dc Michael Hanselmann
    cmdresult = None
3848 1a2eb2dc Michael Hanselmann
    try:
3849 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
3850 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3851 1a2eb2dc Michael Hanselmann
3852 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
3853 1a2eb2dc Michael Hanselmann
3854 1a2eb2dc Michael Hanselmann
      if status:
3855 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3856 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
3857 1a2eb2dc Michael Hanselmann
      else:
3858 1a2eb2dc Michael Hanselmann
        logging.error(value)
3859 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
3860 1a2eb2dc Michael Hanselmann
      # Keep original error in log
3861 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
3862 1a2eb2dc Michael Hanselmann
3863 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
3864 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
3865 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
3866 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
3867 1a2eb2dc Michael Hanselmann
3868 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
3869 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
3870 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
3871 45bc4635 Iustin Pop
      _Fail("Restricted command '%s' failed: %s; output: %s",
3872 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
3873 1a2eb2dc Michael Hanselmann
    else:
3874 1a2eb2dc Michael Hanselmann
      return cmdresult.output
3875 1a2eb2dc Michael Hanselmann
  finally:
3876 1a2eb2dc Michael Hanselmann
    if lock is not None:
3877 1a2eb2dc Michael Hanselmann
      # Release lock at last
3878 1a2eb2dc Michael Hanselmann
      lock.Close()
3879 1a2eb2dc Michael Hanselmann
      lock = None
3880 1a2eb2dc Michael Hanselmann
3881 1a2eb2dc Michael Hanselmann
3882 99e222b1 Michael Hanselmann
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3883 99e222b1 Michael Hanselmann
  """Creates or removes the watcher pause file.
3884 99e222b1 Michael Hanselmann

3885 99e222b1 Michael Hanselmann
  @type until: None or number
3886 99e222b1 Michael Hanselmann
  @param until: Unix timestamp saying until when the watcher shouldn't run
3887 99e222b1 Michael Hanselmann

3888 99e222b1 Michael Hanselmann
  """
3889 99e222b1 Michael Hanselmann
  if until is None:
3890 99e222b1 Michael Hanselmann
    logging.info("Received request to no longer pause watcher")
3891 99e222b1 Michael Hanselmann
    utils.RemoveFile(_filename)
3892 99e222b1 Michael Hanselmann
  else:
3893 99e222b1 Michael Hanselmann
    logging.info("Received request to pause watcher until %s", until)
3894 99e222b1 Michael Hanselmann
3895 99e222b1 Michael Hanselmann
    if not ht.TNumber(until):
3896 99e222b1 Michael Hanselmann
      _Fail("Duration must be numeric")
3897 99e222b1 Michael Hanselmann
3898 99e222b1 Michael Hanselmann
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
3899 99e222b1 Michael Hanselmann
3900 99e222b1 Michael Hanselmann
3901 a8083063 Iustin Pop
class HooksRunner(object):
3902 a8083063 Iustin Pop
  """Hook runner.
3903 a8083063 Iustin Pop

3904 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3905 10c2650b Iustin Pop
  on the master side.
3906 a8083063 Iustin Pop

3907 a8083063 Iustin Pop
  """
3908 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3909 a8083063 Iustin Pop
    """Constructor for hooks runner.
3910 a8083063 Iustin Pop

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

3915 a8083063 Iustin Pop
    """
3916 a8083063 Iustin Pop
    if hooks_base_dir is None:
3917 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3918 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3919 fe267188 Iustin Pop
    # constant
3920 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3921 a8083063 Iustin Pop
3922 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3923 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3924 0fa481f5 Andrea Spadaccini

3925 0fa481f5 Andrea Spadaccini
    """
3926 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3927 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3928 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3929 0fa481f5 Andrea Spadaccini
    assert node == myself
3930 0fa481f5 Andrea Spadaccini
3931 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3932 0fa481f5 Andrea Spadaccini
3933 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3934 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3935 0fa481f5 Andrea Spadaccini
3936 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3937 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3938 a8083063 Iustin Pop

3939 10c2650b Iustin Pop
    @type hpath: str
3940 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3941 10c2650b Iustin Pop
        holds the scripts
3942 10c2650b Iustin Pop
    @type phase: str
3943 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3944 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3945 10c2650b Iustin Pop
    @type env: dict
3946 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3947 10c2650b Iustin Pop
    @rtype: list
3948 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3949 10c2650b Iustin Pop
      - script path
3950 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3951 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3952 10c2650b Iustin Pop
      - output of the script
3953 10c2650b Iustin Pop

3954 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3955 10c2650b Iustin Pop
        parameters
3956 a8083063 Iustin Pop

3957 a8083063 Iustin Pop
    """
3958 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3959 a8083063 Iustin Pop
      suffix = "pre"
3960 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3961 a8083063 Iustin Pop
      suffix = "post"
3962 a8083063 Iustin Pop
    else:
3963 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3964 3fb4f740 Iustin Pop
3965 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3966 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3967 6bb65e3a Guido Trotter
3968 6bb65e3a Guido Trotter
    results = []
3969 a9b7e346 Iustin Pop
3970 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
3971 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
3972 a9b7e346 Iustin Pop
      # warning at every operation
3973 a9b7e346 Iustin Pop
      return results
3974 a9b7e346 Iustin Pop
3975 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3976 a9b7e346 Iustin Pop
3977 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
3978 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3979 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3980 a8083063 Iustin Pop
        output = ""
3981 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3982 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3983 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3984 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3985 6bb65e3a Guido Trotter
        if runresult.failed:
3986 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3987 a8083063 Iustin Pop
        else:
3988 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3989 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3990 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3991 6bb65e3a Guido Trotter
3992 6bb65e3a Guido Trotter
    return results
3993 3f78eef2 Iustin Pop
3994 3f78eef2 Iustin Pop
3995 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3996 8d528b7c Iustin Pop
  """IAllocator runner.
3997 8d528b7c Iustin Pop

3998 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3999 8d528b7c Iustin Pop
  the master side.
4000 8d528b7c Iustin Pop

4001 8d528b7c Iustin Pop
  """
4002 7e950d31 Iustin Pop
  @staticmethod
4003 7e950d31 Iustin Pop
  def Run(name, idata):
4004 8d528b7c Iustin Pop
    """Run an iallocator script.
4005 8d528b7c Iustin Pop

4006 10c2650b Iustin Pop
    @type name: str
4007 10c2650b Iustin Pop
    @param name: the iallocator script name
4008 10c2650b Iustin Pop
    @type idata: str
4009 10c2650b Iustin Pop
    @param idata: the allocator input data
4010 10c2650b Iustin Pop

4011 10c2650b Iustin Pop
    @rtype: tuple
4012 87f5c298 Iustin Pop
    @return: two element tuple of:
4013 87f5c298 Iustin Pop
       - status
4014 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
4015 8d528b7c Iustin Pop

4016 8d528b7c Iustin Pop
    """
4017 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4018 8d528b7c Iustin Pop
                                  os.path.isfile)
4019 8d528b7c Iustin Pop
    if alloc_script is None:
4020 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
4021 8d528b7c Iustin Pop
4022 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4023 8d528b7c Iustin Pop
    try:
4024 8d528b7c Iustin Pop
      os.write(fd, idata)
4025 8d528b7c Iustin Pop
      os.close(fd)
4026 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
4027 8d528b7c Iustin Pop
      if result.failed:
4028 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4029 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
4030 8d528b7c Iustin Pop
    finally:
4031 8d528b7c Iustin Pop
      os.unlink(fin_name)
4032 8d528b7c Iustin Pop
4033 c26a6bd2 Iustin Pop
    return result.stdout
4034 8d528b7c Iustin Pop
4035 8d528b7c Iustin Pop
4036 3f78eef2 Iustin Pop
class DevCacheManager(object):
4037 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
4038 3f78eef2 Iustin Pop

4039 3f78eef2 Iustin Pop
  """
4040 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
4041 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4042 3f78eef2 Iustin Pop
4043 3f78eef2 Iustin Pop
  @classmethod
4044 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
4045 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
4046 3f78eef2 Iustin Pop

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

4050 10c2650b Iustin Pop
    @type dev_path: str
4051 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
4052 10c2650b Iustin Pop
    @rtype: str
4053 10c2650b Iustin Pop
    @return: the converted path name
4054 3f78eef2 Iustin Pop

4055 3f78eef2 Iustin Pop
    """
4056 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
4057 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4058 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
4059 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4060 3f78eef2 Iustin Pop
    return fpath
4061 3f78eef2 Iustin Pop
4062 3f78eef2 Iustin Pop
  @classmethod
4063 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4064 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
4065 3f78eef2 Iustin Pop

4066 10c2650b Iustin Pop
    @type dev_path: str
4067 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4068 10c2650b Iustin Pop
    @type owner: str
4069 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
4070 10c2650b Iustin Pop
    @type on_primary: bool
4071 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
4072 10c2650b Iustin Pop
        node nor not
4073 10c2650b Iustin Pop
    @type iv_name: str
4074 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
4075 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
4076 10c2650b Iustin Pop

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

4079 3f78eef2 Iustin Pop
    """
4080 cf5a8306 Iustin Pop
    if dev_path is None:
4081 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4082 cf5a8306 Iustin Pop
      return
4083 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4084 3f78eef2 Iustin Pop
    if on_primary:
4085 3f78eef2 Iustin Pop
      state = "primary"
4086 3f78eef2 Iustin Pop
    else:
4087 3f78eef2 Iustin Pop
      state = "secondary"
4088 3f78eef2 Iustin Pop
    if iv_name is None:
4089 3f78eef2 Iustin Pop
      iv_name = "not_visible"
4090 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4091 3f78eef2 Iustin Pop
    try:
4092 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
4093 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4094 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4095 3f78eef2 Iustin Pop
4096 3f78eef2 Iustin Pop
  @classmethod
4097 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
4098 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
4099 3f78eef2 Iustin Pop

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

4103 10c2650b Iustin Pop
    @type dev_path: str
4104 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4105 10c2650b Iustin Pop

4106 10c2650b Iustin Pop
    @rtype: None
4107 10c2650b Iustin Pop

4108 3f78eef2 Iustin Pop
    """
4109 cf5a8306 Iustin Pop
    if dev_path is None:
4110 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4111 cf5a8306 Iustin Pop
      return
4112 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4113 3f78eef2 Iustin Pop
    try:
4114 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
4115 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4116 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)