Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 2ef21e6e

History | View | Annotate | Download (125.4 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 a59d5fa1 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 a59d5fa1 Michele Tartara
class InstReason(object):
126 a59d5fa1 Michele Tartara
  """Class representing the reason for a change of state of a VM.
127 a59d5fa1 Michele Tartara

128 a59d5fa1 Michele Tartara
  It is used to allow an easy serialization of the reason, so that it can be
129 a59d5fa1 Michele Tartara
  written on a file.
130 a59d5fa1 Michele Tartara

131 a59d5fa1 Michele Tartara
  """
132 a59d5fa1 Michele Tartara
  def __init__(self, source, text):
133 a59d5fa1 Michele Tartara
    """Initialize the class with all the required values.
134 a59d5fa1 Michele Tartara

135 a59d5fa1 Michele Tartara
    @type text: string
136 a59d5fa1 Michele Tartara
    @param text: The textual description of the reason for changing state
137 a59d5fa1 Michele Tartara
    @type source: string
138 a59d5fa1 Michele Tartara
    @param source: The source of the state change (RAPI, CLI, ...)
139 a59d5fa1 Michele Tartara

140 a59d5fa1 Michele Tartara
    """
141 a59d5fa1 Michele Tartara
    self.source = source
142 a59d5fa1 Michele Tartara
    self.text = text
143 a59d5fa1 Michele Tartara
144 a59d5fa1 Michele Tartara
  def GetJson(self):
145 a59d5fa1 Michele Tartara
    """Get the JSON representation of the InstReason.
146 a59d5fa1 Michele Tartara

147 a59d5fa1 Michele Tartara
    @rtype: string
148 a59d5fa1 Michele Tartara
    @return : The JSON representation of the object
149 a59d5fa1 Michele Tartara

150 a59d5fa1 Michele Tartara
    """
151 a59d5fa1 Michele Tartara
    return serializer.DumpJson(dict(source=self.source, text=self.text))
152 a59d5fa1 Michele Tartara
153 a59d5fa1 Michele Tartara
  def Store(self, instance_name):
154 a59d5fa1 Michele Tartara
    """Serialize on a file the reason for the last state change of an instance.
155 a59d5fa1 Michele Tartara

156 a59d5fa1 Michele Tartara
    The exact location of the file depends on the name of the instance and on
157 a59d5fa1 Michele Tartara
    the configuration of the Ganeti cluster defined at deploy time.
158 a59d5fa1 Michele Tartara

159 a59d5fa1 Michele Tartara
    @type instance_name: string
160 a59d5fa1 Michele Tartara
    @param instance_name: The name of the instance
161 a59d5fa1 Michele Tartara
    @rtype: None
162 a59d5fa1 Michele Tartara

163 a59d5fa1 Michele Tartara
    """
164 a59d5fa1 Michele Tartara
    filename = GetInstReasonFilename(instance_name)
165 a59d5fa1 Michele Tartara
    utils.WriteFile(filename, data=self.GetJson())
166 a59d5fa1 Michele Tartara
167 a59d5fa1 Michele Tartara
168 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
169 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
170 2cc6781a Iustin Pop

171 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
172 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
173 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
174 2cc6781a Iustin Pop
  daemon.
175 2cc6781a Iustin Pop

176 2cc6781a Iustin Pop
  @type msg: string
177 2cc6781a Iustin Pop
  @param msg: the text of the exception
178 2cc6781a Iustin Pop
  @raise RPCFail
179 2cc6781a Iustin Pop

180 2cc6781a Iustin Pop
  """
181 2cc6781a Iustin Pop
  if args:
182 2cc6781a Iustin Pop
    msg = msg % args
183 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
184 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
185 afdc3985 Iustin Pop
      logging.exception(msg)
186 afdc3985 Iustin Pop
    else:
187 afdc3985 Iustin Pop
      logging.error(msg)
188 2cc6781a Iustin Pop
  raise RPCFail(msg)
189 2cc6781a Iustin Pop
190 2cc6781a Iustin Pop
191 c657dcc9 Michael Hanselmann
def _GetConfig():
192 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
193 10c2650b Iustin Pop

194 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
195 93384844 Iustin Pop
  @return: a SimpleStore instance
196 10c2650b Iustin Pop

197 10c2650b Iustin Pop
  """
198 93384844 Iustin Pop
  return ssconf.SimpleStore()
199 c657dcc9 Michael Hanselmann
200 c657dcc9 Michael Hanselmann
201 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
202 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
203 10c2650b Iustin Pop

204 10c2650b Iustin Pop
  @type cluster_name: str
205 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
206 10c2650b Iustin Pop
      by the SshRunner constructor
207 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
208 10c2650b Iustin Pop
  @return: an SshRunner instance
209 10c2650b Iustin Pop

210 10c2650b Iustin Pop
  """
211 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
212 c92b310a Michael Hanselmann
213 c92b310a Michael Hanselmann
214 12bce260 Michael Hanselmann
def _Decompress(data):
215 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
216 12bce260 Michael Hanselmann

217 12bce260 Michael Hanselmann
  @type data: list or tuple
218 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
219 12bce260 Michael Hanselmann
  @rtype: str
220 12bce260 Michael Hanselmann
  @return: Decompressed data
221 12bce260 Michael Hanselmann

222 12bce260 Michael Hanselmann
  """
223 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
224 12bce260 Michael Hanselmann
  assert len(data) == 2
225 12bce260 Michael Hanselmann
  (encoding, content) = data
226 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
227 12bce260 Michael Hanselmann
    return content
228 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
229 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
230 12bce260 Michael Hanselmann
  else:
231 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
232 12bce260 Michael Hanselmann
233 12bce260 Michael Hanselmann
234 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
235 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
236 76ab5558 Michael Hanselmann

237 10c2650b Iustin Pop
  @type path: str
238 10c2650b Iustin Pop
  @param path: the directory to clean
239 76ab5558 Michael Hanselmann
  @type exclude: list
240 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
241 10c2650b Iustin Pop
      to the empty list
242 76ab5558 Michael Hanselmann

243 76ab5558 Michael Hanselmann
  """
244 714ea7ca Iustin Pop
  if path not in _ALLOWED_CLEAN_DIRS:
245 714ea7ca Iustin Pop
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
246 714ea7ca Iustin Pop
          path)
247 714ea7ca Iustin Pop
248 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
249 3956cee1 Michael Hanselmann
    return
250 3bc6be5c Iustin Pop
  if exclude is None:
251 3bc6be5c Iustin Pop
    exclude = []
252 3bc6be5c Iustin Pop
  else:
253 3bc6be5c Iustin Pop
    # Normalize excluded paths
254 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
255 76ab5558 Michael Hanselmann
256 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
257 c4feafe8 Iustin Pop
    full_name = utils.PathJoin(path, rel_name)
258 76ab5558 Michael Hanselmann
    if full_name in exclude:
259 76ab5558 Michael Hanselmann
      continue
260 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
261 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
262 3956cee1 Michael Hanselmann
263 3956cee1 Michael Hanselmann
264 360b0dc2 Iustin Pop
def _BuildUploadFileList():
265 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
266 360b0dc2 Iustin Pop

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

269 360b0dc2 Iustin Pop
  """
270 b397a7d2 Iustin Pop
  allowed_files = set([
271 710f30ec Michael Hanselmann
    pathutils.CLUSTER_CONF_FILE,
272 ee045466 Michael Hanselmann
    pathutils.ETC_HOSTS,
273 710f30ec Michael Hanselmann
    pathutils.SSH_KNOWN_HOSTS_FILE,
274 710f30ec Michael Hanselmann
    pathutils.VNC_PASSWORD_FILE,
275 710f30ec Michael Hanselmann
    pathutils.RAPI_CERT_FILE,
276 710f30ec Michael Hanselmann
    pathutils.SPICE_CERT_FILE,
277 710f30ec Michael Hanselmann
    pathutils.SPICE_CACERT_FILE,
278 710f30ec Michael Hanselmann
    pathutils.RAPI_USERS_FILE,
279 710f30ec Michael Hanselmann
    pathutils.CONFD_HMAC_KEY,
280 710f30ec Michael Hanselmann
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
281 b397a7d2 Iustin Pop
    ])
282 b397a7d2 Iustin Pop
283 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
284 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
285 69ab2e12 Guido Trotter
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
286 b397a7d2 Iustin Pop
287 3439fd6b Michael Hanselmann
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
288 3439fd6b Michael Hanselmann
    "Allowed file storage paths should never be uploaded via RPC"
289 3439fd6b Michael Hanselmann
290 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
291 360b0dc2 Iustin Pop
292 360b0dc2 Iustin Pop
293 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
294 360b0dc2 Iustin Pop
295 360b0dc2 Iustin Pop
296 1bc59f76 Michael Hanselmann
def JobQueuePurge():
297 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
298 10c2650b Iustin Pop

299 c8457ce7 Iustin Pop
  @rtype: tuple
300 c8457ce7 Iustin Pop
  @return: True, None
301 24fc781f Michael Hanselmann

302 24fc781f Michael Hanselmann
  """
303 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
304 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
305 24fc781f Michael Hanselmann
306 24fc781f Michael Hanselmann
307 bd1e4562 Iustin Pop
def GetMasterInfo():
308 bd1e4562 Iustin Pop
  """Returns master information.
309 bd1e4562 Iustin Pop

310 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
311 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
312 bd1e4562 Iustin Pop

313 bd1e4562 Iustin Pop
  @rtype: tuple
314 909b3a0e Andrea Spadaccini
  @return: master_netdev, master_ip, master_name, primary_ip_family,
315 909b3a0e Andrea Spadaccini
    master_netmask
316 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
317 b1b6ea87 Iustin Pop

318 b1b6ea87 Iustin Pop
  """
319 b1b6ea87 Iustin Pop
  try:
320 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
321 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
322 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
323 5a8648eb Andrea Spadaccini
    master_netmask = cfg.GetMasterNetmask()
324 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
325 d8e0caa6 Manuel Franceschini
    primary_ip_family = cfg.GetPrimaryIPFamily()
326 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
327 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
328 909b3a0e Andrea Spadaccini
  return (master_netdev, master_ip, master_node, primary_ip_family,
329 5ae4945a Iustin Pop
          master_netmask)
330 b1b6ea87 Iustin Pop
331 b1b6ea87 Iustin Pop
332 0fa481f5 Andrea Spadaccini
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
333 0fa481f5 Andrea Spadaccini
  """Decorator that runs hooks before and after the decorated function.
334 0fa481f5 Andrea Spadaccini

335 0fa481f5 Andrea Spadaccini
  @type hook_opcode: string
336 0fa481f5 Andrea Spadaccini
  @param hook_opcode: opcode of the hook
337 0fa481f5 Andrea Spadaccini
  @type hooks_path: string
338 0fa481f5 Andrea Spadaccini
  @param hooks_path: path of the hooks
339 0fa481f5 Andrea Spadaccini
  @type env_builder_fn: function
340 0fa481f5 Andrea Spadaccini
  @param env_builder_fn: function that returns a dictionary containing the
341 3ccd3243 Andrea Spadaccini
    environment variables for the hooks. Will get all the parameters of the
342 3ccd3243 Andrea Spadaccini
    decorated function.
343 0fa481f5 Andrea Spadaccini
  @raise RPCFail: in case of pre-hook failure
344 0fa481f5 Andrea Spadaccini

345 0fa481f5 Andrea Spadaccini
  """
346 0fa481f5 Andrea Spadaccini
  def decorator(fn):
347 0fa481f5 Andrea Spadaccini
    def wrapper(*args, **kwargs):
348 0fa481f5 Andrea Spadaccini
      _, myself = ssconf.GetMasterAndMyself()
349 0fa481f5 Andrea Spadaccini
      nodes = ([myself], [myself])  # these hooks run locally
350 0fa481f5 Andrea Spadaccini
351 3ccd3243 Andrea Spadaccini
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
352 3ccd3243 Andrea Spadaccini
353 0fa481f5 Andrea Spadaccini
      cfg = _GetConfig()
354 0fa481f5 Andrea Spadaccini
      hr = HooksRunner()
355 0fa481f5 Andrea Spadaccini
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
356 3ccd3243 Andrea Spadaccini
                            None, env_fn, logging.warning, cfg.GetClusterName(),
357 3ccd3243 Andrea Spadaccini
                            cfg.GetMasterNode())
358 0fa481f5 Andrea Spadaccini
359 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
360 0fa481f5 Andrea Spadaccini
      result = fn(*args, **kwargs)
361 0fa481f5 Andrea Spadaccini
      hm.RunPhase(constants.HOOKS_PHASE_POST)
362 0fa481f5 Andrea Spadaccini
363 0fa481f5 Andrea Spadaccini
      return result
364 0fa481f5 Andrea Spadaccini
    return wrapper
365 0fa481f5 Andrea Spadaccini
  return decorator
366 0fa481f5 Andrea Spadaccini
367 0fa481f5 Andrea Spadaccini
368 57c7bc57 Andrea Spadaccini
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
369 2d88fdd3 Andrea Spadaccini
  """Builds environment variables for master IP hooks.
370 2d88fdd3 Andrea Spadaccini

371 3ccd3243 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
372 3ccd3243 Andrea Spadaccini
  @param master_params: network parameters of the master
373 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
374 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
375 57c7bc57 Andrea Spadaccini
    address setup script (unused, but necessary per the implementation of the
376 57c7bc57 Andrea Spadaccini
    _RunLocalHooks decorator)
377 3ccd3243 Andrea Spadaccini

378 2d88fdd3 Andrea Spadaccini
  """
379 57c7bc57 Andrea Spadaccini
  # pylint: disable=W0613
380 3ccd3243 Andrea Spadaccini
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
381 2d88fdd3 Andrea Spadaccini
  env = {
382 3ccd3243 Andrea Spadaccini
    "MASTER_NETDEV": master_params.netdev,
383 3ccd3243 Andrea Spadaccini
    "MASTER_IP": master_params.ip,
384 702eff21 Andrea Spadaccini
    "MASTER_NETMASK": str(master_params.netmask),
385 3ccd3243 Andrea Spadaccini
    "CLUSTER_IP_VERSION": str(ver),
386 2d88fdd3 Andrea Spadaccini
  }
387 2d88fdd3 Andrea Spadaccini
388 2d88fdd3 Andrea Spadaccini
  return env
389 2d88fdd3 Andrea Spadaccini
390 2d88fdd3 Andrea Spadaccini
391 702eff21 Andrea Spadaccini
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
392 702eff21 Andrea Spadaccini
  """Execute the master IP address setup script.
393 702eff21 Andrea Spadaccini

394 702eff21 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
395 702eff21 Andrea Spadaccini
  @param master_params: network parameters of the master
396 702eff21 Andrea Spadaccini
  @type action: string
397 702eff21 Andrea Spadaccini
  @param action: action to pass to the script. Must be one of
398 702eff21 Andrea Spadaccini
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
399 702eff21 Andrea Spadaccini
  @type use_external_mip_script: boolean
400 702eff21 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
401 702eff21 Andrea Spadaccini
    address setup script
402 702eff21 Andrea Spadaccini
  @raise backend.RPCFail: if there are errors during the execution of the
403 702eff21 Andrea Spadaccini
    script
404 702eff21 Andrea Spadaccini

405 702eff21 Andrea Spadaccini
  """
406 702eff21 Andrea Spadaccini
  env = _BuildMasterIpEnv(master_params)
407 702eff21 Andrea Spadaccini
408 702eff21 Andrea Spadaccini
  if use_external_mip_script:
409 710f30ec Michael Hanselmann
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
410 702eff21 Andrea Spadaccini
  else:
411 710f30ec Michael Hanselmann
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
412 702eff21 Andrea Spadaccini
413 702eff21 Andrea Spadaccini
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
414 702eff21 Andrea Spadaccini
415 702eff21 Andrea Spadaccini
  if result.failed:
416 19e1b715 Iustin Pop
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
417 19e1b715 Iustin Pop
          (action, result.exit_code, result.output), log=True)
418 702eff21 Andrea Spadaccini
419 702eff21 Andrea Spadaccini
420 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
421 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
422 57c7bc57 Andrea Spadaccini
def ActivateMasterIp(master_params, use_external_mip_script):
423 fb460cf7 Andrea Spadaccini
  """Activate the IP address of the master daemon.
424 fb460cf7 Andrea Spadaccini

425 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
426 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
427 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
428 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
429 57c7bc57 Andrea Spadaccini
    address setup script
430 702eff21 Andrea Spadaccini
  @raise RPCFail: in case of errors during the IP startup
431 8da2bd43 Andrea Spadaccini

432 fb460cf7 Andrea Spadaccini
  """
433 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_START,
434 702eff21 Andrea Spadaccini
                        use_external_mip_script)
435 fb460cf7 Andrea Spadaccini
436 fb460cf7 Andrea Spadaccini
437 fb460cf7 Andrea Spadaccini
def StartMasterDaemons(no_voting):
438 a8083063 Iustin Pop
  """Activate local node as master node.
439 a8083063 Iustin Pop

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

442 3583908a Guido Trotter
  @type no_voting: boolean
443 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
444 fb460cf7 Andrea Spadaccini
      but still non-interactively
445 10c2650b Iustin Pop
  @rtype: None
446 a8083063 Iustin Pop

447 a8083063 Iustin Pop
  """
448 a8083063 Iustin Pop
449 fb460cf7 Andrea Spadaccini
  if no_voting:
450 fb460cf7 Andrea Spadaccini
    masterd_args = "--no-voting --yes-do-it"
451 fb460cf7 Andrea Spadaccini
  else:
452 fb460cf7 Andrea Spadaccini
    masterd_args = ""
453 f154a7a3 Michael Hanselmann
454 fb460cf7 Andrea Spadaccini
  env = {
455 fb460cf7 Andrea Spadaccini
    "EXTRA_MASTERD_ARGS": masterd_args,
456 fb460cf7 Andrea Spadaccini
    }
457 fb460cf7 Andrea Spadaccini
458 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
459 fb460cf7 Andrea Spadaccini
  if result.failed:
460 fb460cf7 Andrea Spadaccini
    msg = "Can't start Ganeti master: %s" % result.output
461 fb460cf7 Andrea Spadaccini
    logging.error(msg)
462 fb460cf7 Andrea Spadaccini
    _Fail(msg)
463 f154a7a3 Michael Hanselmann
464 fb460cf7 Andrea Spadaccini
465 2d88fdd3 Andrea Spadaccini
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
466 3a3e4f1e Andrea Spadaccini
               _BuildMasterIpEnv)
467 57c7bc57 Andrea Spadaccini
def DeactivateMasterIp(master_params, use_external_mip_script):
468 fb460cf7 Andrea Spadaccini
  """Deactivate the master IP on this node.
469 a8083063 Iustin Pop

470 c79198a0 Andrea Spadaccini
  @type master_params: L{objects.MasterNetworkParameters}
471 c79198a0 Andrea Spadaccini
  @param master_params: network parameters of the master
472 57c7bc57 Andrea Spadaccini
  @type use_external_mip_script: boolean
473 57c7bc57 Andrea Spadaccini
  @param use_external_mip_script: whether to use an external master IP
474 57c7bc57 Andrea Spadaccini
    address setup script
475 702eff21 Andrea Spadaccini
  @raise RPCFail: in case of errors during the IP turndown
476 96e0d5cc Andrea Spadaccini

477 a8083063 Iustin Pop
  """
478 702eff21 Andrea Spadaccini
  _RunMasterSetupScript(master_params, _MASTER_STOP,
479 702eff21 Andrea Spadaccini
                        use_external_mip_script)
480 b1b6ea87 Iustin Pop
481 fb460cf7 Andrea Spadaccini
482 fb460cf7 Andrea Spadaccini
def StopMasterDaemons():
483 fb460cf7 Andrea Spadaccini
  """Stop the master daemons on this node.
484 fb460cf7 Andrea Spadaccini

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

487 fb460cf7 Andrea Spadaccini
  @rtype: None
488 fb460cf7 Andrea Spadaccini

489 fb460cf7 Andrea Spadaccini
  """
490 fb460cf7 Andrea Spadaccini
  # TODO: log and report back to the caller the error failures; we
491 fb460cf7 Andrea Spadaccini
  # need to decide in which case we fail the RPC for this
492 fb460cf7 Andrea Spadaccini
493 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
494 fb460cf7 Andrea Spadaccini
  if result.failed:
495 fb460cf7 Andrea Spadaccini
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
496 fb460cf7 Andrea Spadaccini
                  " and error %s",
497 fb460cf7 Andrea Spadaccini
                  result.cmd, result.exit_code, result.output)
498 a8083063 Iustin Pop
499 a8083063 Iustin Pop
500 41e079ce Andrea Spadaccini
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
501 5a8648eb Andrea Spadaccini
  """Change the netmask of the master IP.
502 5a8648eb Andrea Spadaccini

503 41e079ce Andrea Spadaccini
  @param old_netmask: the old value of the netmask
504 41e079ce Andrea Spadaccini
  @param netmask: the new value of the netmask
505 41e079ce Andrea Spadaccini
  @param master_ip: the master IP
506 41e079ce Andrea Spadaccini
  @param master_netdev: the master network device
507 41e079ce Andrea Spadaccini

508 5a8648eb Andrea Spadaccini
  """
509 5a8648eb Andrea Spadaccini
  if old_netmask == netmask:
510 5a8648eb Andrea Spadaccini
    return
511 5a8648eb Andrea Spadaccini
512 9e6014b9 Andrea Spadaccini
  if not netutils.IPAddress.Own(master_ip):
513 9e6014b9 Andrea Spadaccini
    _Fail("The master IP address is not up, not attempting to change its"
514 9e6014b9 Andrea Spadaccini
          " netmask")
515 9e6014b9 Andrea Spadaccini
516 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
517 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, netmask),
518 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
519 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
520 5a8648eb Andrea Spadaccini
  if result.failed:
521 9e6014b9 Andrea Spadaccini
    _Fail("Could not set the new netmask on the master IP address")
522 5a8648eb Andrea Spadaccini
523 5a8648eb Andrea Spadaccini
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
524 5a8648eb Andrea Spadaccini
                         "%s/%s" % (master_ip, old_netmask),
525 5a8648eb Andrea Spadaccini
                         "dev", master_netdev, "label",
526 5a8648eb Andrea Spadaccini
                         "%s:0" % master_netdev])
527 5a8648eb Andrea Spadaccini
  if result.failed:
528 9e6014b9 Andrea Spadaccini
    _Fail("Could not bring down the master IP address with the old netmask")
529 5a8648eb Andrea Spadaccini
530 5a8648eb Andrea Spadaccini
531 19ddc57a René Nussbaumer
def EtcHostsModify(mode, host, ip):
532 19ddc57a René Nussbaumer
  """Modify a host entry in /etc/hosts.
533 19ddc57a René Nussbaumer

534 19ddc57a René Nussbaumer
  @param mode: The mode to operate. Either add or remove entry
535 19ddc57a René Nussbaumer
  @param host: The host to operate on
536 19ddc57a René Nussbaumer
  @param ip: The ip associated with the entry
537 19ddc57a René Nussbaumer

538 19ddc57a René Nussbaumer
  """
539 19ddc57a René Nussbaumer
  if mode == constants.ETC_HOSTS_ADD:
540 19ddc57a René Nussbaumer
    if not ip:
541 19ddc57a René Nussbaumer
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
542 19ddc57a René Nussbaumer
              " present")
543 19ddc57a René Nussbaumer
    utils.AddHostToEtcHosts(host, ip)
544 19ddc57a René Nussbaumer
  elif mode == constants.ETC_HOSTS_REMOVE:
545 19ddc57a René Nussbaumer
    if ip:
546 19ddc57a René Nussbaumer
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
547 19ddc57a René Nussbaumer
              " parameter is present")
548 19ddc57a René Nussbaumer
    utils.RemoveHostFromEtcHosts(host)
549 19ddc57a René Nussbaumer
  else:
550 19ddc57a René Nussbaumer
    RPCFail("Mode not supported")
551 19ddc57a René Nussbaumer
552 19ddc57a René Nussbaumer
553 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
554 10c2650b Iustin Pop
  """Cleans up and remove the current node.
555 10c2650b Iustin Pop

556 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
557 10c2650b Iustin Pop
  from the cluster.
558 10c2650b Iustin Pop

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

563 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
564 b989b9d9 Ken Wehr

565 a8083063 Iustin Pop
  """
566 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.DATA_DIR)
567 710f30ec Michael Hanselmann
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
568 1bc59f76 Michael Hanselmann
  JobQueuePurge()
569 f78346f5 Michael Hanselmann
570 b989b9d9 Ken Wehr
  if modify_ssh_setup:
571 b989b9d9 Ken Wehr
    try:
572 052783ff Michael Hanselmann
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
573 7900ed01 Iustin Pop
574 b989b9d9 Ken Wehr
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
575 a8083063 Iustin Pop
576 b989b9d9 Ken Wehr
      utils.RemoveFile(priv_key)
577 b989b9d9 Ken Wehr
      utils.RemoveFile(pub_key)
578 b989b9d9 Ken Wehr
    except errors.OpExecError:
579 b989b9d9 Ken Wehr
      logging.exception("Error while processing ssh files")
580 a8083063 Iustin Pop
581 ed008420 Guido Trotter
  try:
582 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
583 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
584 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
585 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
586 710f30ec Michael Hanselmann
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
587 b459a848 Andrea Spadaccini
  except: # pylint: disable=W0702
588 ed008420 Guido Trotter
    logging.exception("Error while removing cluster secrets")
589 ed008420 Guido Trotter
590 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
591 f154a7a3 Michael Hanselmann
  if result.failed:
592 f154a7a3 Michael Hanselmann
    logging.error("Command %s failed with exitcode %s and error %s",
593 f154a7a3 Michael Hanselmann
                  result.cmd, result.exit_code, result.output)
594 ed008420 Guido Trotter
595 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
596 d0c8c01d Iustin Pop
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
597 6d8b6238 Guido Trotter
598 a8083063 Iustin Pop
599 1a3c5d4e Bernardo Dal Seno
def _GetVgInfo(name, excl_stor):
600 78519c10 Michael Hanselmann
  """Retrieves information about a LVM volume group.
601 78519c10 Michael Hanselmann

602 78519c10 Michael Hanselmann
  """
603 78519c10 Michael Hanselmann
  # TODO: GetVGInfo supports returning information for multiple VGs at once
604 1a3c5d4e Bernardo Dal Seno
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
605 78519c10 Michael Hanselmann
  if vginfo:
606 78519c10 Michael Hanselmann
    vg_free = int(round(vginfo[0][0], 0))
607 78519c10 Michael Hanselmann
    vg_size = int(round(vginfo[0][1], 0))
608 78519c10 Michael Hanselmann
  else:
609 78519c10 Michael Hanselmann
    vg_free = None
610 78519c10 Michael Hanselmann
    vg_size = None
611 78519c10 Michael Hanselmann
612 78519c10 Michael Hanselmann
  return {
613 78519c10 Michael Hanselmann
    "name": name,
614 1e89a135 Michael Hanselmann
    "vg_free": vg_free,
615 1e89a135 Michael Hanselmann
    "vg_size": vg_size,
616 78519c10 Michael Hanselmann
    }
617 78519c10 Michael Hanselmann
618 78519c10 Michael Hanselmann
619 78519c10 Michael Hanselmann
def _GetHvInfo(name):
620 78519c10 Michael Hanselmann
  """Retrieves node information from a hypervisor.
621 78519c10 Michael Hanselmann

622 78519c10 Michael Hanselmann
  The information returned depends on the hypervisor. Common items:
623 78519c10 Michael Hanselmann

624 78519c10 Michael Hanselmann
    - vg_size is the size of the configured volume group in MiB
625 78519c10 Michael Hanselmann
    - vg_free is the free size of the volume group in MiB
626 78519c10 Michael Hanselmann
    - memory_dom0 is the memory allocated for domain0 in MiB
627 78519c10 Michael Hanselmann
    - memory_free is the currently available (free) ram in MiB
628 78519c10 Michael Hanselmann
    - memory_total is the total number of ram in MiB
629 78519c10 Michael Hanselmann
    - hv_version: the hypervisor version, if available
630 78519c10 Michael Hanselmann

631 78519c10 Michael Hanselmann
  """
632 78519c10 Michael Hanselmann
  return hypervisor.GetHypervisor(name).GetNodeInfo()
633 78519c10 Michael Hanselmann
634 78519c10 Michael Hanselmann
635 78519c10 Michael Hanselmann
def _GetNamedNodeInfo(names, fn):
636 78519c10 Michael Hanselmann
  """Calls C{fn} for all names in C{names} and returns a dictionary.
637 78519c10 Michael Hanselmann

638 78519c10 Michael Hanselmann
  @rtype: None or dict
639 78519c10 Michael Hanselmann

640 78519c10 Michael Hanselmann
  """
641 78519c10 Michael Hanselmann
  if names is None:
642 78519c10 Michael Hanselmann
    return None
643 78519c10 Michael Hanselmann
  else:
644 ff3be305 Michael Hanselmann
    return map(fn, names)
645 78519c10 Michael Hanselmann
646 78519c10 Michael Hanselmann
647 1a3c5d4e Bernardo Dal Seno
def GetNodeInfo(vg_names, hv_names, excl_stor):
648 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
649 a8083063 Iustin Pop

650 78519c10 Michael Hanselmann
  @type vg_names: list of string
651 78519c10 Michael Hanselmann
  @param vg_names: Names of the volume groups to ask for disk space information
652 78519c10 Michael Hanselmann
  @type hv_names: list of string
653 78519c10 Michael Hanselmann
  @param hv_names: Names of the hypervisors to ask for node information
654 1a3c5d4e Bernardo Dal Seno
  @type excl_stor: boolean
655 1a3c5d4e Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
656 78519c10 Michael Hanselmann
  @rtype: tuple; (string, None/dict, None/dict)
657 78519c10 Michael Hanselmann
  @return: Tuple containing boot ID, volume group information and hypervisor
658 78519c10 Michael Hanselmann
    information
659 a8083063 Iustin Pop

660 098c0958 Michael Hanselmann
  """
661 78519c10 Michael Hanselmann
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
662 1a3c5d4e Bernardo Dal Seno
  vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
663 78519c10 Michael Hanselmann
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
664 78519c10 Michael Hanselmann
665 78519c10 Michael Hanselmann
  return (bootid, vg_info, hv_info)
666 a8083063 Iustin Pop
667 a8083063 Iustin Pop
668 d5a690cb Bernardo Dal Seno
def _CheckExclusivePvs(pvi_list):
669 d5a690cb Bernardo Dal Seno
  """Check that PVs are not shared among LVs
670 d5a690cb Bernardo Dal Seno

671 d5a690cb Bernardo Dal Seno
  @type pvi_list: list of L{objects.LvmPvInfo} objects
672 d5a690cb Bernardo Dal Seno
  @param pvi_list: information about the PVs
673 d5a690cb Bernardo Dal Seno

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

677 d5a690cb Bernardo Dal Seno
  """
678 d5a690cb Bernardo Dal Seno
  res = []
679 d5a690cb Bernardo Dal Seno
  for pvi in pvi_list:
680 d5a690cb Bernardo Dal Seno
    if len(pvi.lv_list) > 1:
681 d5a690cb Bernardo Dal Seno
      res.append((pvi.name, pvi.lv_list))
682 d5a690cb Bernardo Dal Seno
  return res
683 d5a690cb Bernardo Dal Seno
684 d5a690cb Bernardo Dal Seno
685 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
686 a8083063 Iustin Pop
  """Verify the status of the local node.
687 a8083063 Iustin Pop

688 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
689 e69d05fd Iustin Pop
  local node.
690 e69d05fd Iustin Pop

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

694 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
695 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
696 e69d05fd Iustin Pop
  report).
697 a8083063 Iustin Pop

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

702 e69d05fd Iustin Pop
  @type what: C{dict}
703 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
704 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
705 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
706 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
707 e69d05fd Iustin Pop
        connectivity with
708 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
709 10c2650b Iustin Pop
  @rtype: dict
710 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
711 10c2650b Iustin Pop
      values representing the result of the checks
712 a8083063 Iustin Pop

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

909 2be7273c Apollon Oikonomopoulos
  @type devices: list
910 2be7273c Apollon Oikonomopoulos
  @param devices: list of block device nodes to query
911 2be7273c Apollon Oikonomopoulos
  @rtype: dict
912 2be7273c Apollon Oikonomopoulos
  @return:
913 2be7273c Apollon Oikonomopoulos
    dictionary of all block devices under /dev (key). The value is their
914 2be7273c Apollon Oikonomopoulos
    size in MiB.
915 2be7273c Apollon Oikonomopoulos

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

918 2be7273c Apollon Oikonomopoulos
  """
919 2be7273c Apollon Oikonomopoulos
  DEV_PREFIX = "/dev/"
920 2be7273c Apollon Oikonomopoulos
  blockdevs = {}
921 2be7273c Apollon Oikonomopoulos
922 2be7273c Apollon Oikonomopoulos
  for devpath in devices:
923 cf00dba0 René Nussbaumer
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
924 2be7273c Apollon Oikonomopoulos
      continue
925 2be7273c Apollon Oikonomopoulos
926 2be7273c Apollon Oikonomopoulos
    try:
927 2be7273c Apollon Oikonomopoulos
      st = os.stat(devpath)
928 2be7273c Apollon Oikonomopoulos
    except EnvironmentError, err:
929 2be7273c Apollon Oikonomopoulos
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
930 2be7273c Apollon Oikonomopoulos
      continue
931 2be7273c Apollon Oikonomopoulos
932 2be7273c Apollon Oikonomopoulos
    if stat.S_ISBLK(st.st_mode):
933 2be7273c Apollon Oikonomopoulos
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
934 2be7273c Apollon Oikonomopoulos
      if result.failed:
935 2be7273c Apollon Oikonomopoulos
        # We don't want to fail, just do not list this device as available
936 2be7273c Apollon Oikonomopoulos
        logging.warning("Cannot get size for block device %s", devpath)
937 2be7273c Apollon Oikonomopoulos
        continue
938 2be7273c Apollon Oikonomopoulos
939 2be7273c Apollon Oikonomopoulos
      size = int(result.stdout) / (1024 * 1024)
940 2be7273c Apollon Oikonomopoulos
      blockdevs[devpath] = size
941 2be7273c Apollon Oikonomopoulos
  return blockdevs
942 2be7273c Apollon Oikonomopoulos
943 2be7273c Apollon Oikonomopoulos
944 84d7e26b Dmitry Chernyak
def GetVolumeList(vg_names):
945 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
946 a8083063 Iustin Pop

947 84d7e26b Dmitry Chernyak
  @type vg_names: list
948 397693d3 Iustin Pop
  @param vg_names: the volume groups whose LVs we should list, or
949 397693d3 Iustin Pop
      empty for all volume groups
950 10c2650b Iustin Pop
  @rtype: dict
951 10c2650b Iustin Pop
  @return:
952 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
953 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
954 10c2650b Iustin Pop

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

957 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
958 10c2650b Iustin Pop
      details.
959 a8083063 Iustin Pop

960 a8083063 Iustin Pop
  """
961 cb2037a2 Iustin Pop
  lvs = {}
962 d0c8c01d Iustin Pop
  sep = "|"
963 397693d3 Iustin Pop
  if not vg_names:
964 397693d3 Iustin Pop
    vg_names = []
965 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
966 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
967 84d7e26b Dmitry Chernyak
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
968 a8083063 Iustin Pop
  if result.failed:
969 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
970 cb2037a2 Iustin Pop
971 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
972 df4c2628 Iustin Pop
    line = line.strip()
973 0b5303da Iustin Pop
    match = _LVSLINE_REGEX.match(line)
974 df4c2628 Iustin Pop
    if not match:
975 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
976 df4c2628 Iustin Pop
      continue
977 84d7e26b Dmitry Chernyak
    vg_name, name, size, attr = match.groups()
978 d0c8c01d Iustin Pop
    inactive = attr[4] == "-"
979 d0c8c01d Iustin Pop
    online = attr[5] == "o"
980 d0c8c01d Iustin Pop
    virtual = attr[0] == "v"
981 33f2a81a Iustin Pop
    if virtual:
982 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
983 33f2a81a Iustin Pop
      # don't really hold data
984 33f2a81a Iustin Pop
      continue
985 e687ec01 Michael Hanselmann
    lvs[vg_name + "/" + name] = (size, inactive, online)
986 cb2037a2 Iustin Pop
987 cb2037a2 Iustin Pop
  return lvs
988 a8083063 Iustin Pop
989 a8083063 Iustin Pop
990 a8083063 Iustin Pop
def ListVolumeGroups():
991 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
992 a8083063 Iustin Pop

993 10c2650b Iustin Pop
  @rtype: dict
994 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
995 10c2650b Iustin Pop
      size of the volume
996 a8083063 Iustin Pop

997 a8083063 Iustin Pop
  """
998 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
999 a8083063 Iustin Pop
1000 a8083063 Iustin Pop
1001 dcb93971 Michael Hanselmann
def NodeVolumes():
1002 dcb93971 Michael Hanselmann
  """List all volumes on this node.
1003 dcb93971 Michael Hanselmann

1004 10c2650b Iustin Pop
  @rtype: list
1005 10c2650b Iustin Pop
  @return:
1006 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
1007 10c2650b Iustin Pop
      - name: the logical volume name,
1008 10c2650b Iustin Pop
      - size: the size of the logical volume
1009 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
1010 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
1011 10c2650b Iustin Pop

1012 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
1013 10c2650b Iustin Pop
    error.
1014 10c2650b Iustin Pop

1015 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
1016 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
1017 10c2650b Iustin Pop
    multiple times.
1018 10c2650b Iustin Pop

1019 dcb93971 Michael Hanselmann
  """
1020 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1021 dcb93971 Michael Hanselmann
                         "--separator=|",
1022 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
1023 dcb93971 Michael Hanselmann
  if result.failed:
1024 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
1025 10bfe6cb Iustin Pop
          result.output)
1026 dcb93971 Michael Hanselmann
1027 dcb93971 Michael Hanselmann
  def parse_dev(dev):
1028 d0c8c01d Iustin Pop
    return dev.split("(")[0]
1029 89e5ab02 Iustin Pop
1030 89e5ab02 Iustin Pop
  def handle_dev(dev):
1031 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
1032 dcb93971 Michael Hanselmann
1033 dcb93971 Michael Hanselmann
  def map_line(line):
1034 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
1035 d0c8c01d Iustin Pop
    return [{"name": line[0], "size": line[1],
1036 d0c8c01d Iustin Pop
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1037 89e5ab02 Iustin Pop
1038 89e5ab02 Iustin Pop
  all_devs = []
1039 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
1040 d0c8c01d Iustin Pop
    if line.count("|") >= 3:
1041 d0c8c01d Iustin Pop
      all_devs.extend(map_line(line.split("|")))
1042 89e5ab02 Iustin Pop
    else:
1043 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
1044 89e5ab02 Iustin Pop
  return all_devs
1045 dcb93971 Michael Hanselmann
1046 dcb93971 Michael Hanselmann
1047 a8083063 Iustin Pop
def BridgesExist(bridges_list):
1048 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
1049 a8083063 Iustin Pop

1050 b1206984 Iustin Pop
  @rtype: boolean
1051 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
1052 a8083063 Iustin Pop

1053 a8083063 Iustin Pop
  """
1054 35c0c8da Iustin Pop
  missing = []
1055 a8083063 Iustin Pop
  for bridge in bridges_list:
1056 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
1057 35c0c8da Iustin Pop
      missing.append(bridge)
1058 a8083063 Iustin Pop
1059 35c0c8da Iustin Pop
  if missing:
1060 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1061 35c0c8da Iustin Pop
1062 a8083063 Iustin Pop
1063 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
1064 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
1065 a8083063 Iustin Pop

1066 e69d05fd Iustin Pop
  @type hypervisor_list: list
1067 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
1068 e69d05fd Iustin Pop

1069 e69d05fd Iustin Pop
  @rtype: list
1070 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
1071 10c2650b Iustin Pop
    - instance1.example.com
1072 10c2650b Iustin Pop
    - instance2.example.com
1073 a8083063 Iustin Pop

1074 098c0958 Michael Hanselmann
  """
1075 e69d05fd Iustin Pop
  results = []
1076 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1077 e69d05fd Iustin Pop
    try:
1078 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
1079 e69d05fd Iustin Pop
      results.extend(names)
1080 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
1081 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
1082 aca13712 Iustin Pop
            hname, err, exc=True)
1083 a8083063 Iustin Pop
1084 e69d05fd Iustin Pop
  return results
1085 a8083063 Iustin Pop
1086 a8083063 Iustin Pop
1087 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
1088 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
1089 a8083063 Iustin Pop

1090 e69d05fd Iustin Pop
  @type instance: string
1091 e69d05fd Iustin Pop
  @param instance: the instance name
1092 e69d05fd Iustin Pop
  @type hname: string
1093 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
1094 a8083063 Iustin Pop

1095 e69d05fd Iustin Pop
  @rtype: dict
1096 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
1097 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1098 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1099 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1100 1cb97324 Agata Murawska
      - vcpus: the number of vcpus (int)
1101 a8083063 Iustin Pop

1102 098c0958 Michael Hanselmann
  """
1103 a8083063 Iustin Pop
  output = {}
1104 a8083063 Iustin Pop
1105 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1106 a8083063 Iustin Pop
  if iinfo is not None:
1107 d0c8c01d Iustin Pop
    output["memory"] = iinfo[2]
1108 1cb97324 Agata Murawska
    output["vcpus"] = iinfo[3]
1109 d0c8c01d Iustin Pop
    output["state"] = iinfo[4]
1110 d0c8c01d Iustin Pop
    output["time"] = iinfo[5]
1111 a8083063 Iustin Pop
1112 c26a6bd2 Iustin Pop
  return output
1113 a8083063 Iustin Pop
1114 a8083063 Iustin Pop
1115 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
1116 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
1117 56e7640c Iustin Pop

1118 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
1119 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
1120 56e7640c Iustin Pop

1121 56e7640c Iustin Pop
  @rtype: tuple
1122 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
1123 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
1124 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
1125 56e7640c Iustin Pop

1126 56e7640c Iustin Pop
  """
1127 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1128 afdc3985 Iustin Pop
  iname = instance.name
1129 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
1130 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
1131 56e7640c Iustin Pop
1132 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
1133 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1134 56e7640c Iustin Pop
    if not os.path.islink(link_name):
1135 b8ebd37b Iustin Pop
      logging.warning("Instance %s is missing symlink %s for disk %d",
1136 b8ebd37b Iustin Pop
                      iname, link_name, idx)
1137 56e7640c Iustin Pop
1138 56e7640c Iustin Pop
1139 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
1140 a8083063 Iustin Pop
  """Gather data about all instances.
1141 a8083063 Iustin Pop

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

1146 e69d05fd Iustin Pop
  @type hypervisor_list: list
1147 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
1148 e69d05fd Iustin Pop

1149 955db481 Guido Trotter
  @rtype: dict
1150 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
1151 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
1152 e69d05fd Iustin Pop
      - state: xen state of instance (string)
1153 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
1154 10c2650b Iustin Pop
      - vcpus: the number of vcpus
1155 a8083063 Iustin Pop

1156 098c0958 Michael Hanselmann
  """
1157 a8083063 Iustin Pop
  output = {}
1158 a8083063 Iustin Pop
1159 e69d05fd Iustin Pop
  for hname in hypervisor_list:
1160 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1161 e69d05fd Iustin Pop
    if iinfo:
1162 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
1163 f23b5ae8 Iustin Pop
        value = {
1164 d0c8c01d Iustin Pop
          "memory": memory,
1165 d0c8c01d Iustin Pop
          "vcpus": vcpus,
1166 d0c8c01d Iustin Pop
          "state": state,
1167 d0c8c01d Iustin Pop
          "time": times,
1168 e69d05fd Iustin Pop
          }
1169 b33b6f55 Iustin Pop
        if name in output:
1170 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
1171 b33b6f55 Iustin Pop
          # and not state and time which can change between the
1172 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
1173 d0c8c01d Iustin Pop
          for key in "memory", "vcpus":
1174 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
1175 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
1176 2fa74ef4 Iustin Pop
                    " with different parameters", name)
1177 f23b5ae8 Iustin Pop
        output[name] = value
1178 a8083063 Iustin Pop
1179 c26a6bd2 Iustin Pop
  return output
1180 a8083063 Iustin Pop
1181 a8083063 Iustin Pop
1182 6aa7a354 Iustin Pop
def _InstanceLogName(kind, os_name, instance, component):
1183 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
1184 81a3406c Iustin Pop

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

1188 81a3406c Iustin Pop
  @type kind: string
1189 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
1190 81a3406c Iustin Pop
  @type os_name: string
1191 81a3406c Iustin Pop
  @param os_name: the os name
1192 81a3406c Iustin Pop
  @type instance: string
1193 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
1194 6aa7a354 Iustin Pop
  @type component: string or None
1195 6aa7a354 Iustin Pop
  @param component: the name of the component of the instance being
1196 6aa7a354 Iustin Pop
      transferred
1197 81a3406c Iustin Pop

1198 81a3406c Iustin Pop
  """
1199 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
1200 6aa7a354 Iustin Pop
  if component:
1201 6aa7a354 Iustin Pop
    assert "/" not in component
1202 6aa7a354 Iustin Pop
    c_msg = "-%s" % component
1203 6aa7a354 Iustin Pop
  else:
1204 6aa7a354 Iustin Pop
    c_msg = ""
1205 6aa7a354 Iustin Pop
  base = ("%s-%s-%s%s-%s.log" %
1206 6aa7a354 Iustin Pop
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1207 710f30ec Michael Hanselmann
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1208 81a3406c Iustin Pop
1209 81a3406c Iustin Pop
1210 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
1211 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
1212 a8083063 Iustin Pop

1213 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
1214 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1215 e557bae9 Guido Trotter
  @type reinstall: boolean
1216 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
1217 4a0e011f Iustin Pop
  @type debug: integer
1218 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1219 c26a6bd2 Iustin Pop
  @rtype: None
1220 a8083063 Iustin Pop

1221 a8083063 Iustin Pop
  """
1222 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
1223 255dcebd Iustin Pop
1224 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
1225 e557bae9 Guido Trotter
  if reinstall:
1226 d0c8c01d Iustin Pop
    create_env["INSTANCE_REINSTALL"] = "1"
1227 a8083063 Iustin Pop
1228 6aa7a354 Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1229 decd5f45 Iustin Pop
1230 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1231 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1232 decd5f45 Iustin Pop
  if result.failed:
1233 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1234 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
1235 18682bca Iustin Pop
                  result.output)
1236 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1237 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1238 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
1239 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1240 decd5f45 Iustin Pop
1241 decd5f45 Iustin Pop
1242 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
1243 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
1244 decd5f45 Iustin Pop

1245 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1246 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
1247 d15a9ad3 Guido Trotter
  @type old_name: string
1248 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
1249 4a0e011f Iustin Pop
  @type debug: integer
1250 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
1251 10c2650b Iustin Pop
  @rtype: boolean
1252 10c2650b Iustin Pop
  @return: the success of the operation
1253 decd5f45 Iustin Pop

1254 decd5f45 Iustin Pop
  """
1255 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1256 decd5f45 Iustin Pop
1257 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
1258 d0c8c01d Iustin Pop
  rename_env["OLD_INSTANCE_NAME"] = old_name
1259 decd5f45 Iustin Pop
1260 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
1261 6aa7a354 Iustin Pop
                             "%s-%s" % (old_name, instance.name), None)
1262 a8083063 Iustin Pop
1263 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1264 896a03f6 Iustin Pop
                        cwd=inst_os.path, output=logfile, reset_env=True)
1265 a8083063 Iustin Pop
1266 a8083063 Iustin Pop
  if result.failed:
1267 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
1268 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
1269 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
1270 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
1271 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
1272 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1273 a8083063 Iustin Pop
1274 a8083063 Iustin Pop
1275 3b721842 Michael Hanselmann
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1276 3b721842 Michael Hanselmann
  """Returns symlink path for block device.
1277 3b721842 Michael Hanselmann

1278 3b721842 Michael Hanselmann
  """
1279 3b721842 Michael Hanselmann
  if _dir is None:
1280 3b721842 Michael Hanselmann
    _dir = pathutils.DISK_LINKS_DIR
1281 3b721842 Michael Hanselmann
1282 3b721842 Michael Hanselmann
  return utils.PathJoin(_dir,
1283 3b721842 Michael Hanselmann
                        ("%s%s%s" %
1284 3b721842 Michael Hanselmann
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1285 5282084b Iustin Pop
1286 5282084b Iustin Pop
1287 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
1288 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
1289 9332fd8a Iustin Pop

1290 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
1291 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
1292 9332fd8a Iustin Pop

1293 9332fd8a Iustin Pop

1294 5282084b Iustin Pop
  @param instance_name: the name of the target instance
1295 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
1296 5282084b Iustin Pop
  @param idx: the disk index
1297 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
1298 9332fd8a Iustin Pop

1299 9332fd8a Iustin Pop
  """
1300 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1301 9332fd8a Iustin Pop
  try:
1302 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
1303 5282084b Iustin Pop
  except OSError, err:
1304 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
1305 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
1306 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
1307 9332fd8a Iustin Pop
        os.remove(link_name)
1308 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
1309 9332fd8a Iustin Pop
    else:
1310 9332fd8a Iustin Pop
      raise
1311 9332fd8a Iustin Pop
1312 9332fd8a Iustin Pop
  return link_name
1313 9332fd8a Iustin Pop
1314 9332fd8a Iustin Pop
1315 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
1316 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
1317 3c9c571d Iustin Pop

1318 3c9c571d Iustin Pop
  """
1319 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1320 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1321 5282084b Iustin Pop
    if os.path.islink(link_name):
1322 3c9c571d Iustin Pop
      try:
1323 03dfa658 Iustin Pop
        os.remove(link_name)
1324 03dfa658 Iustin Pop
      except OSError:
1325 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1326 3c9c571d Iustin Pop
1327 3c9c571d Iustin Pop
1328 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1329 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1330 a8083063 Iustin Pop

1331 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1332 a8083063 Iustin Pop
  devices must be already assembled.
1333 a8083063 Iustin Pop

1334 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1335 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1336 069cfbf1 Iustin Pop
  @rtype: list
1337 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1338 10c2650b Iustin Pop

1339 a8083063 Iustin Pop
  """
1340 a8083063 Iustin Pop
  block_devices = []
1341 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1342 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1343 a8083063 Iustin Pop
    if device is None:
1344 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1345 a8083063 Iustin Pop
                                    str(disk))
1346 a8083063 Iustin Pop
    device.Open()
1347 9332fd8a Iustin Pop
    try:
1348 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1349 9332fd8a Iustin Pop
    except OSError, e:
1350 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1351 9332fd8a Iustin Pop
                                    e.strerror)
1352 9332fd8a Iustin Pop
1353 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1354 9332fd8a Iustin Pop
1355 a8083063 Iustin Pop
  return block_devices
1356 a8083063 Iustin Pop
1357 a8083063 Iustin Pop
1358 323f9095 Stephen Shirley
def StartInstance(instance, startup_paused):
1359 a8083063 Iustin Pop
  """Start an instance.
1360 a8083063 Iustin Pop

1361 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1362 e69d05fd Iustin Pop
  @param instance: the instance object
1363 323f9095 Stephen Shirley
  @type startup_paused: bool
1364 323f9095 Stephen Shirley
  @param instance: pause instance at startup?
1365 c26a6bd2 Iustin Pop
  @rtype: None
1366 a8083063 Iustin Pop

1367 098c0958 Michael Hanselmann
  """
1368 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1369 a8083063 Iustin Pop
1370 a8083063 Iustin Pop
  if instance.name in running_instances:
1371 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1372 c26a6bd2 Iustin Pop
    return
1373 a8083063 Iustin Pop
1374 a8083063 Iustin Pop
  try:
1375 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1376 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1377 323f9095 Stephen Shirley
    hyper.StartInstance(instance, block_devices, startup_paused)
1378 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1379 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1380 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1381 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1382 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1383 a8083063 Iustin Pop
1384 a8083063 Iustin Pop
1385 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1386 a8083063 Iustin Pop
  """Shut an instance down.
1387 a8083063 Iustin Pop

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

1390 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1391 e69d05fd Iustin Pop
  @param instance: the instance object
1392 6263189c Guido Trotter
  @type timeout: integer
1393 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1394 c26a6bd2 Iustin Pop
  @rtype: None
1395 a8083063 Iustin Pop

1396 098c0958 Michael Hanselmann
  """
1397 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1398 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1399 c26a6bd2 Iustin Pop
  iname = instance.name
1400 a8083063 Iustin Pop
1401 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1402 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1403 c26a6bd2 Iustin Pop
    return
1404 a8083063 Iustin Pop
1405 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1406 3c0cdc83 Michael Hanselmann
    def __init__(self):
1407 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1408 a8083063 Iustin Pop
1409 3c0cdc83 Michael Hanselmann
    def __call__(self):
1410 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1411 3c0cdc83 Michael Hanselmann
        return
1412 3c0cdc83 Michael Hanselmann
1413 3c0cdc83 Michael Hanselmann
      try:
1414 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1415 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1416 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1417 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1418 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1419 3c0cdc83 Michael Hanselmann
          return
1420 3c0cdc83 Michael Hanselmann
1421 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1422 3c0cdc83 Michael Hanselmann
1423 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1424 3c0cdc83 Michael Hanselmann
1425 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1426 3c0cdc83 Michael Hanselmann
1427 3c0cdc83 Michael Hanselmann
  try:
1428 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1429 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1430 a8083063 Iustin Pop
    # the shutdown did not succeed
1431 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1432 a8083063 Iustin Pop
1433 a8083063 Iustin Pop
    try:
1434 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1435 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1436 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1437 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1438 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1439 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1440 a8083063 Iustin Pop
1441 a8083063 Iustin Pop
    time.sleep(1)
1442 3c0cdc83 Michael Hanselmann
1443 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1444 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1445 3c9c571d Iustin Pop
1446 f28ec899 Guido Trotter
  try:
1447 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1448 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1449 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1450 f28ec899 Guido Trotter
1451 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1452 a8083063 Iustin Pop
1453 a8083063 Iustin Pop
1454 4a90bd4f Michele Tartara
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1455 007a2f3e Alexander Schreiber
  """Reboot an instance.
1456 007a2f3e Alexander Schreiber

1457 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1458 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1459 10c2650b Iustin Pop
  @type reboot_type: str
1460 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1461 10c2650b Iustin Pop
    constants:
1462 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1463 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1464 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1465 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1466 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1467 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1468 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1469 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1470 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1471 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1472 c26a6bd2 Iustin Pop
  @rtype: None
1473 007a2f3e Alexander Schreiber

1474 007a2f3e Alexander Schreiber
  """
1475 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1476 007a2f3e Alexander Schreiber
1477 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1478 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1479 007a2f3e Alexander Schreiber
1480 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1481 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1482 007a2f3e Alexander Schreiber
    try:
1483 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1484 4a90bd4f Michele Tartara
      reason.Store(instance.name)
1485 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1486 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1487 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1488 007a2f3e Alexander Schreiber
    try:
1489 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1490 4a90bd4f Michele Tartara
      result = StartInstance(instance, False)
1491 4a90bd4f Michele Tartara
      reason.Store(instance.name)
1492 4a90bd4f Michele Tartara
      return result
1493 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1494 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1495 007a2f3e Alexander Schreiber
  else:
1496 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1497 007a2f3e Alexander Schreiber
1498 007a2f3e Alexander Schreiber
1499 ebe466d8 Guido Trotter
def InstanceBalloonMemory(instance, memory):
1500 ebe466d8 Guido Trotter
  """Resize an instance's memory.
1501 ebe466d8 Guido Trotter

1502 ebe466d8 Guido Trotter
  @type instance: L{objects.Instance}
1503 ebe466d8 Guido Trotter
  @param instance: the instance object
1504 ebe466d8 Guido Trotter
  @type memory: int
1505 ebe466d8 Guido Trotter
  @param memory: new memory amount in MB
1506 ebe466d8 Guido Trotter
  @rtype: None
1507 ebe466d8 Guido Trotter

1508 ebe466d8 Guido Trotter
  """
1509 ebe466d8 Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1510 ebe466d8 Guido Trotter
  running = hyper.ListInstances()
1511 ebe466d8 Guido Trotter
  if instance.name not in running:
1512 ebe466d8 Guido Trotter
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1513 ebe466d8 Guido Trotter
    return
1514 ebe466d8 Guido Trotter
  try:
1515 ebe466d8 Guido Trotter
    hyper.BalloonInstanceMemory(instance, memory)
1516 ebe466d8 Guido Trotter
  except errors.HypervisorError, err:
1517 ebe466d8 Guido Trotter
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1518 ebe466d8 Guido Trotter
1519 ebe466d8 Guido Trotter
1520 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1521 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1522 6906a9d8 Guido Trotter

1523 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1524 6906a9d8 Guido Trotter
  @param instance: the instance definition
1525 6906a9d8 Guido Trotter

1526 6906a9d8 Guido Trotter
  """
1527 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1528 cd42d0ad Guido Trotter
  try:
1529 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1530 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1531 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1532 c26a6bd2 Iustin Pop
  return info
1533 6906a9d8 Guido Trotter
1534 6906a9d8 Guido Trotter
1535 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1536 6906a9d8 Guido Trotter
  """Prepare the node 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 target: string
1543 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1544 6906a9d8 Guido Trotter

1545 6906a9d8 Guido Trotter
  """
1546 77fcff4a Apollon Oikonomopoulos
  # TODO: why is this required only for DTS_EXT_MIRROR?
1547 77fcff4a Apollon Oikonomopoulos
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1548 77fcff4a Apollon Oikonomopoulos
    # Create the symlinks, as the disks are not active
1549 77fcff4a Apollon Oikonomopoulos
    # in any way
1550 77fcff4a Apollon Oikonomopoulos
    try:
1551 77fcff4a Apollon Oikonomopoulos
      _GatherAndLinkBlockDevs(instance)
1552 77fcff4a Apollon Oikonomopoulos
    except errors.BlockDeviceError, err:
1553 77fcff4a Apollon Oikonomopoulos
      _Fail("Block device error: %s", err, exc=True)
1554 77fcff4a Apollon Oikonomopoulos
1555 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1556 cd42d0ad Guido Trotter
  try:
1557 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1558 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1559 77fcff4a Apollon Oikonomopoulos
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1560 77fcff4a Apollon Oikonomopoulos
      _RemoveBlockDevLinks(instance.name, instance.disks)
1561 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1562 6906a9d8 Guido Trotter
1563 6906a9d8 Guido Trotter
1564 6a1434d7 Andrea Spadaccini
def FinalizeMigrationDst(instance, info, success):
1565 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1566 6906a9d8 Guido Trotter

1567 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1568 6906a9d8 Guido Trotter
  @param instance: the instance definition
1569 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1570 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1571 6906a9d8 Guido Trotter
  @type success: boolean
1572 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1573 6906a9d8 Guido Trotter

1574 6906a9d8 Guido Trotter
  """
1575 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1576 cd42d0ad Guido Trotter
  try:
1577 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationDst(instance, info, success)
1578 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1579 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1580 6906a9d8 Guido Trotter
1581 6906a9d8 Guido Trotter
1582 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1583 2a10865c Iustin Pop
  """Migrates an instance to another node.
1584 2a10865c Iustin Pop

1585 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1586 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1587 9f0e6b37 Iustin Pop
  @type target: string
1588 9f0e6b37 Iustin Pop
  @param target: the target node name
1589 9f0e6b37 Iustin Pop
  @type live: boolean
1590 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1591 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1592 c03fe62b Andrea Spadaccini
  @raise RPCFail: if migration fails for some reason
1593 9f0e6b37 Iustin Pop

1594 2a10865c Iustin Pop
  """
1595 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1596 2a10865c Iustin Pop
1597 2a10865c Iustin Pop
  try:
1598 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1599 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1600 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1601 2a10865c Iustin Pop
1602 2a10865c Iustin Pop
1603 6a1434d7 Andrea Spadaccini
def FinalizeMigrationSource(instance, success, live):
1604 6a1434d7 Andrea Spadaccini
  """Finalize the instance migration on the source node.
1605 6a1434d7 Andrea Spadaccini

1606 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1607 6a1434d7 Andrea Spadaccini
  @param instance: the instance definition of the migrated instance
1608 6a1434d7 Andrea Spadaccini
  @type success: bool
1609 6a1434d7 Andrea Spadaccini
  @param success: whether the migration succeeded or not
1610 6a1434d7 Andrea Spadaccini
  @type live: bool
1611 6a1434d7 Andrea Spadaccini
  @param live: whether the user requested a live migration or not
1612 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the execution fails for some reason
1613 6a1434d7 Andrea Spadaccini

1614 6a1434d7 Andrea Spadaccini
  """
1615 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1616 6a1434d7 Andrea Spadaccini
1617 6a1434d7 Andrea Spadaccini
  try:
1618 6a1434d7 Andrea Spadaccini
    hyper.FinalizeMigrationSource(instance, success, live)
1619 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1620 6a1434d7 Andrea Spadaccini
    _Fail("Failed to finalize the migration on the source node: %s", err,
1621 6a1434d7 Andrea Spadaccini
          exc=True)
1622 6a1434d7 Andrea Spadaccini
1623 6a1434d7 Andrea Spadaccini
1624 6a1434d7 Andrea Spadaccini
def GetMigrationStatus(instance):
1625 6a1434d7 Andrea Spadaccini
  """Get the migration status
1626 6a1434d7 Andrea Spadaccini

1627 6a1434d7 Andrea Spadaccini
  @type instance: L{objects.Instance}
1628 6a1434d7 Andrea Spadaccini
  @param instance: the instance that is being migrated
1629 6a1434d7 Andrea Spadaccini
  @rtype: L{objects.MigrationStatus}
1630 6a1434d7 Andrea Spadaccini
  @return: the status of the current migration (one of
1631 6a1434d7 Andrea Spadaccini
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1632 6a1434d7 Andrea Spadaccini
           progress info that can be retrieved from the hypervisor
1633 6a1434d7 Andrea Spadaccini
  @raise RPCFail: If the migration status cannot be retrieved
1634 6a1434d7 Andrea Spadaccini

1635 6a1434d7 Andrea Spadaccini
  """
1636 6a1434d7 Andrea Spadaccini
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1637 6a1434d7 Andrea Spadaccini
  try:
1638 6a1434d7 Andrea Spadaccini
    return hyper.GetMigrationStatus(instance)
1639 6a1434d7 Andrea Spadaccini
  except Exception, err:  # pylint: disable=W0703
1640 6a1434d7 Andrea Spadaccini
    _Fail("Failed to get migration status: %s", err, exc=True)
1641 6a1434d7 Andrea Spadaccini
1642 6a1434d7 Andrea Spadaccini
1643 ee1478e5 Bernardo Dal Seno
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1644 a8083063 Iustin Pop
  """Creates a block device for an instance.
1645 a8083063 Iustin Pop

1646 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1647 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1648 b1206984 Iustin Pop
  @type size: int
1649 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1650 b1206984 Iustin Pop
  @type owner: str
1651 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1652 b1206984 Iustin Pop
      used for device cache data
1653 b1206984 Iustin Pop
  @type on_primary: boolean
1654 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1655 b1206984 Iustin Pop
  @type info: string
1656 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1657 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1658 ee1478e5 Bernardo Dal Seno
  @type excl_stor: boolean
1659 ee1478e5 Bernardo Dal Seno
  @param excl_stor: Whether exclusive_storage is active
1660 b1206984 Iustin Pop

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

1665 a8083063 Iustin Pop
  """
1666 d0c8c01d Iustin Pop
  # TODO: remove the obsolete "size" argument
1667 b459a848 Andrea Spadaccini
  # pylint: disable=W0613
1668 a8083063 Iustin Pop
  clist = []
1669 a8083063 Iustin Pop
  if disk.children:
1670 a8083063 Iustin Pop
    for child in disk.children:
1671 1063abd1 Iustin Pop
      try:
1672 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1673 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1674 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1675 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1676 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1677 a8083063 Iustin Pop
        # be assembled
1678 1063abd1 Iustin Pop
        try:
1679 b459a848 Andrea Spadaccini
          # pylint: disable=E1103
1680 1063abd1 Iustin Pop
          crdev.Open()
1681 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1682 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1683 a8083063 Iustin Pop
      clist.append(crdev)
1684 a8083063 Iustin Pop
1685 dab69e97 Iustin Pop
  try:
1686 ee1478e5 Bernardo Dal Seno
    device = bdev.Create(disk, clist, excl_stor)
1687 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1688 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1689 6c626518 Iustin Pop
1690 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1691 1063abd1 Iustin Pop
    try:
1692 1063abd1 Iustin Pop
      device.Assemble()
1693 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1694 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1695 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1696 1063abd1 Iustin Pop
      try:
1697 1063abd1 Iustin Pop
        device.Open(force=True)
1698 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1699 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1700 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1701 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1702 a0c3fea1 Michael Hanselmann
1703 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1704 a0c3fea1 Michael Hanselmann
1705 c26a6bd2 Iustin Pop
  return device.unique_id
1706 a8083063 Iustin Pop
1707 a8083063 Iustin Pop
1708 da63bb4e René Nussbaumer
def _WipeDevice(path, offset, size):
1709 69dd363f René Nussbaumer
  """This function actually wipes the device.
1710 69dd363f René Nussbaumer

1711 69dd363f René Nussbaumer
  @param path: The path to the device to wipe
1712 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1713 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1714 69dd363f René Nussbaumer

1715 69dd363f René Nussbaumer
  """
1716 0188611b Michael Hanselmann
  # Internal sizes are always in Mebibytes; if the following "dd" command
1717 0188611b Michael Hanselmann
  # should use a different block size the offset and size given to this
1718 0188611b Michael Hanselmann
  # function must be adjusted accordingly before being passed to "dd".
1719 0188611b Michael Hanselmann
  block_size = 1024 * 1024
1720 0188611b Michael Hanselmann
1721 da63bb4e René Nussbaumer
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1722 0188611b Michael Hanselmann
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1723 da63bb4e René Nussbaumer
         "count=%d" % size]
1724 da63bb4e René Nussbaumer
  result = utils.RunCmd(cmd)
1725 69dd363f René Nussbaumer
1726 69dd363f René Nussbaumer
  if result.failed:
1727 69dd363f René Nussbaumer
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1728 69dd363f René Nussbaumer
          result.fail_reason, result.output)
1729 69dd363f René Nussbaumer
1730 69dd363f René Nussbaumer
1731 da63bb4e René Nussbaumer
def BlockdevWipe(disk, offset, size):
1732 69dd363f René Nussbaumer
  """Wipes a block device.
1733 69dd363f René Nussbaumer

1734 69dd363f René Nussbaumer
  @type disk: L{objects.Disk}
1735 69dd363f René Nussbaumer
  @param disk: the disk object we want to wipe
1736 da63bb4e René Nussbaumer
  @type offset: int
1737 da63bb4e René Nussbaumer
  @param offset: The offset in MiB in the file
1738 da63bb4e René Nussbaumer
  @type size: int
1739 da63bb4e René Nussbaumer
  @param size: The size in MiB to write
1740 69dd363f René Nussbaumer

1741 69dd363f René Nussbaumer
  """
1742 69dd363f René Nussbaumer
  try:
1743 69dd363f René Nussbaumer
    rdev = _RecursiveFindBD(disk)
1744 da63bb4e René Nussbaumer
  except errors.BlockDeviceError:
1745 da63bb4e René Nussbaumer
    rdev = None
1746 da63bb4e René Nussbaumer
1747 da63bb4e René Nussbaumer
  if not rdev:
1748 da63bb4e René Nussbaumer
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1749 da63bb4e René Nussbaumer
1750 da63bb4e René Nussbaumer
  # Do cross verify some of the parameters
1751 0188611b Michael Hanselmann
  if offset < 0:
1752 0188611b Michael Hanselmann
    _Fail("Negative offset")
1753 0188611b Michael Hanselmann
  if size < 0:
1754 0188611b Michael Hanselmann
    _Fail("Negative size")
1755 da63bb4e René Nussbaumer
  if offset > rdev.size:
1756 da63bb4e René Nussbaumer
    _Fail("Offset is bigger than device size")
1757 da63bb4e René Nussbaumer
  if (offset + size) > rdev.size:
1758 da63bb4e René Nussbaumer
    _Fail("The provided offset and size to wipe is bigger than device size")
1759 69dd363f René Nussbaumer
1760 da63bb4e René Nussbaumer
  _WipeDevice(rdev.dev_path, offset, size)
1761 69dd363f René Nussbaumer
1762 69dd363f René Nussbaumer
1763 5119c79e René Nussbaumer
def BlockdevPauseResumeSync(disks, pause):
1764 5119c79e René Nussbaumer
  """Pause or resume the sync of the block device.
1765 5119c79e René Nussbaumer

1766 0f39886a René Nussbaumer
  @type disks: list of L{objects.Disk}
1767 0f39886a René Nussbaumer
  @param disks: the disks object we want to pause/resume
1768 5119c79e René Nussbaumer
  @type pause: bool
1769 5119c79e René Nussbaumer
  @param pause: Wheater to pause or resume
1770 5119c79e René Nussbaumer

1771 5119c79e René Nussbaumer
  """
1772 5119c79e René Nussbaumer
  success = []
1773 5119c79e René Nussbaumer
  for disk in disks:
1774 5119c79e René Nussbaumer
    try:
1775 5119c79e René Nussbaumer
      rdev = _RecursiveFindBD(disk)
1776 5119c79e René Nussbaumer
    except errors.BlockDeviceError:
1777 5119c79e René Nussbaumer
      rdev = None
1778 5119c79e René Nussbaumer
1779 5119c79e René Nussbaumer
    if not rdev:
1780 5119c79e René Nussbaumer
      success.append((False, ("Cannot change sync for device %s:"
1781 5119c79e René Nussbaumer
                              " device not found" % disk.iv_name)))
1782 5119c79e René Nussbaumer
      continue
1783 5119c79e René Nussbaumer
1784 5119c79e René Nussbaumer
    result = rdev.PauseResumeSync(pause)
1785 5119c79e René Nussbaumer
1786 5119c79e René Nussbaumer
    if result:
1787 5119c79e René Nussbaumer
      success.append((result, None))
1788 5119c79e René Nussbaumer
    else:
1789 5119c79e René Nussbaumer
      if pause:
1790 5119c79e René Nussbaumer
        msg = "Pause"
1791 5119c79e René Nussbaumer
      else:
1792 5119c79e René Nussbaumer
        msg = "Resume"
1793 5119c79e René Nussbaumer
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1794 5119c79e René Nussbaumer
1795 5119c79e René Nussbaumer
  return success
1796 5119c79e René Nussbaumer
1797 5119c79e René Nussbaumer
1798 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1799 a8083063 Iustin Pop
  """Remove a block device.
1800 a8083063 Iustin Pop

1801 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1802 10c2650b Iustin Pop

1803 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1804 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1805 10c2650b Iustin Pop
  @rtype: boolean
1806 10c2650b Iustin Pop
  @return: the success of the operation
1807 a8083063 Iustin Pop

1808 a8083063 Iustin Pop
  """
1809 e1bc0878 Iustin Pop
  msgs = []
1810 a8083063 Iustin Pop
  try:
1811 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1812 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1813 a8083063 Iustin Pop
    # probably can't attach
1814 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1815 a8083063 Iustin Pop
    rdev = None
1816 a8083063 Iustin Pop
  if rdev is not None:
1817 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1818 e1bc0878 Iustin Pop
    try:
1819 0c6c04ec Iustin Pop
      rdev.Remove()
1820 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1821 e1bc0878 Iustin Pop
      msgs.append(str(err))
1822 c26a6bd2 Iustin Pop
    if not msgs:
1823 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1824 e1bc0878 Iustin Pop
1825 a8083063 Iustin Pop
  if disk.children:
1826 a8083063 Iustin Pop
    for child in disk.children:
1827 c26a6bd2 Iustin Pop
      try:
1828 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1829 c26a6bd2 Iustin Pop
      except RPCFail, err:
1830 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1831 e1bc0878 Iustin Pop
1832 c26a6bd2 Iustin Pop
  if msgs:
1833 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1834 afdc3985 Iustin Pop
1835 a8083063 Iustin Pop
1836 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1837 a8083063 Iustin Pop
  """Activate a block device for an instance.
1838 a8083063 Iustin Pop

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

1841 10c2650b Iustin Pop
  @note: this function is called recursively.
1842 a8083063 Iustin Pop

1843 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1844 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1845 10c2650b Iustin Pop
  @type owner: str
1846 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1847 10c2650b Iustin Pop
  @type as_primary: boolean
1848 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1849 10c2650b Iustin Pop
      read/write
1850 a8083063 Iustin Pop

1851 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1852 10c2650b Iustin Pop
      was assembled)
1853 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1854 10c2650b Iustin Pop
      during the activation of the children or the device
1855 10c2650b Iustin Pop
      itself
1856 a8083063 Iustin Pop

1857 a8083063 Iustin Pop
  """
1858 a8083063 Iustin Pop
  children = []
1859 a8083063 Iustin Pop
  if disk.children:
1860 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1861 fc1dc9d7 Iustin Pop
    if mcn == -1:
1862 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1863 fc1dc9d7 Iustin Pop
    else:
1864 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1865 a8083063 Iustin Pop
    for chld_disk in disk.children:
1866 fc1dc9d7 Iustin Pop
      try:
1867 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1868 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1869 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1870 fc1dc9d7 Iustin Pop
          raise
1871 fc1dc9d7 Iustin Pop
        cdev = None
1872 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1873 1063abd1 Iustin Pop
                      str(err))
1874 fc1dc9d7 Iustin Pop
      children.append(cdev)
1875 a8083063 Iustin Pop
1876 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1877 94dcbdb0 Andrea Spadaccini
    r_dev = bdev.Assemble(disk, children)
1878 a8083063 Iustin Pop
    result = r_dev
1879 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1880 a8083063 Iustin Pop
      r_dev.Open()
1881 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1882 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1883 3f78eef2 Iustin Pop
1884 a8083063 Iustin Pop
  else:
1885 a8083063 Iustin Pop
    result = True
1886 a8083063 Iustin Pop
  return result
1887 a8083063 Iustin Pop
1888 a8083063 Iustin Pop
1889 c417e115 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary, idx):
1890 a8083063 Iustin Pop
  """Activate a block device for an instance.
1891 a8083063 Iustin Pop

1892 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1893 a8083063 Iustin Pop

1894 b1206984 Iustin Pop
  @rtype: str or boolean
1895 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1896 b1206984 Iustin Pop
      C{True} for secondary nodes
1897 a8083063 Iustin Pop

1898 a8083063 Iustin Pop
  """
1899 53c14ef1 Iustin Pop
  try:
1900 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1901 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1902 b459a848 Andrea Spadaccini
      # pylint: disable=E1103
1903 53c14ef1 Iustin Pop
      result = result.dev_path
1904 c417e115 Iustin Pop
      if as_primary:
1905 c417e115 Iustin Pop
        _SymlinkBlockDev(owner, result, idx)
1906 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1907 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1908 c417e115 Iustin Pop
  except OSError, err:
1909 c417e115 Iustin Pop
    _Fail("Error while symlinking disk: %s", err, exc=True)
1910 afdc3985 Iustin Pop
1911 c26a6bd2 Iustin Pop
  return result
1912 a8083063 Iustin Pop
1913 a8083063 Iustin Pop
1914 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1915 a8083063 Iustin Pop
  """Shut down a block device.
1916 a8083063 Iustin Pop

1917 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1918 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1919 c41eea6e Iustin Pop
  shutdown.
1920 a8083063 Iustin Pop

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

1925 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1926 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1927 10c2650b Iustin Pop
      shutdown
1928 c26a6bd2 Iustin Pop
  @rtype: None
1929 10c2650b Iustin Pop

1930 a8083063 Iustin Pop
  """
1931 cacfd1fd Iustin Pop
  msgs = []
1932 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1933 a8083063 Iustin Pop
  if r_dev is not None:
1934 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1935 cacfd1fd Iustin Pop
    try:
1936 746f7476 Iustin Pop
      r_dev.Shutdown()
1937 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1938 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1939 cacfd1fd Iustin Pop
      msgs.append(str(err))
1940 746f7476 Iustin Pop
1941 a8083063 Iustin Pop
  if disk.children:
1942 a8083063 Iustin Pop
    for child in disk.children:
1943 c26a6bd2 Iustin Pop
      try:
1944 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1945 c26a6bd2 Iustin Pop
      except RPCFail, err:
1946 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1947 746f7476 Iustin Pop
1948 c26a6bd2 Iustin Pop
  if msgs:
1949 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1950 a8083063 Iustin Pop
1951 a8083063 Iustin Pop
1952 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1953 153d9724 Iustin Pop
  """Extend a mirrored block device.
1954 a8083063 Iustin Pop

1955 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1956 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1957 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1958 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1959 c26a6bd2 Iustin Pop
  @rtype: None
1960 10c2650b Iustin Pop

1961 a8083063 Iustin Pop
  """
1962 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1963 153d9724 Iustin Pop
  if parent_bdev is None:
1964 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1965 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1966 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1967 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1968 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1969 a8083063 Iustin Pop
1970 a8083063 Iustin Pop
1971 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1972 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1973 a8083063 Iustin Pop

1974 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1975 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1976 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1977 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1978 c26a6bd2 Iustin Pop
  @rtype: None
1979 10c2650b Iustin Pop

1980 a8083063 Iustin Pop
  """
1981 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1982 153d9724 Iustin Pop
  if parent_bdev is None:
1983 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1984 e739bd57 Iustin Pop
  devs = []
1985 e739bd57 Iustin Pop
  for disk in new_cdevs:
1986 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1987 e739bd57 Iustin Pop
    if rpath is None:
1988 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1989 e739bd57 Iustin Pop
      if bd is None:
1990 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1991 e739bd57 Iustin Pop
      else:
1992 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1993 e739bd57 Iustin Pop
    else:
1994 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1995 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1996 e739bd57 Iustin Pop
      devs.append(rpath)
1997 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1998 a8083063 Iustin Pop
1999 a8083063 Iustin Pop
2000 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
2001 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
2002 a8083063 Iustin Pop

2003 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2004 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
2005 10c2650b Iustin Pop
  @rtype: disk
2006 c6a9dffa Michael Hanselmann
  @return: List of L{objects.BlockDevStatus}, one for each disk
2007 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
2008 10c2650b Iustin Pop
      found
2009 a8083063 Iustin Pop

2010 a8083063 Iustin Pop
  """
2011 a8083063 Iustin Pop
  stats = []
2012 a8083063 Iustin Pop
  for dsk in disks:
2013 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
2014 a8083063 Iustin Pop
    if rbd is None:
2015 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
2016 96acbc09 Michael Hanselmann
2017 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
2018 96acbc09 Michael Hanselmann
2019 c26a6bd2 Iustin Pop
  return stats
2020 a8083063 Iustin Pop
2021 a8083063 Iustin Pop
2022 c6a9dffa Michael Hanselmann
def BlockdevGetmirrorstatusMulti(disks):
2023 c6a9dffa Michael Hanselmann
  """Get the mirroring status of a list of devices.
2024 c6a9dffa Michael Hanselmann

2025 c6a9dffa Michael Hanselmann
  @type disks: list of L{objects.Disk}
2026 c6a9dffa Michael Hanselmann
  @param disks: the list of disks which we should query
2027 c6a9dffa Michael Hanselmann
  @rtype: disk
2028 c6a9dffa Michael Hanselmann
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2029 c6a9dffa Michael Hanselmann
    success/failure, status is L{objects.BlockDevStatus} on success, string
2030 c6a9dffa Michael Hanselmann
    otherwise
2031 c6a9dffa Michael Hanselmann

2032 c6a9dffa Michael Hanselmann
  """
2033 c6a9dffa Michael Hanselmann
  result = []
2034 c6a9dffa Michael Hanselmann
  for disk in disks:
2035 c6a9dffa Michael Hanselmann
    try:
2036 c6a9dffa Michael Hanselmann
      rbd = _RecursiveFindBD(disk)
2037 c6a9dffa Michael Hanselmann
      if rbd is None:
2038 c6a9dffa Michael Hanselmann
        result.append((False, "Can't find device %s" % disk))
2039 c6a9dffa Michael Hanselmann
        continue
2040 c6a9dffa Michael Hanselmann
2041 c6a9dffa Michael Hanselmann
      status = rbd.CombinedSyncStatus()
2042 c6a9dffa Michael Hanselmann
    except errors.BlockDeviceError, err:
2043 c6a9dffa Michael Hanselmann
      logging.exception("Error while getting disk status")
2044 c6a9dffa Michael Hanselmann
      result.append((False, str(err)))
2045 c6a9dffa Michael Hanselmann
    else:
2046 c6a9dffa Michael Hanselmann
      result.append((True, status))
2047 c6a9dffa Michael Hanselmann
2048 c6a9dffa Michael Hanselmann
  assert len(disks) == len(result)
2049 c6a9dffa Michael Hanselmann
2050 c6a9dffa Michael Hanselmann
  return result
2051 c6a9dffa Michael Hanselmann
2052 c6a9dffa Michael Hanselmann
2053 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
2054 a8083063 Iustin Pop
  """Check if a device is activated.
2055 a8083063 Iustin Pop

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

2058 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2059 10c2650b Iustin Pop
  @param disk: the disk object we need to find
2060 a8083063 Iustin Pop

2061 10c2650b Iustin Pop
  @return: None if the device can't be found,
2062 10c2650b Iustin Pop
      otherwise the device instance
2063 a8083063 Iustin Pop

2064 a8083063 Iustin Pop
  """
2065 a8083063 Iustin Pop
  children = []
2066 a8083063 Iustin Pop
  if disk.children:
2067 a8083063 Iustin Pop
    for chdisk in disk.children:
2068 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
2069 a8083063 Iustin Pop
2070 94dcbdb0 Andrea Spadaccini
  return bdev.FindDevice(disk, children)
2071 a8083063 Iustin Pop
2072 a8083063 Iustin Pop
2073 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
2074 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
2075 f2e07bb4 Michael Hanselmann

2076 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
2077 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
2078 f2e07bb4 Michael Hanselmann

2079 f2e07bb4 Michael Hanselmann
  """
2080 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
2081 f2e07bb4 Michael Hanselmann
  if real_disk is None:
2082 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
2083 f2e07bb4 Michael Hanselmann
2084 f2e07bb4 Michael Hanselmann
  real_disk.Open()
2085 f2e07bb4 Michael Hanselmann
2086 f2e07bb4 Michael Hanselmann
  return real_disk
2087 f2e07bb4 Michael Hanselmann
2088 f2e07bb4 Michael Hanselmann
2089 821d1bd1 Iustin Pop
def BlockdevFind(disk):
2090 a8083063 Iustin Pop
  """Check if a device is activated.
2091 a8083063 Iustin Pop

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

2094 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2095 10c2650b Iustin Pop
  @param disk: the disk to find
2096 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
2097 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
2098 96acbc09 Michael Hanselmann
           information
2099 a8083063 Iustin Pop

2100 a8083063 Iustin Pop
  """
2101 23829f6f Iustin Pop
  try:
2102 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
2103 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
2104 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
2105 96acbc09 Michael Hanselmann
2106 a8083063 Iustin Pop
  if rbd is None:
2107 c26a6bd2 Iustin Pop
    return None
2108 96acbc09 Michael Hanselmann
2109 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
2110 a8083063 Iustin Pop
2111 a8083063 Iustin Pop
2112 968a7623 Iustin Pop
def BlockdevGetsize(disks):
2113 968a7623 Iustin Pop
  """Computes the size of the given disks.
2114 968a7623 Iustin Pop

2115 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
2116 968a7623 Iustin Pop

2117 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
2118 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
2119 968a7623 Iustin Pop
  @rtype: list
2120 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
2121 968a7623 Iustin Pop
      otherwise the size
2122 968a7623 Iustin Pop

2123 968a7623 Iustin Pop
  """
2124 968a7623 Iustin Pop
  result = []
2125 968a7623 Iustin Pop
  for cf in disks:
2126 968a7623 Iustin Pop
    try:
2127 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
2128 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
2129 968a7623 Iustin Pop
      result.append(None)
2130 968a7623 Iustin Pop
      continue
2131 968a7623 Iustin Pop
    if rbd is None:
2132 968a7623 Iustin Pop
      result.append(None)
2133 968a7623 Iustin Pop
    else:
2134 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
2135 968a7623 Iustin Pop
  return result
2136 968a7623 Iustin Pop
2137 968a7623 Iustin Pop
2138 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2139 858f3d18 Iustin Pop
  """Export a block device to a remote node.
2140 858f3d18 Iustin Pop

2141 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
2142 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
2143 858f3d18 Iustin Pop
  @type dest_node: str
2144 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
2145 858f3d18 Iustin Pop
  @type dest_path: str
2146 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
2147 858f3d18 Iustin Pop
  @type cluster_name: str
2148 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
2149 858f3d18 Iustin Pop
  @rtype: None
2150 858f3d18 Iustin Pop

2151 858f3d18 Iustin Pop
  """
2152 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
2153 858f3d18 Iustin Pop
2154 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
2155 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2156 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
2157 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
2158 858f3d18 Iustin Pop
2159 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
2160 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
2161 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
2162 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2163 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
2164 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
2165 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2166 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
2167 858f3d18 Iustin Pop
2168 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2169 052783ff Michael Hanselmann
                                                   constants.SSH_LOGIN_USER,
2170 858f3d18 Iustin Pop
                                                   destcmd)
2171 858f3d18 Iustin Pop
2172 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
2173 d0c8c01d Iustin Pop
  command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2174 858f3d18 Iustin Pop
2175 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
2176 858f3d18 Iustin Pop
2177 858f3d18 Iustin Pop
  if result.failed:
2178 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
2179 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
2180 858f3d18 Iustin Pop
2181 858f3d18 Iustin Pop
2182 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2183 a8083063 Iustin Pop
  """Write a file to the filesystem.
2184 a8083063 Iustin Pop

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

2188 10c2650b Iustin Pop
  @type file_name: str
2189 10c2650b Iustin Pop
  @param file_name: the target file name
2190 10c2650b Iustin Pop
  @type data: str
2191 10c2650b Iustin Pop
  @param data: the new contents of the file
2192 10c2650b Iustin Pop
  @type mode: int
2193 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
2194 9a914f7a René Nussbaumer
  @type uid: string
2195 9a914f7a René Nussbaumer
  @param uid: the owner of the file
2196 9a914f7a René Nussbaumer
  @type gid: string
2197 9a914f7a René Nussbaumer
  @param gid: the group of the file
2198 10c2650b Iustin Pop
  @type atime: float
2199 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
2200 10c2650b Iustin Pop
  @type mtime: float
2201 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
2202 c26a6bd2 Iustin Pop
  @rtype: None
2203 10c2650b Iustin Pop

2204 a8083063 Iustin Pop
  """
2205 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
2206 cffbbae7 Michael Hanselmann
2207 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
2208 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2209 a8083063 Iustin Pop
2210 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
2211 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2212 2cc6781a Iustin Pop
          file_name)
2213 a8083063 Iustin Pop
2214 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
2215 12bce260 Michael Hanselmann
2216 9a914f7a René Nussbaumer
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2217 9a914f7a René Nussbaumer
    _Fail("Invalid username/groupname type")
2218 9a914f7a René Nussbaumer
2219 9a914f7a René Nussbaumer
  getents = runtime.GetEnts()
2220 9a914f7a René Nussbaumer
  uid = getents.LookupUser(uid)
2221 9a914f7a René Nussbaumer
  gid = getents.LookupGroup(gid)
2222 9a914f7a René Nussbaumer
2223 8f065ae2 Iustin Pop
  utils.SafeWriteFile(file_name, None,
2224 8f065ae2 Iustin Pop
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2225 8f065ae2 Iustin Pop
                      atime=atime, mtime=mtime)
2226 a8083063 Iustin Pop
2227 386b57af Iustin Pop
2228 b2f29800 René Nussbaumer
def RunOob(oob_program, command, node, timeout):
2229 b2f29800 René Nussbaumer
  """Executes oob_program with given command on given node.
2230 b2f29800 René Nussbaumer

2231 b2f29800 René Nussbaumer
  @param oob_program: The path to the executable oob_program
2232 b2f29800 René Nussbaumer
  @param command: The command to invoke on oob_program
2233 b2f29800 René Nussbaumer
  @param node: The node given as an argument to the program
2234 b2f29800 René Nussbaumer
  @param timeout: Timeout after which we kill the oob program
2235 b2f29800 René Nussbaumer

2236 b2f29800 René Nussbaumer
  @return: stdout
2237 b2f29800 René Nussbaumer
  @raise RPCFail: If execution fails for some reason
2238 b2f29800 René Nussbaumer

2239 b2f29800 René Nussbaumer
  """
2240 b2f29800 René Nussbaumer
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2241 b2f29800 René Nussbaumer
2242 b2f29800 René Nussbaumer
  if result.failed:
2243 b2f29800 René Nussbaumer
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2244 b2f29800 René Nussbaumer
          result.fail_reason, result.output)
2245 b2f29800 René Nussbaumer
2246 b2f29800 René Nussbaumer
  return result.stdout
2247 b2f29800 René Nussbaumer
2248 b2f29800 René Nussbaumer
2249 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
2250 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
2251 a8083063 Iustin Pop

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

2255 10c2650b Iustin Pop
  @type os_dir: str
2256 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
2257 8e70b181 Iustin Pop
  @rtype: tuple
2258 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
2259 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
2260 a8083063 Iustin Pop

2261 a8083063 Iustin Pop
  """
2262 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2263 a8083063 Iustin Pop
2264 a8083063 Iustin Pop
  try:
2265 a8083063 Iustin Pop
    st = os.stat(api_file)
2266 a8083063 Iustin Pop
  except EnvironmentError, err:
2267 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
2268 eb93b673 Guido Trotter
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2269 a8083063 Iustin Pop
2270 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2271 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
2272 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
2273 a8083063 Iustin Pop
2274 a8083063 Iustin Pop
  try:
2275 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
2276 a8083063 Iustin Pop
  except EnvironmentError, err:
2277 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
2278 eb93b673 Guido Trotter
                   (api_file, utils.ErrnoOrStr(err)))
2279 a8083063 Iustin Pop
2280 a8083063 Iustin Pop
  try:
2281 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
2282 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
2283 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
2284 255dcebd Iustin Pop
                   str(err))
2285 a8083063 Iustin Pop
2286 255dcebd Iustin Pop
  return True, api_versions
2287 a8083063 Iustin Pop
2288 386b57af Iustin Pop
2289 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
2290 a8083063 Iustin Pop
  """Compute the validity for all OSes.
2291 a8083063 Iustin Pop

2292 10c2650b Iustin Pop
  @type top_dirs: list
2293 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
2294 10c2650b Iustin Pop
      search (if not given defaults to
2295 3329f4de Michael Hanselmann
      L{pathutils.OS_SEARCH_PATH})
2296 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
2297 bad78e66 Iustin Pop
  @return: a list of tuples (name, path, status, diagnose, variants,
2298 bad78e66 Iustin Pop
      parameters, api_version) for all (potential) OSes under all
2299 bad78e66 Iustin Pop
      search paths, where:
2300 255dcebd Iustin Pop
          - name is the (potential) OS name
2301 255dcebd Iustin Pop
          - path is the full path to the OS
2302 255dcebd Iustin Pop
          - status True/False is the validity of the OS
2303 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
2304 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
2305 c7d04a6b Iustin Pop
          - parameters is a list of (name, help) parameters, if any
2306 bad78e66 Iustin Pop
          - api_version is a list of support OS API versions
2307 a8083063 Iustin Pop

2308 a8083063 Iustin Pop
  """
2309 7c3d51d4 Guido Trotter
  if top_dirs is None:
2310 710f30ec Michael Hanselmann
    top_dirs = pathutils.OS_SEARCH_PATH
2311 a8083063 Iustin Pop
2312 a8083063 Iustin Pop
  result = []
2313 65fe4693 Iustin Pop
  for dir_name in top_dirs:
2314 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
2315 7c3d51d4 Guido Trotter
      try:
2316 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
2317 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
2318 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2319 7c3d51d4 Guido Trotter
        break
2320 7c3d51d4 Guido Trotter
      for name in f_names:
2321 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
2322 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2323 255dcebd Iustin Pop
        if status:
2324 255dcebd Iustin Pop
          diagnose = ""
2325 ba00557a Guido Trotter
          variants = os_inst.supported_variants
2326 c7d04a6b Iustin Pop
          parameters = os_inst.supported_parameters
2327 bad78e66 Iustin Pop
          api_versions = os_inst.api_versions
2328 255dcebd Iustin Pop
        else:
2329 255dcebd Iustin Pop
          diagnose = os_inst
2330 bad78e66 Iustin Pop
          variants = parameters = api_versions = []
2331 bad78e66 Iustin Pop
        result.append((name, os_path, status, diagnose, variants,
2332 bad78e66 Iustin Pop
                       parameters, api_versions))
2333 a8083063 Iustin Pop
2334 c26a6bd2 Iustin Pop
  return result
2335 a8083063 Iustin Pop
2336 a8083063 Iustin Pop
2337 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
2338 a8083063 Iustin Pop
  """Create an OS instance from disk.
2339 a8083063 Iustin Pop

2340 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
2341 8e70b181 Iustin Pop
  valid OS name.
2342 a8083063 Iustin Pop

2343 8ee4dc80 Guido Trotter
  @type base_dir: string
2344 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
2345 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2346 255dcebd Iustin Pop
  @rtype: tuple
2347 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
2348 255dcebd Iustin Pop
      or error message
2349 7c3d51d4 Guido Trotter

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

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

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

2447 255dcebd Iustin Pop
  @type base_dir: string
2448 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
2449 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2450 255dcebd Iustin Pop
  @rtype: L{objects.OS}
2451 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
2452 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
2453 255dcebd Iustin Pop

2454 255dcebd Iustin Pop
  """
2455 870dc44c Iustin Pop
  name_only = objects.OS.GetName(name)
2456 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
2457 255dcebd Iustin Pop
2458 255dcebd Iustin Pop
  if not status:
2459 255dcebd Iustin Pop
    _Fail(payload)
2460 a8083063 Iustin Pop
2461 255dcebd Iustin Pop
  return payload
2462 a8083063 Iustin Pop
2463 a8083063 Iustin Pop
2464 a025e535 Vitaly Kuznetsov
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2465 efaa9b06 Iustin Pop
  """Calculate the basic environment for an os script.
2466 2266edb2 Guido Trotter

2467 a025e535 Vitaly Kuznetsov
  @type os_name: str
2468 a025e535 Vitaly Kuznetsov
  @param os_name: full operating system name (including variant)
2469 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
2470 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
2471 1bdcbbab Iustin Pop
  @type os_params: dict
2472 1bdcbbab Iustin Pop
  @param os_params: the OS parameters
2473 2266edb2 Guido Trotter
  @type debug: integer
2474 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2475 2266edb2 Guido Trotter
  @rtype: dict
2476 2266edb2 Guido Trotter
  @return: dict of environment variables
2477 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2478 10c2650b Iustin Pop
      cannot be found
2479 2266edb2 Guido Trotter

2480 2266edb2 Guido Trotter
  """
2481 2266edb2 Guido Trotter
  result = {}
2482 099c52ad Iustin Pop
  api_version = \
2483 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2484 d0c8c01d Iustin Pop
  result["OS_API_VERSION"] = "%d" % api_version
2485 d0c8c01d Iustin Pop
  result["OS_NAME"] = inst_os.name
2486 d0c8c01d Iustin Pop
  result["DEBUG_LEVEL"] = "%d" % debug
2487 efaa9b06 Iustin Pop
2488 efaa9b06 Iustin Pop
  # OS variants
2489 35007011 Iustin Pop
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2490 870dc44c Iustin Pop
    variant = objects.OS.GetVariant(os_name)
2491 870dc44c Iustin Pop
    if not variant:
2492 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
2493 35007011 Iustin Pop
  else:
2494 35007011 Iustin Pop
    variant = ""
2495 35007011 Iustin Pop
  result["OS_VARIANT"] = variant
2496 efaa9b06 Iustin Pop
2497 1bdcbbab Iustin Pop
  # OS params
2498 1bdcbbab Iustin Pop
  for pname, pvalue in os_params.items():
2499 d0c8c01d Iustin Pop
    result["OSP_%s" % pname.upper()] = pvalue
2500 1bdcbbab Iustin Pop
2501 9a6ade06 Iustin Pop
  # Set a default path otherwise programs called by OS scripts (or
2502 9a6ade06 Iustin Pop
  # even hooks called from OS scripts) might break, and we don't want
2503 9a6ade06 Iustin Pop
  # to have each script require setting a PATH variable
2504 9a6ade06 Iustin Pop
  result["PATH"] = constants.HOOKS_PATH
2505 9a6ade06 Iustin Pop
2506 efaa9b06 Iustin Pop
  return result
2507 efaa9b06 Iustin Pop
2508 efaa9b06 Iustin Pop
2509 efaa9b06 Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
2510 efaa9b06 Iustin Pop
  """Calculate the environment for an os script.
2511 efaa9b06 Iustin Pop

2512 efaa9b06 Iustin Pop
  @type instance: L{objects.Instance}
2513 efaa9b06 Iustin Pop
  @param instance: target instance for the os script run
2514 efaa9b06 Iustin Pop
  @type inst_os: L{objects.OS}
2515 efaa9b06 Iustin Pop
  @param inst_os: operating system for which the environment is being built
2516 efaa9b06 Iustin Pop
  @type debug: integer
2517 efaa9b06 Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
2518 efaa9b06 Iustin Pop
  @rtype: dict
2519 efaa9b06 Iustin Pop
  @return: dict of environment variables
2520 efaa9b06 Iustin Pop
  @raise errors.BlockDeviceError: if the block device
2521 efaa9b06 Iustin Pop
      cannot be found
2522 efaa9b06 Iustin Pop

2523 efaa9b06 Iustin Pop
  """
2524 a025e535 Vitaly Kuznetsov
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2525 efaa9b06 Iustin Pop
2526 519719fd Marco Casavecchia
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2527 f2165b8a Iustin Pop
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2528 f2165b8a Iustin Pop
2529 d0c8c01d Iustin Pop
  result["HYPERVISOR"] = instance.hypervisor
2530 d0c8c01d Iustin Pop
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2531 d0c8c01d Iustin Pop
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2532 d0c8c01d Iustin Pop
  result["INSTANCE_SECONDARY_NODES"] = \
2533 d0c8c01d Iustin Pop
      ("%s" % " ".join(instance.secondary_nodes))
2534 efaa9b06 Iustin Pop
2535 efaa9b06 Iustin Pop
  # Disks
2536 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
2537 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2538 d0c8c01d Iustin Pop
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2539 d0c8c01d Iustin Pop
    result["DISK_%d_ACCESS" % idx] = disk.mode
2540 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
2541 d0c8c01d Iustin Pop
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2542 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
2543 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
2544 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2545 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
2546 d0c8c01d Iustin Pop
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2547 d0c8c01d Iustin Pop
        "file:%s" % disk.physical_id[0]
2548 efaa9b06 Iustin Pop
2549 efaa9b06 Iustin Pop
  # NICs
2550 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
2551 d0c8c01d Iustin Pop
    result["NIC_%d_MAC" % idx] = nic.mac
2552 2266edb2 Guido Trotter
    if nic.ip:
2553 d0c8c01d Iustin Pop
      result["NIC_%d_IP" % idx] = nic.ip
2554 d0c8c01d Iustin Pop
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2555 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2556 d0c8c01d Iustin Pop
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2557 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
2558 d0c8c01d Iustin Pop
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2559 d89168ff Guido Trotter
    if nic.netinfo:
2560 d89168ff Guido Trotter
      nobj = objects.Network.FromDict(nic.netinfo)
2561 d89168ff Guido Trotter
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2562 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
2563 d0c8c01d Iustin Pop
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2564 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
2565 2266edb2 Guido Trotter
2566 efaa9b06 Iustin Pop
  # HV/BE params
2567 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2568 67fc3042 Iustin Pop
    for key, value in source.items():
2569 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2570 67fc3042 Iustin Pop
2571 2266edb2 Guido Trotter
  return result
2572 a8083063 Iustin Pop
2573 f2e07bb4 Michael Hanselmann
2574 b954f097 Constantinos Venetsanopoulos
def DiagnoseExtStorage(top_dirs=None):
2575 b954f097 Constantinos Venetsanopoulos
  """Compute the validity for all ExtStorage Providers.
2576 b954f097 Constantinos Venetsanopoulos

2577 b954f097 Constantinos Venetsanopoulos
  @type top_dirs: list
2578 b954f097 Constantinos Venetsanopoulos
  @param top_dirs: the list of directories in which to
2579 b954f097 Constantinos Venetsanopoulos
      search (if not given defaults to
2580 b954f097 Constantinos Venetsanopoulos
      L{pathutils.ES_SEARCH_PATH})
2581 b954f097 Constantinos Venetsanopoulos
  @rtype: list of L{objects.ExtStorage}
2582 b954f097 Constantinos Venetsanopoulos
  @return: a list of tuples (name, path, status, diagnose, parameters)
2583 b954f097 Constantinos Venetsanopoulos
      for all (potential) ExtStorage Providers under all
2584 b954f097 Constantinos Venetsanopoulos
      search paths, where:
2585 b954f097 Constantinos Venetsanopoulos
          - name is the (potential) ExtStorage Provider
2586 b954f097 Constantinos Venetsanopoulos
          - path is the full path to the ExtStorage Provider
2587 b954f097 Constantinos Venetsanopoulos
          - status True/False is the validity of the ExtStorage Provider
2588 b954f097 Constantinos Venetsanopoulos
          - diagnose is the error message for an invalid ExtStorage Provider,
2589 b954f097 Constantinos Venetsanopoulos
            otherwise empty
2590 b954f097 Constantinos Venetsanopoulos
          - parameters is a list of (name, help) parameters, if any
2591 b954f097 Constantinos Venetsanopoulos

2592 b954f097 Constantinos Venetsanopoulos
  """
2593 b954f097 Constantinos Venetsanopoulos
  if top_dirs is None:
2594 b954f097 Constantinos Venetsanopoulos
    top_dirs = pathutils.ES_SEARCH_PATH
2595 b954f097 Constantinos Venetsanopoulos
2596 b954f097 Constantinos Venetsanopoulos
  result = []
2597 b954f097 Constantinos Venetsanopoulos
  for dir_name in top_dirs:
2598 b954f097 Constantinos Venetsanopoulos
    if os.path.isdir(dir_name):
2599 b954f097 Constantinos Venetsanopoulos
      try:
2600 b954f097 Constantinos Venetsanopoulos
        f_names = utils.ListVisibleFiles(dir_name)
2601 b954f097 Constantinos Venetsanopoulos
      except EnvironmentError, err:
2602 b954f097 Constantinos Venetsanopoulos
        logging.exception("Can't list the ExtStorage directory %s: %s",
2603 b954f097 Constantinos Venetsanopoulos
                          dir_name, err)
2604 b954f097 Constantinos Venetsanopoulos
        break
2605 b954f097 Constantinos Venetsanopoulos
      for name in f_names:
2606 b954f097 Constantinos Venetsanopoulos
        es_path = utils.PathJoin(dir_name, name)
2607 b954f097 Constantinos Venetsanopoulos
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2608 b954f097 Constantinos Venetsanopoulos
        if status:
2609 b954f097 Constantinos Venetsanopoulos
          diagnose = ""
2610 b954f097 Constantinos Venetsanopoulos
          parameters = es_inst.supported_parameters
2611 b954f097 Constantinos Venetsanopoulos
        else:
2612 b954f097 Constantinos Venetsanopoulos
          diagnose = es_inst
2613 b954f097 Constantinos Venetsanopoulos
          parameters = []
2614 b954f097 Constantinos Venetsanopoulos
        result.append((name, es_path, status, diagnose, parameters))
2615 b954f097 Constantinos Venetsanopoulos
2616 b954f097 Constantinos Venetsanopoulos
  return result
2617 b954f097 Constantinos Venetsanopoulos
2618 b954f097 Constantinos Venetsanopoulos
2619 cad0723b Iustin Pop
def BlockdevGrow(disk, amount, dryrun, backingstore):
2620 594609c0 Iustin Pop
  """Grow a stack of block devices.
2621 594609c0 Iustin Pop

2622 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
2623 10c2650b Iustin Pop
  first ones to resize.
2624 594609c0 Iustin Pop

2625 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
2626 10c2650b Iustin Pop
  @param disk: the disk to be grown
2627 a59faf4b Iustin Pop
  @type amount: integer
2628 a59faf4b Iustin Pop
  @param amount: the amount (in mebibytes) to grow with
2629 a59faf4b Iustin Pop
  @type dryrun: boolean
2630 a59faf4b Iustin Pop
  @param dryrun: whether to execute the operation in simulation mode
2631 a59faf4b Iustin Pop
      only, without actually increasing the size
2632 cad0723b Iustin Pop
  @param backingstore: whether to execute the operation on backing storage
2633 cad0723b Iustin Pop
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2634 cad0723b Iustin Pop
      whereas LVM, file, RBD are backing storage
2635 10c2650b Iustin Pop
  @rtype: (status, result)
2636 a59faf4b Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2637 a59faf4b Iustin Pop
      the errors message if status is False
2638 594609c0 Iustin Pop

2639 594609c0 Iustin Pop
  """
2640 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2641 594609c0 Iustin Pop
  if r_dev is None:
2642 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2643 594609c0 Iustin Pop
2644 594609c0 Iustin Pop
  try:
2645 cad0723b Iustin Pop
    r_dev.Grow(amount, dryrun, backingstore)
2646 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
2647 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
2648 594609c0 Iustin Pop
2649 594609c0 Iustin Pop
2650 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2651 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2652 a8083063 Iustin Pop

2653 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2654 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2655 a8083063 Iustin Pop

2656 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2657 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2658 e9e9263d Guido Trotter
  @rtype: string
2659 800ac399 Iustin Pop
  @return: snapshot disk ID as (vg, lv)
2660 a8083063 Iustin Pop

2661 098c0958 Michael Hanselmann
  """
2662 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2663 433c63aa Iustin Pop
    if not disk.children:
2664 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2665 433c63aa Iustin Pop
            disk.unique_id)
2666 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2667 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2668 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2669 a8083063 Iustin Pop
    if r_dev is not None:
2670 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2671 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2672 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2673 a8083063 Iustin Pop
    else:
2674 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2675 a8083063 Iustin Pop
  else:
2676 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2677 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2678 a8083063 Iustin Pop
2679 a8083063 Iustin Pop
2680 48e175a2 Iustin Pop
def BlockdevSetInfo(disk, info):
2681 48e175a2 Iustin Pop
  """Sets 'metadata' information on block devices.
2682 48e175a2 Iustin Pop

2683 48e175a2 Iustin Pop
  This function sets 'info' metadata on block devices. Initial
2684 48e175a2 Iustin Pop
  information is set at device creation; this function should be used
2685 48e175a2 Iustin Pop
  for example after renames.
2686 48e175a2 Iustin Pop

2687 48e175a2 Iustin Pop
  @type disk: L{objects.Disk}
2688 48e175a2 Iustin Pop
  @param disk: the disk to be grown
2689 48e175a2 Iustin Pop
  @type info: string
2690 48e175a2 Iustin Pop
  @param info: new 'info' metadata
2691 48e175a2 Iustin Pop
  @rtype: (status, result)
2692 48e175a2 Iustin Pop
  @return: a tuple with the status of the operation (True/False), and
2693 48e175a2 Iustin Pop
      the errors message if status is False
2694 48e175a2 Iustin Pop

2695 48e175a2 Iustin Pop
  """
2696 48e175a2 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
2697 48e175a2 Iustin Pop
  if r_dev is None:
2698 48e175a2 Iustin Pop
    _Fail("Cannot find block device %s", disk)
2699 48e175a2 Iustin Pop
2700 48e175a2 Iustin Pop
  try:
2701 48e175a2 Iustin Pop
    r_dev.SetInfo(info)
2702 48e175a2 Iustin Pop
  except errors.BlockDeviceError, err:
2703 48e175a2 Iustin Pop
    _Fail("Failed to set information on block device: %s", err, exc=True)
2704 48e175a2 Iustin Pop
2705 48e175a2 Iustin Pop
2706 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2707 a8083063 Iustin Pop
  """Write out the export configuration information.
2708 a8083063 Iustin Pop

2709 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2710 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2711 10c2650b Iustin Pop
      saving configuration
2712 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2713 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2714 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2715 a8083063 Iustin Pop

2716 c26a6bd2 Iustin Pop
  @rtype: None
2717 a8083063 Iustin Pop

2718 098c0958 Michael Hanselmann
  """
2719 710f30ec Michael Hanselmann
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2720 710f30ec Michael Hanselmann
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2721 a8083063 Iustin Pop
2722 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2723 a8083063 Iustin Pop
2724 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2725 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "version", "0")
2726 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2727 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2728 d0c8c01d Iustin Pop
  config.set(constants.INISECT_EXP, "os", instance.os)
2729 775b8743 Michael Hanselmann
  config.set(constants.INISECT_EXP, "compression", "none")
2730 a8083063 Iustin Pop
2731 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2732 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "name", instance.name)
2733 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2734 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2735 1db993d5 Guido Trotter
  config.set(constants.INISECT_INS, "minmem", "%d" %
2736 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MINMEM])
2737 1db993d5 Guido Trotter
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2738 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "memory", "%d" %
2739 1db993d5 Guido Trotter
             instance.beparams[constants.BE_MAXMEM])
2740 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2741 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2742 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2743 d0c8c01d Iustin Pop
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2744 fbb2c636 Michael Hanselmann
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2745 66f93869 Manuel Franceschini
2746 95268cc3 Iustin Pop
  nic_total = 0
2747 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2748 95268cc3 Iustin Pop
    nic_total += 1
2749 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_mac" %
2750 d0c8c01d Iustin Pop
               nic_count, "%s" % nic.mac)
2751 d0c8c01d Iustin Pop
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2752 7a476bb5 Dimitris Aragiorgis
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2753 7a476bb5 Dimitris Aragiorgis
               "%s" % nic.network)
2754 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2755 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2756 d0c8c01d Iustin Pop
                 "%s" % nic.nicparams.get(param, None))
2757 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2758 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2759 a8083063 Iustin Pop
2760 726d7d68 Iustin Pop
  disk_total = 0
2761 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2762 19d7f90a Guido Trotter
    if disk:
2763 726d7d68 Iustin Pop
      disk_total += 1
2764 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2765 d0c8c01d Iustin Pop
                 ("%s" % disk.iv_name))
2766 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2767 d0c8c01d Iustin Pop
                 ("%s" % disk.physical_id[1]))
2768 d0c8c01d Iustin Pop
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2769 d0c8c01d Iustin Pop
                 ("%d" % disk.size))
2770 d0c8c01d Iustin Pop
2771 e687ec01 Michael Hanselmann
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2772 a8083063 Iustin Pop
2773 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2774 3c8954ad Iustin Pop
2775 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2776 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2777 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2778 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2779 3c8954ad Iustin Pop
2780 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2781 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2782 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2783 3c8954ad Iustin Pop
2784 535b49cb Iustin Pop
  config.add_section(constants.INISECT_OSP)
2785 535b49cb Iustin Pop
  for name, value in instance.osparams.items():
2786 535b49cb Iustin Pop
    config.set(constants.INISECT_OSP, name, str(value))
2787 535b49cb Iustin Pop
2788 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2789 726d7d68 Iustin Pop
                  data=config.Dumps())
2790 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2791 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2792 a8083063 Iustin Pop
2793 a8083063 Iustin Pop
2794 a8083063 Iustin Pop
def ExportInfo(dest):
2795 a8083063 Iustin Pop
  """Get export configuration information.
2796 a8083063 Iustin Pop

2797 10c2650b Iustin Pop
  @type dest: str
2798 10c2650b Iustin Pop
  @param dest: directory containing the export
2799 a8083063 Iustin Pop

2800 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2801 10c2650b Iustin Pop
  @return: a serializable config file containing the
2802 10c2650b Iustin Pop
      export info
2803 a8083063 Iustin Pop

2804 a8083063 Iustin Pop
  """
2805 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2806 a8083063 Iustin Pop
2807 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2808 a8083063 Iustin Pop
  config.read(cff)
2809 a8083063 Iustin Pop
2810 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2811 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2812 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2813 a8083063 Iustin Pop
2814 c26a6bd2 Iustin Pop
  return config.Dumps()
2815 a8083063 Iustin Pop
2816 a8083063 Iustin Pop
2817 a8083063 Iustin Pop
def ListExports():
2818 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2819 098c0958 Michael Hanselmann

2820 10c2650b Iustin Pop
  @rtype: list
2821 10c2650b Iustin Pop
  @return: list of the exports
2822 10c2650b Iustin Pop

2823 a8083063 Iustin Pop
  """
2824 710f30ec Michael Hanselmann
  if os.path.isdir(pathutils.EXPORT_DIR):
2825 710f30ec Michael Hanselmann
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2826 a8083063 Iustin Pop
  else:
2827 afdc3985 Iustin Pop
    _Fail("No exports directory")
2828 a8083063 Iustin Pop
2829 a8083063 Iustin Pop
2830 a8083063 Iustin Pop
def RemoveExport(export):
2831 a8083063 Iustin Pop
  """Remove an existing export from the node.
2832 a8083063 Iustin Pop

2833 10c2650b Iustin Pop
  @type export: str
2834 10c2650b Iustin Pop
  @param export: the name of the export to remove
2835 c26a6bd2 Iustin Pop
  @rtype: None
2836 a8083063 Iustin Pop

2837 098c0958 Michael Hanselmann
  """
2838 710f30ec Michael Hanselmann
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2839 a8083063 Iustin Pop
2840 35fbcd11 Iustin Pop
  try:
2841 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2842 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2843 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2844 a8083063 Iustin Pop
2845 a8083063 Iustin Pop
2846 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2847 f3e513ad Iustin Pop
  """Rename a list of block devices.
2848 f3e513ad Iustin Pop

2849 10c2650b Iustin Pop
  @type devlist: list of tuples
2850 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2851 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2852 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2853 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2854 10c2650b Iustin Pop
      rename it to
2855 10c2650b Iustin Pop
  @rtype: boolean
2856 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2857 f3e513ad Iustin Pop

2858 f3e513ad Iustin Pop
  """
2859 6b5e3f70 Iustin Pop
  msgs = []
2860 f3e513ad Iustin Pop
  result = True
2861 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2862 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2863 f3e513ad Iustin Pop
    if dev is None:
2864 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2865 f3e513ad Iustin Pop
      result = False
2866 f3e513ad Iustin Pop
      continue
2867 f3e513ad Iustin Pop
    try:
2868 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2869 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2870 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2871 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2872 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2873 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2874 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2875 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2876 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2877 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2878 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2879 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2880 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2881 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2882 f3e513ad Iustin Pop
      result = False
2883 afdc3985 Iustin Pop
  if not result:
2884 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2885 f3e513ad Iustin Pop
2886 f3e513ad Iustin Pop
2887 4b97f902 Apollon Oikonomopoulos
def _TransformFileStorageDir(fs_dir):
2888 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2889 778b75bb Manuel Franceschini

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

2894 4b97f902 Apollon Oikonomopoulos
  @type fs_dir: str
2895 4b97f902 Apollon Oikonomopoulos
  @param fs_dir: the path to check
2896 d61cbe76 Iustin Pop

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

2899 778b75bb Manuel Franceschini
  """
2900 63a3d8f7 Michael Hanselmann
  if not (constants.ENABLE_FILE_STORAGE or
2901 63a3d8f7 Michael Hanselmann
          constants.ENABLE_SHARED_FILE_STORAGE):
2902 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2903 5e09a309 Michael Hanselmann
2904 5e09a309 Michael Hanselmann
  bdev.CheckFileStoragePath(fs_dir)
2905 5e09a309 Michael Hanselmann
2906 5e09a309 Michael Hanselmann
  return os.path.normpath(fs_dir)
2907 778b75bb Manuel Franceschini
2908 778b75bb Manuel Franceschini
2909 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2910 778b75bb Manuel Franceschini
  """Create file storage directory.
2911 778b75bb Manuel Franceschini

2912 b1206984 Iustin Pop
  @type file_storage_dir: str
2913 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2914 778b75bb Manuel Franceschini

2915 b1206984 Iustin Pop
  @rtype: tuple
2916 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2917 b1206984 Iustin Pop
      creation was successful or not
2918 778b75bb Manuel Franceschini

2919 778b75bb Manuel Franceschini
  """
2920 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2921 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2922 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2923 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2924 b2b8bcce Iustin Pop
            file_storage_dir)
2925 778b75bb Manuel Franceschini
  else:
2926 b2b8bcce Iustin Pop
    try:
2927 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2928 b2b8bcce Iustin Pop
    except OSError, err:
2929 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2930 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2931 778b75bb Manuel Franceschini
2932 778b75bb Manuel Franceschini
2933 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2934 778b75bb Manuel Franceschini
  """Remove file storage directory.
2935 778b75bb Manuel Franceschini

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

2938 10c2650b Iustin Pop
  @type file_storage_dir: str
2939 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2940 10c2650b Iustin Pop
  @rtype: tuple (success,)
2941 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2942 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2943 778b75bb Manuel Franceschini

2944 778b75bb Manuel Franceschini
  """
2945 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2946 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2947 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2948 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2949 b2b8bcce Iustin Pop
            file_storage_dir)
2950 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2951 b2b8bcce Iustin Pop
    try:
2952 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2953 b2b8bcce Iustin Pop
    except OSError, err:
2954 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2955 b2b8bcce Iustin Pop
            file_storage_dir, err)
2956 b2b8bcce Iustin Pop
2957 778b75bb Manuel Franceschini
2958 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2959 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2960 778b75bb Manuel Franceschini

2961 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2962 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2963 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2964 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2965 10c2650b Iustin Pop
  @rtype: tuple (success,)
2966 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2967 10c2650b Iustin Pop
      whether the operation was successful
2968 778b75bb Manuel Franceschini

2969 778b75bb Manuel Franceschini
  """
2970 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2971 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2972 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2973 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2974 b2b8bcce Iustin Pop
      try:
2975 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2976 b2b8bcce Iustin Pop
      except OSError, err:
2977 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2978 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2979 778b75bb Manuel Franceschini
    else:
2980 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2981 b2b8bcce Iustin Pop
            old_file_storage_dir)
2982 b2b8bcce Iustin Pop
  else:
2983 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2984 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2985 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2986 778b75bb Manuel Franceschini
2987 778b75bb Manuel Franceschini
2988 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2989 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2990 ca52cdeb Michael Hanselmann

2991 10c2650b Iustin Pop
  @type file_name: str
2992 10c2650b Iustin Pop
  @param file_name: the file name we should check
2993 c8457ce7 Iustin Pop
  @rtype: None
2994 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2995 10c2650b Iustin Pop

2996 ca52cdeb Michael Hanselmann
  """
2997 b3589802 Michael Hanselmann
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2998 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2999 b3589802 Michael Hanselmann
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3000 dc31eae3 Michael Hanselmann
3001 dc31eae3 Michael Hanselmann
3002 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
3003 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
3004 dc31eae3 Michael Hanselmann

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

3008 10c2650b Iustin Pop
  @type file_name: str
3009 10c2650b Iustin Pop
  @param file_name: the job file name
3010 10c2650b Iustin Pop
  @type content: str
3011 10c2650b Iustin Pop
  @param content: the new job contents
3012 10c2650b Iustin Pop
  @rtype: boolean
3013 10c2650b Iustin Pop
  @return: the success of the operation
3014 10c2650b Iustin Pop

3015 dc31eae3 Michael Hanselmann
  """
3016 cffbbae7 Michael Hanselmann
  file_name = vcluster.LocalizeVirtualPath(file_name)
3017 cffbbae7 Michael Hanselmann
3018 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
3019 82b22e19 René Nussbaumer
  getents = runtime.GetEnts()
3020 ca52cdeb Michael Hanselmann
3021 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
3022 82b22e19 René Nussbaumer
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3023 fe05a931 Michele Tartara
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3024 ca52cdeb Michael Hanselmann
3025 ca52cdeb Michael Hanselmann
3026 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
3027 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
3028 af5ebcb1 Michael Hanselmann

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

3031 10c2650b Iustin Pop
  @type old: str
3032 10c2650b Iustin Pop
  @param old: the old (actual) file name
3033 10c2650b Iustin Pop
  @type new: str
3034 10c2650b Iustin Pop
  @param new: the desired file name
3035 c8457ce7 Iustin Pop
  @rtype: tuple
3036 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
3037 10c2650b Iustin Pop

3038 af5ebcb1 Michael Hanselmann
  """
3039 cffbbae7 Michael Hanselmann
  old = vcluster.LocalizeVirtualPath(old)
3040 cffbbae7 Michael Hanselmann
  new = vcluster.LocalizeVirtualPath(new)
3041 cffbbae7 Michael Hanselmann
3042 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
3043 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
3044 af5ebcb1 Michael Hanselmann
3045 8e5a705d René Nussbaumer
  getents = runtime.GetEnts()
3046 8e5a705d René Nussbaumer
3047 fe05a931 Michele Tartara
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3048 fe05a931 Michele Tartara
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3049 af5ebcb1 Michael Hanselmann
3050 af5ebcb1 Michael Hanselmann
3051 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
3052 d61cbe76 Iustin Pop
  """Closes the given block devices.
3053 d61cbe76 Iustin Pop

3054 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
3055 10c2650b Iustin Pop
  DRBD).
3056 10c2650b Iustin Pop

3057 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
3058 b2e7666a Iustin Pop
      of this instance will be removed
3059 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
3060 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
3061 10c2650b Iustin Pop
  @rtype: tuple (success, message)
3062 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
3063 10c2650b Iustin Pop
      indicates the succes of the operation, and message
3064 10c2650b Iustin Pop
      which will contain the error details in case we
3065 10c2650b Iustin Pop
      failed
3066 d61cbe76 Iustin Pop

3067 d61cbe76 Iustin Pop
  """
3068 d61cbe76 Iustin Pop
  bdevs = []
3069 d61cbe76 Iustin Pop
  for cf in disks:
3070 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
3071 d61cbe76 Iustin Pop
    if rd is None:
3072 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
3073 d61cbe76 Iustin Pop
    bdevs.append(rd)
3074 d61cbe76 Iustin Pop
3075 d61cbe76 Iustin Pop
  msg = []
3076 d61cbe76 Iustin Pop
  for rd in bdevs:
3077 d61cbe76 Iustin Pop
    try:
3078 d61cbe76 Iustin Pop
      rd.Close()
3079 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
3080 d61cbe76 Iustin Pop
      msg.append(str(err))
3081 d61cbe76 Iustin Pop
  if msg:
3082 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3083 d61cbe76 Iustin Pop
  else:
3084 b2e7666a Iustin Pop
    if instance_name:
3085 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
3086 d61cbe76 Iustin Pop
3087 d61cbe76 Iustin Pop
3088 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
3089 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
3090 6217e295 Iustin Pop

3091 6217e295 Iustin Pop
  @type hvname: string
3092 6217e295 Iustin Pop
  @param hvname: the hypervisor name
3093 6217e295 Iustin Pop
  @type hvparams: dict
3094 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
3095 c26a6bd2 Iustin Pop
  @rtype: None
3096 6217e295 Iustin Pop

3097 6217e295 Iustin Pop
  """
3098 6217e295 Iustin Pop
  try:
3099 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
3100 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
3101 6217e295 Iustin Pop
  except errors.HypervisorError, err:
3102 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
3103 6217e295 Iustin Pop
3104 6217e295 Iustin Pop
3105 acd9ff9e Iustin Pop
def _CheckOSPList(os_obj, parameters):
3106 acd9ff9e Iustin Pop
  """Check whether a list of parameters is supported by the OS.
3107 acd9ff9e Iustin Pop

3108 acd9ff9e Iustin Pop
  @type os_obj: L{objects.OS}
3109 acd9ff9e Iustin Pop
  @param os_obj: OS object to check
3110 acd9ff9e Iustin Pop
  @type parameters: list
3111 acd9ff9e Iustin Pop
  @param parameters: the list of parameters to check
3112 acd9ff9e Iustin Pop

3113 acd9ff9e Iustin Pop
  """
3114 acd9ff9e Iustin Pop
  supported = [v[0] for v in os_obj.supported_parameters]
3115 acd9ff9e Iustin Pop
  delta = frozenset(parameters).difference(supported)
3116 acd9ff9e Iustin Pop
  if delta:
3117 acd9ff9e Iustin Pop
    _Fail("The following parameters are not supported"
3118 acd9ff9e Iustin Pop
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3119 acd9ff9e Iustin Pop
3120 acd9ff9e Iustin Pop
3121 acd9ff9e Iustin Pop
def ValidateOS(required, osname, checks, osparams):
3122 acd9ff9e Iustin Pop
  """Validate the given OS' parameters.
3123 acd9ff9e Iustin Pop

3124 acd9ff9e Iustin Pop
  @type required: boolean
3125 acd9ff9e Iustin Pop
  @param required: whether absence of the OS should translate into
3126 acd9ff9e Iustin Pop
      failure or not
3127 acd9ff9e Iustin Pop
  @type osname: string
3128 acd9ff9e Iustin Pop
  @param osname: the OS to be validated
3129 acd9ff9e Iustin Pop
  @type checks: list
3130 acd9ff9e Iustin Pop
  @param checks: list of the checks to run (currently only 'parameters')
3131 acd9ff9e Iustin Pop
  @type osparams: dict
3132 acd9ff9e Iustin Pop
  @param osparams: dictionary with OS parameters
3133 acd9ff9e Iustin Pop
  @rtype: boolean
3134 acd9ff9e Iustin Pop
  @return: True if the validation passed, or False if the OS was not
3135 acd9ff9e Iustin Pop
      found and L{required} was false
3136 acd9ff9e Iustin Pop

3137 acd9ff9e Iustin Pop
  """
3138 acd9ff9e Iustin Pop
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3139 acd9ff9e Iustin Pop
    _Fail("Unknown checks required for OS %s: %s", osname,
3140 acd9ff9e Iustin Pop
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3141 acd9ff9e Iustin Pop
3142 870dc44c Iustin Pop
  name_only = objects.OS.GetName(osname)
3143 acd9ff9e Iustin Pop
  status, tbv = _TryOSFromDisk(name_only, None)
3144 acd9ff9e Iustin Pop
3145 acd9ff9e Iustin Pop
  if not status:
3146 acd9ff9e Iustin Pop
    if required:
3147 acd9ff9e Iustin Pop
      _Fail(tbv)
3148 acd9ff9e Iustin Pop
    else:
3149 acd9ff9e Iustin Pop
      return False
3150 acd9ff9e Iustin Pop
3151 72db3fd7 Iustin Pop
  if max(tbv.api_versions) < constants.OS_API_V20:
3152 72db3fd7 Iustin Pop
    return True
3153 72db3fd7 Iustin Pop
3154 acd9ff9e Iustin Pop
  if constants.OS_VALIDATE_PARAMETERS in checks:
3155 acd9ff9e Iustin Pop
    _CheckOSPList(tbv, osparams.keys())
3156 acd9ff9e Iustin Pop
3157 a025e535 Vitaly Kuznetsov
  validate_env = OSCoreEnv(osname, tbv, osparams)
3158 acd9ff9e Iustin Pop
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3159 896a03f6 Iustin Pop
                        cwd=tbv.path, reset_env=True)
3160 acd9ff9e Iustin Pop
  if result.failed:
3161 acd9ff9e Iustin Pop
    logging.error("os validate command '%s' returned error: %s output: %s",
3162 acd9ff9e Iustin Pop
                  result.cmd, result.fail_reason, result.output)
3163 acd9ff9e Iustin Pop
    _Fail("OS validation script failed (%s), output: %s",
3164 acd9ff9e Iustin Pop
          result.fail_reason, result.output, log=False)
3165 acd9ff9e Iustin Pop
3166 acd9ff9e Iustin Pop
  return True
3167 acd9ff9e Iustin Pop
3168 acd9ff9e Iustin Pop
3169 56aa9fd5 Iustin Pop
def DemoteFromMC():
3170 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
3171 56aa9fd5 Iustin Pop

3172 56aa9fd5 Iustin Pop
  """
3173 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
3174 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
3175 56aa9fd5 Iustin Pop
  if master == myself:
3176 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
3177 f154a7a3 Michael Hanselmann
3178 710f30ec Michael Hanselmann
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3179 f154a7a3 Michael Hanselmann
  if not result.failed:
3180 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
3181 f154a7a3 Michael Hanselmann
3182 56aa9fd5 Iustin Pop
  try:
3183 710f30ec Michael Hanselmann
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3184 710f30ec Michael Hanselmann
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3185 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
3186 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
3187 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3188 f154a7a3 Michael Hanselmann
3189 710f30ec Michael Hanselmann
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3190 56aa9fd5 Iustin Pop
3191 56aa9fd5 Iustin Pop
3192 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
3193 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
3194 f942a838 Michael Hanselmann

3195 f942a838 Michael Hanselmann
  """
3196 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
3197 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3198 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3199 f942a838 Michael Hanselmann
3200 f942a838 Michael Hanselmann
3201 710f30ec Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3202 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
3203 f942a838 Michael Hanselmann

3204 f942a838 Michael Hanselmann
  @type validity: int
3205 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
3206 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
3207 f942a838 Michael Hanselmann
  @return: Certificate name and public part
3208 f942a838 Michael Hanselmann

3209 f942a838 Michael Hanselmann
  """
3210 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
3211 b705c7a6 Manuel Franceschini
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3212 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3213 f942a838 Michael Hanselmann
3214 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3215 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
3216 f942a838 Michael Hanselmann
  try:
3217 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
3218 f942a838 Michael Hanselmann
    assert len(name) > 5
3219 f942a838 Michael Hanselmann
3220 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3221 f942a838 Michael Hanselmann
3222 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3223 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3224 f942a838 Michael Hanselmann
3225 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
3226 f942a838 Michael Hanselmann
    return (name, cert_pem)
3227 f942a838 Michael Hanselmann
  except Exception:
3228 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
3229 f942a838 Michael Hanselmann
    raise
3230 f942a838 Michael Hanselmann
3231 f942a838 Michael Hanselmann
3232 710f30ec Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3233 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
3234 f942a838 Michael Hanselmann

3235 f942a838 Michael Hanselmann
  @type name: string
3236 f942a838 Michael Hanselmann
  @param name: Certificate name
3237 f942a838 Michael Hanselmann

3238 f942a838 Michael Hanselmann
  """
3239 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3240 f942a838 Michael Hanselmann
3241 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
3242 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
3243 f942a838 Michael Hanselmann
3244 f942a838 Michael Hanselmann
  try:
3245 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
3246 f942a838 Michael Hanselmann
  except EnvironmentError, err:
3247 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
3248 f942a838 Michael Hanselmann
          cert_dir, err)
3249 f942a838 Michael Hanselmann
3250 f942a838 Michael Hanselmann
3251 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3252 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
3253 1651d116 Michael Hanselmann

3254 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3255 1651d116 Michael Hanselmann
  @param instance: The instance object
3256 1651d116 Michael Hanselmann
  @param mode: Import/export mode
3257 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3258 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
3259 1651d116 Michael Hanselmann

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

3365 1651d116 Michael Hanselmann
  """
3366 710f30ec Michael Hanselmann
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3367 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
3368 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
3369 1651d116 Michael Hanselmann
3370 1651d116 Michael Hanselmann
3371 6613661a Iustin Pop
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3372 6613661a Iustin Pop
                            ieio, ieioargs):
3373 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
3374 1651d116 Michael Hanselmann

3375 1651d116 Michael Hanselmann
  @param mode: Import/output mode
3376 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
3377 eb630f50 Michael Hanselmann
  @param opts: Daemon options
3378 1651d116 Michael Hanselmann
  @type host: string
3379 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
3380 1651d116 Michael Hanselmann
  @type port: int
3381 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
3382 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
3383 1651d116 Michael Hanselmann
  @param instance: Instance object
3384 6613661a Iustin Pop
  @type component: string
3385 6613661a Iustin Pop
  @param component: which part of the instance is transferred now,
3386 6613661a Iustin Pop
      e.g. 'disk/0'
3387 1651d116 Michael Hanselmann
  @param ieio: Input/output type
3388 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
3389 1651d116 Michael Hanselmann

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

3502 1651d116 Michael Hanselmann
  @type names: sequence
3503 1651d116 Michael Hanselmann
  @param names: List of names
3504 1651d116 Michael Hanselmann
  @rtype: List of dicts
3505 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
3506 1651d116 Michael Hanselmann
           status couldn't be read
3507 1651d116 Michael Hanselmann

3508 1651d116 Michael Hanselmann
  """
3509 1651d116 Michael Hanselmann
  result = []
3510 1651d116 Michael Hanselmann
3511 1651d116 Michael Hanselmann
  for name in names:
3512 710f30ec Michael Hanselmann
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3513 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
3514 1651d116 Michael Hanselmann
3515 1651d116 Michael Hanselmann
    try:
3516 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
3517 1651d116 Michael Hanselmann
    except EnvironmentError, err:
3518 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
3519 1651d116 Michael Hanselmann
        raise
3520 1651d116 Michael Hanselmann
      data = None
3521 1651d116 Michael Hanselmann
3522 1651d116 Michael Hanselmann
    if not data:
3523 1651d116 Michael Hanselmann
      result.append(None)
3524 1651d116 Michael Hanselmann
      continue
3525 1651d116 Michael Hanselmann
3526 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
3527 1651d116 Michael Hanselmann
3528 1651d116 Michael Hanselmann
  return result
3529 1651d116 Michael Hanselmann
3530 1651d116 Michael Hanselmann
3531 f81c4737 Michael Hanselmann
def AbortImportExport(name):
3532 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
3533 f81c4737 Michael Hanselmann

3534 f81c4737 Michael Hanselmann
  """
3535 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
3536 f81c4737 Michael Hanselmann
3537 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3538 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3539 f81c4737 Michael Hanselmann
3540 f81c4737 Michael Hanselmann
  if pid:
3541 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3542 f81c4737 Michael Hanselmann
                 name, pid)
3543 560cbec1 Michael Hanselmann
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3544 f81c4737 Michael Hanselmann
3545 f81c4737 Michael Hanselmann
3546 1651d116 Michael Hanselmann
def CleanupImportExport(name):
3547 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
3548 1651d116 Michael Hanselmann

3549 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
3550 1651d116 Michael Hanselmann
  whole status directory is removed.
3551 1651d116 Michael Hanselmann

3552 1651d116 Michael Hanselmann
  """
3553 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
3554 1651d116 Michael Hanselmann
3555 710f30ec Michael Hanselmann
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3556 1651d116 Michael Hanselmann
3557 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3558 1651d116 Michael Hanselmann
3559 1651d116 Michael Hanselmann
  if pid:
3560 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
3561 1651d116 Michael Hanselmann
                 name, pid)
3562 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
3563 1651d116 Michael Hanselmann
3564 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
3565 1651d116 Michael Hanselmann
3566 1651d116 Michael Hanselmann
3567 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
3568 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
3569 6b93ec9d Iustin Pop

3570 6b93ec9d Iustin Pop
  """
3571 6b93ec9d Iustin Pop
  # set the correct physical ID
3572 b705c7a6 Manuel Franceschini
  my_name = netutils.Hostname.GetSysName()
3573 6b93ec9d Iustin Pop
  for cf in disks:
3574 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
3575 6b93ec9d Iustin Pop
3576 6b93ec9d Iustin Pop
  bdevs = []
3577 6b93ec9d Iustin Pop
3578 6b93ec9d Iustin Pop
  for cf in disks:
3579 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
3580 6b93ec9d Iustin Pop
    if rd is None:
3581 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
3582 6b93ec9d Iustin Pop
    bdevs.append(rd)
3583 5a533f8a Iustin Pop
  return bdevs
3584 6b93ec9d Iustin Pop
3585 6b93ec9d Iustin Pop
3586 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
3587 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
3588 6b93ec9d Iustin Pop

3589 6b93ec9d Iustin Pop
  """
3590 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3591 6b93ec9d Iustin Pop
3592 6b93ec9d Iustin Pop
  # disconnect disks
3593 6b93ec9d Iustin Pop
  for rd in bdevs:
3594 6b93ec9d Iustin Pop
    try:
3595 6b93ec9d Iustin Pop
      rd.DisconnectNet()
3596 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3597 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
3598 2cc6781a Iustin Pop
            err, exc=True)
3599 6b93ec9d Iustin Pop
3600 6b93ec9d Iustin Pop
3601 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3602 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
3603 6b93ec9d Iustin Pop

3604 6b93ec9d Iustin Pop
  """
3605 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3606 6b93ec9d Iustin Pop
3607 6b93ec9d Iustin Pop
  if multimaster:
3608 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
3609 6b93ec9d Iustin Pop
      try:
3610 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3611 6b93ec9d Iustin Pop
      except EnvironmentError, err:
3612 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
3613 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
3614 6b93ec9d Iustin Pop
  # needed primary mode
3615 6b93ec9d Iustin Pop
  for rd in bdevs:
3616 6b93ec9d Iustin Pop
    try:
3617 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
3618 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
3619 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
3620 3c0cdc83 Michael Hanselmann
3621 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
3622 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
3623 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
3624 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
3625 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
3626 3c0cdc83 Michael Hanselmann
3627 3c0cdc83 Michael Hanselmann
  def _Attach():
3628 6b93ec9d Iustin Pop
    all_connected = True
3629 3c0cdc83 Michael Hanselmann
3630 6b93ec9d Iustin Pop
    for rd in bdevs:
3631 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
3632 3c0cdc83 Michael Hanselmann
3633 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
3634 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
3635 3c0cdc83 Michael Hanselmann
3636 6b93ec9d Iustin Pop
      if stats.is_standalone:
3637 6b93ec9d Iustin Pop
        # peer had different config info and this node became
3638 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
3639 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
3640 6b93ec9d Iustin Pop
        try:
3641 c738375b Iustin Pop
          rd.AttachNet(multimaster)
3642 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
3643 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
3644 3c0cdc83 Michael Hanselmann
3645 3c0cdc83 Michael Hanselmann
    if not all_connected:
3646 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
3647 3c0cdc83 Michael Hanselmann
3648 3c0cdc83 Michael Hanselmann
  try:
3649 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3650 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3651 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
3652 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
3653 3c0cdc83 Michael Hanselmann
3654 6b93ec9d Iustin Pop
  if multimaster:
3655 6b93ec9d Iustin Pop
    # change to primary mode
3656 6b93ec9d Iustin Pop
    for rd in bdevs:
3657 d3da87b8 Iustin Pop
      try:
3658 d3da87b8 Iustin Pop
        rd.Open()
3659 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
3660 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
3661 6b93ec9d Iustin Pop
3662 6b93ec9d Iustin Pop
3663 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
3664 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
3665 6b93ec9d Iustin Pop

3666 6b93ec9d Iustin Pop
  """
3667 db8667b7 Iustin Pop
  def _helper(rd):
3668 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
3669 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
3670 db8667b7 Iustin Pop
      raise utils.RetryAgain()
3671 db8667b7 Iustin Pop
    return stats
3672 db8667b7 Iustin Pop
3673 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
3674 6b93ec9d Iustin Pop
3675 6b93ec9d Iustin Pop
  min_resync = 100
3676 6b93ec9d Iustin Pop
  alldone = True
3677 6b93ec9d Iustin Pop
  for rd in bdevs:
3678 db8667b7 Iustin Pop
    try:
3679 db8667b7 Iustin Pop
      # poll each second for 15 seconds
3680 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3681 db8667b7 Iustin Pop
    except utils.RetryTimeout:
3682 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
3683 db8667b7 Iustin Pop
      # last check
3684 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
3685 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3686 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
3687 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
3688 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
3689 afdc3985 Iustin Pop
3690 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
3691 6b93ec9d Iustin Pop
3692 6b93ec9d Iustin Pop
3693 c46b9782 Luca Bigliardi
def GetDrbdUsermodeHelper():
3694 c46b9782 Luca Bigliardi
  """Returns DRBD usermode helper currently configured.
3695 c46b9782 Luca Bigliardi

3696 c46b9782 Luca Bigliardi
  """
3697 c46b9782 Luca Bigliardi
  try:
3698 c46b9782 Luca Bigliardi
    return bdev.BaseDRBD.GetUsermodeHelper()
3699 c46b9782 Luca Bigliardi
  except errors.BlockDeviceError, err:
3700 c46b9782 Luca Bigliardi
    _Fail(str(err))
3701 c46b9782 Luca Bigliardi
3702 c46b9782 Luca Bigliardi
3703 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
3704 f5118ade Iustin Pop
  """Hard-powercycle the node.
3705 f5118ade Iustin Pop

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

3709 f5118ade Iustin Pop
  """
3710 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3711 f5118ade Iustin Pop
  try:
3712 f5118ade Iustin Pop
    pid = os.fork()
3713 29921401 Iustin Pop
  except OSError:
3714 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
3715 f5118ade Iustin Pop
    pid = 0
3716 f5118ade Iustin Pop
  if pid > 0:
3717 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
3718 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
3719 1af6ac0f Luca Bigliardi
  try:
3720 1af6ac0f Luca Bigliardi
    utils.Mlockall()
3721 b459a848 Andrea Spadaccini
  except Exception: # pylint: disable=W0703
3722 1af6ac0f Luca Bigliardi
    pass
3723 f5118ade Iustin Pop
  time.sleep(5)
3724 f5118ade Iustin Pop
  hyper.PowercycleNode()
3725 f5118ade Iustin Pop
3726 f5118ade Iustin Pop
3727 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdName(cmd):
3728 45bc4635 Iustin Pop
  """Verifies a restricted command name.
3729 1a2eb2dc Michael Hanselmann

3730 1a2eb2dc Michael Hanselmann
  @type cmd: string
3731 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3732 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3733 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3734 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3735 1a2eb2dc Michael Hanselmann

3736 1a2eb2dc Michael Hanselmann
  """
3737 1a2eb2dc Michael Hanselmann
  if not cmd.strip():
3738 1a2eb2dc Michael Hanselmann
    return (False, "Missing command name")
3739 1a2eb2dc Michael Hanselmann
3740 1a2eb2dc Michael Hanselmann
  if os.path.basename(cmd) != cmd:
3741 1a2eb2dc Michael Hanselmann
    return (False, "Invalid command name")
3742 1a2eb2dc Michael Hanselmann
3743 1a2eb2dc Michael Hanselmann
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3744 1a2eb2dc Michael Hanselmann
    return (False, "Command name contains forbidden characters")
3745 1a2eb2dc Michael Hanselmann
3746 1a2eb2dc Michael Hanselmann
  return (True, None)
3747 1a2eb2dc Michael Hanselmann
3748 1a2eb2dc Michael Hanselmann
3749 405bffe2 Michael Hanselmann
def _CommonRestrictedCmdCheck(path, owner):
3750 45bc4635 Iustin Pop
  """Common checks for restricted command file system directories and files.
3751 1a2eb2dc Michael Hanselmann

3752 1a2eb2dc Michael Hanselmann
  @type path: string
3753 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3754 1a2eb2dc Michael Hanselmann
  @param owner: C{None} or tuple containing UID and GID
3755 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or C{os.stat} result)
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 the result of C{os.stat}
3758 1a2eb2dc Michael Hanselmann

3759 1a2eb2dc Michael Hanselmann
  """
3760 1a2eb2dc Michael Hanselmann
  if owner is None:
3761 1a2eb2dc Michael Hanselmann
    # Default to root as owner
3762 1a2eb2dc Michael Hanselmann
    owner = (0, 0)
3763 1a2eb2dc Michael Hanselmann
3764 1a2eb2dc Michael Hanselmann
  try:
3765 1a2eb2dc Michael Hanselmann
    st = os.stat(path)
3766 1a2eb2dc Michael Hanselmann
  except EnvironmentError, err:
3767 1a2eb2dc Michael Hanselmann
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3768 1a2eb2dc Michael Hanselmann
3769 1a2eb2dc Michael Hanselmann
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3770 1a2eb2dc Michael Hanselmann
    return (False, "Permissions on '%s' are too permissive" % path)
3771 1a2eb2dc Michael Hanselmann
3772 1a2eb2dc Michael Hanselmann
  if (st.st_uid, st.st_gid) != owner:
3773 1a2eb2dc Michael Hanselmann
    (owner_uid, owner_gid) = owner
3774 1a2eb2dc Michael Hanselmann
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3775 1a2eb2dc Michael Hanselmann
3776 1a2eb2dc Michael Hanselmann
  return (True, st)
3777 1a2eb2dc Michael Hanselmann
3778 1a2eb2dc Michael Hanselmann
3779 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3780 45bc4635 Iustin Pop
  """Verifies restricted command directory.
3781 1a2eb2dc Michael Hanselmann

3782 1a2eb2dc Michael Hanselmann
  @type path: string
3783 1a2eb2dc Michael Hanselmann
  @param path: Path to check
3784 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string or None)
3785 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3786 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise it's C{None}
3787 1a2eb2dc Michael Hanselmann

3788 1a2eb2dc Michael Hanselmann
  """
3789 405bffe2 Michael Hanselmann
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3790 1a2eb2dc Michael Hanselmann
3791 1a2eb2dc Michael Hanselmann
  if not status:
3792 1a2eb2dc Michael Hanselmann
    return (False, value)
3793 1a2eb2dc Michael Hanselmann
3794 1a2eb2dc Michael Hanselmann
  if not stat.S_ISDIR(value.st_mode):
3795 1a2eb2dc Michael Hanselmann
    return (False, "Path '%s' is not a directory" % path)
3796 1a2eb2dc Michael Hanselmann
3797 1a2eb2dc Michael Hanselmann
  return (True, None)
3798 1a2eb2dc Michael Hanselmann
3799 1a2eb2dc Michael Hanselmann
3800 405bffe2 Michael Hanselmann
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3801 45bc4635 Iustin Pop
  """Verifies a whole restricted command and returns its executable filename.
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 1a2eb2dc Michael Hanselmann
  @rtype: tuple; (boolean, string)
3808 1a2eb2dc Michael Hanselmann
  @return: The tuple's first element is the status; if C{False}, the second
3809 1a2eb2dc Michael Hanselmann
    element is an error message string, otherwise the second element is the
3810 1a2eb2dc Michael Hanselmann
    absolute path to the executable
3811 1a2eb2dc Michael Hanselmann

3812 1a2eb2dc Michael Hanselmann
  """
3813 1a2eb2dc Michael Hanselmann
  executable = utils.PathJoin(path, cmd)
3814 1a2eb2dc Michael Hanselmann
3815 405bffe2 Michael Hanselmann
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3816 1a2eb2dc Michael Hanselmann
3817 1a2eb2dc Michael Hanselmann
  if not status:
3818 1a2eb2dc Michael Hanselmann
    return (False, msg)
3819 1a2eb2dc Michael Hanselmann
3820 1a2eb2dc Michael Hanselmann
  if not utils.IsExecutable(executable):
3821 1a2eb2dc Michael Hanselmann
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3822 1a2eb2dc Michael Hanselmann
3823 1a2eb2dc Michael Hanselmann
  return (True, executable)
3824 1a2eb2dc Michael Hanselmann
3825 1a2eb2dc Michael Hanselmann
3826 405bffe2 Michael Hanselmann
def _PrepareRestrictedCmd(path, cmd,
3827 405bffe2 Michael Hanselmann
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3828 405bffe2 Michael Hanselmann
                          _verify_name=_VerifyRestrictedCmdName,
3829 405bffe2 Michael Hanselmann
                          _verify_cmd=_VerifyRestrictedCmd):
3830 45bc4635 Iustin Pop
  """Performs a number of tests on a restricted command.
3831 1a2eb2dc Michael Hanselmann

3832 1a2eb2dc Michael Hanselmann
  @type path: string
3833 45bc4635 Iustin Pop
  @param path: Directory containing restricted commands
3834 1a2eb2dc Michael Hanselmann
  @type cmd: string
3835 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3836 405bffe2 Michael Hanselmann
  @return: Same as L{_VerifyRestrictedCmd}
3837 1a2eb2dc Michael Hanselmann

3838 1a2eb2dc Michael Hanselmann
  """
3839 1a2eb2dc Michael Hanselmann
  # Verify the directory first
3840 1a2eb2dc Michael Hanselmann
  (status, msg) = _verify_dir(path)
3841 1a2eb2dc Michael Hanselmann
  if status:
3842 1a2eb2dc Michael Hanselmann
    # Check command if everything was alright
3843 1a2eb2dc Michael Hanselmann
    (status, msg) = _verify_name(cmd)
3844 1a2eb2dc Michael Hanselmann
3845 1a2eb2dc Michael Hanselmann
  if not status:
3846 1a2eb2dc Michael Hanselmann
    return (False, msg)
3847 1a2eb2dc Michael Hanselmann
3848 1a2eb2dc Michael Hanselmann
  # Check actual executable
3849 1a2eb2dc Michael Hanselmann
  return _verify_cmd(path, cmd)
3850 1a2eb2dc Michael Hanselmann
3851 1a2eb2dc Michael Hanselmann
3852 42bd26e8 Michael Hanselmann
def RunRestrictedCmd(cmd,
3853 1a2eb2dc Michael Hanselmann
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3854 878c42ae Michael Hanselmann
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3855 878c42ae Michael Hanselmann
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3856 1a2eb2dc Michael Hanselmann
                     _sleep_fn=time.sleep,
3857 405bffe2 Michael Hanselmann
                     _prepare_fn=_PrepareRestrictedCmd,
3858 1a2eb2dc Michael Hanselmann
                     _runcmd_fn=utils.RunCmd,
3859 1fdeb284 Michael Hanselmann
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3860 45bc4635 Iustin Pop
  """Executes a restricted command after performing strict tests.
3861 1a2eb2dc Michael Hanselmann

3862 1a2eb2dc Michael Hanselmann
  @type cmd: string
3863 1a2eb2dc Michael Hanselmann
  @param cmd: Command name
3864 1a2eb2dc Michael Hanselmann
  @rtype: string
3865 1a2eb2dc Michael Hanselmann
  @return: Command output
3866 1a2eb2dc Michael Hanselmann
  @raise RPCFail: In case of an error
3867 1a2eb2dc Michael Hanselmann

3868 1a2eb2dc Michael Hanselmann
  """
3869 45bc4635 Iustin Pop
  logging.info("Preparing to run restricted command '%s'", cmd)
3870 1a2eb2dc Michael Hanselmann
3871 1a2eb2dc Michael Hanselmann
  if not _enabled:
3872 45bc4635 Iustin Pop
    _Fail("Restricted commands disabled at configure time")
3873 1a2eb2dc Michael Hanselmann
3874 1a2eb2dc Michael Hanselmann
  lock = None
3875 1a2eb2dc Michael Hanselmann
  try:
3876 1a2eb2dc Michael Hanselmann
    cmdresult = None
3877 1a2eb2dc Michael Hanselmann
    try:
3878 1a2eb2dc Michael Hanselmann
      lock = utils.FileLock.Open(_lock_file)
3879 1a2eb2dc Michael Hanselmann
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3880 1a2eb2dc Michael Hanselmann
3881 1a2eb2dc Michael Hanselmann
      (status, value) = _prepare_fn(_path, cmd)
3882 1a2eb2dc Michael Hanselmann
3883 1a2eb2dc Michael Hanselmann
      if status:
3884 1a2eb2dc Michael Hanselmann
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3885 1a2eb2dc Michael Hanselmann
                               postfork_fn=lambda _: lock.Unlock())
3886 1a2eb2dc Michael Hanselmann
      else:
3887 1a2eb2dc Michael Hanselmann
        logging.error(value)
3888 1a2eb2dc Michael Hanselmann
    except Exception: # pylint: disable=W0703
3889 1a2eb2dc Michael Hanselmann
      # Keep original error in log
3890 1a2eb2dc Michael Hanselmann
      logging.exception("Caught exception")
3891 1a2eb2dc Michael Hanselmann
3892 1a2eb2dc Michael Hanselmann
    if cmdresult is None:
3893 1a2eb2dc Michael Hanselmann
      logging.info("Sleeping for %0.1f seconds before returning",
3894 1a2eb2dc Michael Hanselmann
                   _RCMD_INVALID_DELAY)
3895 1a2eb2dc Michael Hanselmann
      _sleep_fn(_RCMD_INVALID_DELAY)
3896 1a2eb2dc Michael Hanselmann
3897 1a2eb2dc Michael Hanselmann
      # Do not include original error message in returned error
3898 1a2eb2dc Michael Hanselmann
      _Fail("Executing command '%s' failed" % cmd)
3899 1a2eb2dc Michael Hanselmann
    elif cmdresult.failed or cmdresult.fail_reason:
3900 45bc4635 Iustin Pop
      _Fail("Restricted command '%s' failed: %s; output: %s",
3901 1a2eb2dc Michael Hanselmann
            cmd, cmdresult.fail_reason, cmdresult.output)
3902 1a2eb2dc Michael Hanselmann
    else:
3903 1a2eb2dc Michael Hanselmann
      return cmdresult.output
3904 1a2eb2dc Michael Hanselmann
  finally:
3905 1a2eb2dc Michael Hanselmann
    if lock is not None:
3906 1a2eb2dc Michael Hanselmann
      # Release lock at last
3907 1a2eb2dc Michael Hanselmann
      lock.Close()
3908 1a2eb2dc Michael Hanselmann
      lock = None
3909 1a2eb2dc Michael Hanselmann
3910 1a2eb2dc Michael Hanselmann
3911 99e222b1 Michael Hanselmann
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3912 99e222b1 Michael Hanselmann
  """Creates or removes the watcher pause file.
3913 99e222b1 Michael Hanselmann

3914 99e222b1 Michael Hanselmann
  @type until: None or number
3915 99e222b1 Michael Hanselmann
  @param until: Unix timestamp saying until when the watcher shouldn't run
3916 99e222b1 Michael Hanselmann

3917 99e222b1 Michael Hanselmann
  """
3918 99e222b1 Michael Hanselmann
  if until is None:
3919 99e222b1 Michael Hanselmann
    logging.info("Received request to no longer pause watcher")
3920 99e222b1 Michael Hanselmann
    utils.RemoveFile(_filename)
3921 99e222b1 Michael Hanselmann
  else:
3922 99e222b1 Michael Hanselmann
    logging.info("Received request to pause watcher until %s", until)
3923 99e222b1 Michael Hanselmann
3924 99e222b1 Michael Hanselmann
    if not ht.TNumber(until):
3925 99e222b1 Michael Hanselmann
      _Fail("Duration must be numeric")
3926 99e222b1 Michael Hanselmann
3927 99e222b1 Michael Hanselmann
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
3928 99e222b1 Michael Hanselmann
3929 99e222b1 Michael Hanselmann
3930 a8083063 Iustin Pop
class HooksRunner(object):
3931 a8083063 Iustin Pop
  """Hook runner.
3932 a8083063 Iustin Pop

3933 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
3934 10c2650b Iustin Pop
  on the master side.
3935 a8083063 Iustin Pop

3936 a8083063 Iustin Pop
  """
3937 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
3938 a8083063 Iustin Pop
    """Constructor for hooks runner.
3939 a8083063 Iustin Pop

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

3944 a8083063 Iustin Pop
    """
3945 a8083063 Iustin Pop
    if hooks_base_dir is None:
3946 710f30ec Michael Hanselmann
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3947 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3948 fe267188 Iustin Pop
    # constant
3949 b459a848 Andrea Spadaccini
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3950 a8083063 Iustin Pop
3951 0fa481f5 Andrea Spadaccini
  def RunLocalHooks(self, node_list, hpath, phase, env):
3952 0fa481f5 Andrea Spadaccini
    """Check that the hooks will be run only locally and then run them.
3953 0fa481f5 Andrea Spadaccini

3954 0fa481f5 Andrea Spadaccini
    """
3955 0fa481f5 Andrea Spadaccini
    assert len(node_list) == 1
3956 0fa481f5 Andrea Spadaccini
    node = node_list[0]
3957 0fa481f5 Andrea Spadaccini
    _, myself = ssconf.GetMasterAndMyself()
3958 0fa481f5 Andrea Spadaccini
    assert node == myself
3959 0fa481f5 Andrea Spadaccini
3960 0fa481f5 Andrea Spadaccini
    results = self.RunHooks(hpath, phase, env)
3961 0fa481f5 Andrea Spadaccini
3962 0fa481f5 Andrea Spadaccini
    # Return values in the form expected by HooksMaster
3963 0fa481f5 Andrea Spadaccini
    return {node: (None, False, results)}
3964 0fa481f5 Andrea Spadaccini
3965 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
3966 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
3967 a8083063 Iustin Pop

3968 10c2650b Iustin Pop
    @type hpath: str
3969 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
3970 10c2650b Iustin Pop
        holds the scripts
3971 10c2650b Iustin Pop
    @type phase: str
3972 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3973 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
3974 10c2650b Iustin Pop
    @type env: dict
3975 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
3976 10c2650b Iustin Pop
    @rtype: list
3977 10c2650b Iustin Pop
    @return: list of 3-element tuples:
3978 10c2650b Iustin Pop
      - script path
3979 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
3980 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
3981 10c2650b Iustin Pop
      - output of the script
3982 10c2650b Iustin Pop

3983 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
3984 10c2650b Iustin Pop
        parameters
3985 a8083063 Iustin Pop

3986 a8083063 Iustin Pop
    """
3987 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
3988 a8083063 Iustin Pop
      suffix = "pre"
3989 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
3990 a8083063 Iustin Pop
      suffix = "post"
3991 a8083063 Iustin Pop
    else:
3992 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
3993 3fb4f740 Iustin Pop
3994 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
3995 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3996 6bb65e3a Guido Trotter
3997 6bb65e3a Guido Trotter
    results = []
3998 a9b7e346 Iustin Pop
3999 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
4000 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
4001 a9b7e346 Iustin Pop
      # warning at every operation
4002 a9b7e346 Iustin Pop
      return results
4003 a9b7e346 Iustin Pop
4004 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4005 a9b7e346 Iustin Pop
4006 5ae4945a Iustin Pop
    for (relname, relstatus, runresult) in runparts_results:
4007 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
4008 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
4009 a8083063 Iustin Pop
        output = ""
4010 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
4011 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
4012 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
4013 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
4014 6bb65e3a Guido Trotter
        if runresult.failed:
4015 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
4016 a8083063 Iustin Pop
        else:
4017 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
4018 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
4019 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4020 6bb65e3a Guido Trotter
4021 6bb65e3a Guido Trotter
    return results
4022 3f78eef2 Iustin Pop
4023 3f78eef2 Iustin Pop
4024 8d528b7c Iustin Pop
class IAllocatorRunner(object):
4025 8d528b7c Iustin Pop
  """IAllocator runner.
4026 8d528b7c Iustin Pop

4027 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
4028 8d528b7c Iustin Pop
  the master side.
4029 8d528b7c Iustin Pop

4030 8d528b7c Iustin Pop
  """
4031 7e950d31 Iustin Pop
  @staticmethod
4032 7e950d31 Iustin Pop
  def Run(name, idata):
4033 8d528b7c Iustin Pop
    """Run an iallocator script.
4034 8d528b7c Iustin Pop

4035 10c2650b Iustin Pop
    @type name: str
4036 10c2650b Iustin Pop
    @param name: the iallocator script name
4037 10c2650b Iustin Pop
    @type idata: str
4038 10c2650b Iustin Pop
    @param idata: the allocator input data
4039 10c2650b Iustin Pop

4040 10c2650b Iustin Pop
    @rtype: tuple
4041 87f5c298 Iustin Pop
    @return: two element tuple of:
4042 87f5c298 Iustin Pop
       - status
4043 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
4044 8d528b7c Iustin Pop

4045 8d528b7c Iustin Pop
    """
4046 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4047 8d528b7c Iustin Pop
                                  os.path.isfile)
4048 8d528b7c Iustin Pop
    if alloc_script is None:
4049 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
4050 8d528b7c Iustin Pop
4051 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4052 8d528b7c Iustin Pop
    try:
4053 8d528b7c Iustin Pop
      os.write(fd, idata)
4054 8d528b7c Iustin Pop
      os.close(fd)
4055 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
4056 8d528b7c Iustin Pop
      if result.failed:
4057 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4058 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
4059 8d528b7c Iustin Pop
    finally:
4060 8d528b7c Iustin Pop
      os.unlink(fin_name)
4061 8d528b7c Iustin Pop
4062 c26a6bd2 Iustin Pop
    return result.stdout
4063 8d528b7c Iustin Pop
4064 8d528b7c Iustin Pop
4065 3f78eef2 Iustin Pop
class DevCacheManager(object):
4066 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
4067 3f78eef2 Iustin Pop

4068 3f78eef2 Iustin Pop
  """
4069 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
4070 710f30ec Michael Hanselmann
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4071 3f78eef2 Iustin Pop
4072 3f78eef2 Iustin Pop
  @classmethod
4073 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
4074 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
4075 3f78eef2 Iustin Pop

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

4079 10c2650b Iustin Pop
    @type dev_path: str
4080 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
4081 10c2650b Iustin Pop
    @rtype: str
4082 10c2650b Iustin Pop
    @return: the converted path name
4083 3f78eef2 Iustin Pop

4084 3f78eef2 Iustin Pop
    """
4085 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
4086 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4087 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
4088 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4089 3f78eef2 Iustin Pop
    return fpath
4090 3f78eef2 Iustin Pop
4091 3f78eef2 Iustin Pop
  @classmethod
4092 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4093 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
4094 3f78eef2 Iustin Pop

4095 10c2650b Iustin Pop
    @type dev_path: str
4096 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4097 10c2650b Iustin Pop
    @type owner: str
4098 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
4099 10c2650b Iustin Pop
    @type on_primary: bool
4100 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
4101 10c2650b Iustin Pop
        node nor not
4102 10c2650b Iustin Pop
    @type iv_name: str
4103 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
4104 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
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.UpdateCache got a None dev_path")
4111 cf5a8306 Iustin Pop
      return
4112 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4113 3f78eef2 Iustin Pop
    if on_primary:
4114 3f78eef2 Iustin Pop
      state = "primary"
4115 3f78eef2 Iustin Pop
    else:
4116 3f78eef2 Iustin Pop
      state = "secondary"
4117 3f78eef2 Iustin Pop
    if iv_name is None:
4118 3f78eef2 Iustin Pop
      iv_name = "not_visible"
4119 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4120 3f78eef2 Iustin Pop
    try:
4121 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
4122 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4123 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4124 3f78eef2 Iustin Pop
4125 3f78eef2 Iustin Pop
  @classmethod
4126 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
4127 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
4128 3f78eef2 Iustin Pop

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

4132 10c2650b Iustin Pop
    @type dev_path: str
4133 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
4134 10c2650b Iustin Pop

4135 10c2650b Iustin Pop
    @rtype: None
4136 10c2650b Iustin Pop

4137 3f78eef2 Iustin Pop
    """
4138 cf5a8306 Iustin Pop
    if dev_path is None:
4139 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4140 cf5a8306 Iustin Pop
      return
4141 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
4142 3f78eef2 Iustin Pop
    try:
4143 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
4144 3f78eef2 Iustin Pop
    except EnvironmentError, err:
4145 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)