Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 6abf7f2c

History | View | Annotate | Download (94.2 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 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 6c881c52 Iustin Pop
# pylint: disable-msg=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 a8083063 Iustin Pop
62 a8083063 Iustin Pop
63 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
64 714ea7ca Iustin Pop
_ALLOWED_CLEAN_DIRS = frozenset([
65 714ea7ca Iustin Pop
  constants.DATA_DIR,
66 714ea7ca Iustin Pop
  constants.JOB_QUEUE_ARCHIVE_DIR,
67 714ea7ca Iustin Pop
  constants.QUEUE_DIR,
68 f942a838 Michael Hanselmann
  constants.CRYPTO_KEYS_DIR,
69 714ea7ca Iustin Pop
  ])
70 f942a838 Michael Hanselmann
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
71 f942a838 Michael Hanselmann
_X509_KEY_FILE = "key"
72 f942a838 Michael Hanselmann
_X509_CERT_FILE = "cert"
73 1651d116 Michael Hanselmann
_IES_STATUS_FILE = "status"
74 1651d116 Michael Hanselmann
_IES_PID_FILE = "pid"
75 1651d116 Michael Hanselmann
_IES_CA_FILE = "ca"
76 13998ef2 Michael Hanselmann
77 13998ef2 Michael Hanselmann
78 2cc6781a Iustin Pop
class RPCFail(Exception):
79 2cc6781a Iustin Pop
  """Class denoting RPC failure.
80 2cc6781a Iustin Pop

81 2cc6781a Iustin Pop
  Its argument is the error message.
82 2cc6781a Iustin Pop

83 2cc6781a Iustin Pop
  """
84 2cc6781a Iustin Pop
85 13998ef2 Michael Hanselmann
86 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
87 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
88 2cc6781a Iustin Pop

89 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
90 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
91 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
92 2cc6781a Iustin Pop
  daemon.
93 2cc6781a Iustin Pop

94 2cc6781a Iustin Pop
  @type msg: string
95 2cc6781a Iustin Pop
  @param msg: the text of the exception
96 2cc6781a Iustin Pop
  @raise RPCFail
97 2cc6781a Iustin Pop

98 2cc6781a Iustin Pop
  """
99 2cc6781a Iustin Pop
  if args:
100 2cc6781a Iustin Pop
    msg = msg % args
101 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
102 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
103 afdc3985 Iustin Pop
      logging.exception(msg)
104 afdc3985 Iustin Pop
    else:
105 afdc3985 Iustin Pop
      logging.error(msg)
106 2cc6781a Iustin Pop
  raise RPCFail(msg)
107 2cc6781a Iustin Pop
108 2cc6781a Iustin Pop
109 c657dcc9 Michael Hanselmann
def _GetConfig():
110 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
111 10c2650b Iustin Pop

112 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
113 93384844 Iustin Pop
  @return: a SimpleStore instance
114 10c2650b Iustin Pop

115 10c2650b Iustin Pop
  """
116 93384844 Iustin Pop
  return ssconf.SimpleStore()
117 c657dcc9 Michael Hanselmann
118 c657dcc9 Michael Hanselmann
119 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
120 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
121 10c2650b Iustin Pop

122 10c2650b Iustin Pop
  @type cluster_name: str
123 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
124 10c2650b Iustin Pop
      by the SshRunner constructor
125 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
126 10c2650b Iustin Pop
  @return: an SshRunner instance
127 10c2650b Iustin Pop

128 10c2650b Iustin Pop
  """
129 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
130 c92b310a Michael Hanselmann
131 c92b310a Michael Hanselmann
132 12bce260 Michael Hanselmann
def _Decompress(data):
133 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
134 12bce260 Michael Hanselmann

135 12bce260 Michael Hanselmann
  @type data: list or tuple
136 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
137 12bce260 Michael Hanselmann
  @rtype: str
138 12bce260 Michael Hanselmann
  @return: Decompressed data
139 12bce260 Michael Hanselmann

140 12bce260 Michael Hanselmann
  """
141 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
142 12bce260 Michael Hanselmann
  assert len(data) == 2
143 12bce260 Michael Hanselmann
  (encoding, content) = data
144 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
145 12bce260 Michael Hanselmann
    return content
146 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
147 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
148 12bce260 Michael Hanselmann
  else:
149 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
150 12bce260 Michael Hanselmann
151 12bce260 Michael Hanselmann
152 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
153 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
154 76ab5558 Michael Hanselmann

155 10c2650b Iustin Pop
  @type path: str
156 10c2650b Iustin Pop
  @param path: the directory to clean
157 76ab5558 Michael Hanselmann
  @type exclude: list
158 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
159 10c2650b Iustin Pop
      to the empty list
160 76ab5558 Michael Hanselmann

161 76ab5558 Michael Hanselmann
  """
162 714ea7ca Iustin Pop
  if path not in _ALLOWED_CLEAN_DIRS:
163 714ea7ca Iustin Pop
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
164 714ea7ca Iustin Pop
          path)
165 714ea7ca Iustin Pop
166 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
167 3956cee1 Michael Hanselmann
    return
168 3bc6be5c Iustin Pop
  if exclude is None:
169 3bc6be5c Iustin Pop
    exclude = []
170 3bc6be5c Iustin Pop
  else:
171 3bc6be5c Iustin Pop
    # Normalize excluded paths
172 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
173 76ab5558 Michael Hanselmann
174 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
175 c4feafe8 Iustin Pop
    full_name = utils.PathJoin(path, rel_name)
176 76ab5558 Michael Hanselmann
    if full_name in exclude:
177 76ab5558 Michael Hanselmann
      continue
178 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
179 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
180 3956cee1 Michael Hanselmann
181 3956cee1 Michael Hanselmann
182 360b0dc2 Iustin Pop
def _BuildUploadFileList():
183 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
184 360b0dc2 Iustin Pop

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

187 360b0dc2 Iustin Pop
  """
188 b397a7d2 Iustin Pop
  allowed_files = set([
189 b397a7d2 Iustin Pop
    constants.CLUSTER_CONF_FILE,
190 b397a7d2 Iustin Pop
    constants.ETC_HOSTS,
191 b397a7d2 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
192 b397a7d2 Iustin Pop
    constants.VNC_PASSWORD_FILE,
193 b397a7d2 Iustin Pop
    constants.RAPI_CERT_FILE,
194 b397a7d2 Iustin Pop
    constants.RAPI_USERS_FILE,
195 6b7d5878 Michael Hanselmann
    constants.CONFD_HMAC_KEY,
196 ff89a747 Michael Hanselmann
    constants.CLUSTER_DOMAIN_SECRET_FILE,
197 b397a7d2 Iustin Pop
    ])
198 b397a7d2 Iustin Pop
199 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
200 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
201 b397a7d2 Iustin Pop
    allowed_files.update(hv_class.GetAncillaryFiles())
202 b397a7d2 Iustin Pop
203 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
204 360b0dc2 Iustin Pop
205 360b0dc2 Iustin Pop
206 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
207 360b0dc2 Iustin Pop
208 360b0dc2 Iustin Pop
209 1bc59f76 Michael Hanselmann
def JobQueuePurge():
210 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
211 10c2650b Iustin Pop

212 c8457ce7 Iustin Pop
  @rtype: tuple
213 c8457ce7 Iustin Pop
  @return: True, None
214 24fc781f Michael Hanselmann

215 24fc781f Michael Hanselmann
  """
216 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
217 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
218 24fc781f Michael Hanselmann
219 24fc781f Michael Hanselmann
220 bd1e4562 Iustin Pop
def GetMasterInfo():
221 bd1e4562 Iustin Pop
  """Returns master information.
222 bd1e4562 Iustin Pop

223 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
224 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
225 bd1e4562 Iustin Pop

226 bd1e4562 Iustin Pop
  @rtype: tuple
227 c26a6bd2 Iustin Pop
  @return: master_netdev, master_ip, master_name
228 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
229 b1b6ea87 Iustin Pop

230 b1b6ea87 Iustin Pop
  """
231 b1b6ea87 Iustin Pop
  try:
232 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
233 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
234 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
235 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
236 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
237 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
238 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
239 b1b6ea87 Iustin Pop
240 b1b6ea87 Iustin Pop
241 3583908a Guido Trotter
def StartMaster(start_daemons, no_voting):
242 a8083063 Iustin Pop
  """Activate local node as master node.
243 a8083063 Iustin Pop

244 1c65840b Iustin Pop
  The function will always try activate the IP address of the master
245 10c2650b Iustin Pop
  (unless someone else has it). It will also start the master daemons,
246 10c2650b Iustin Pop
  based on the start_daemons parameter.
247 10c2650b Iustin Pop

248 10c2650b Iustin Pop
  @type start_daemons: boolean
249 c26a6bd2 Iustin Pop
  @param start_daemons: whether to also start the master
250 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
251 3583908a Guido Trotter
  @type no_voting: boolean
252 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
253 3583908a Guido Trotter
      (if start_daemons is True), but still non-interactively
254 10c2650b Iustin Pop
  @rtype: None
255 a8083063 Iustin Pop

256 a8083063 Iustin Pop
  """
257 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
258 541741d3 Guido Trotter
  master_netdev, master_ip, _ = GetMasterInfo()
259 a8083063 Iustin Pop
260 396b5733 Iustin Pop
  err_msgs = []
261 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
262 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
263 b1b6ea87 Iustin Pop
      # we already have the ip:
264 b726aff0 Iustin Pop
      logging.debug("Master IP already configured, doing nothing")
265 b1b6ea87 Iustin Pop
    else:
266 b726aff0 Iustin Pop
      msg = "Someone else has the master ip, not activating"
267 b726aff0 Iustin Pop
      logging.error(msg)
268 396b5733 Iustin Pop
      err_msgs.append(msg)
269 b1b6ea87 Iustin Pop
  else:
270 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
271 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
272 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
273 b1b6ea87 Iustin Pop
    if result.failed:
274 b726aff0 Iustin Pop
      msg = "Can't activate master IP: %s" % result.output
275 b726aff0 Iustin Pop
      logging.error(msg)
276 396b5733 Iustin Pop
      err_msgs.append(msg)
277 b1b6ea87 Iustin Pop
278 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
279 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
280 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
281 b1b6ea87 Iustin Pop
282 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
283 b1b6ea87 Iustin Pop
  if start_daemons:
284 3583908a Guido Trotter
    if no_voting:
285 f154a7a3 Michael Hanselmann
      masterd_args = "--no-voting --yes-do-it"
286 f154a7a3 Michael Hanselmann
    else:
287 f154a7a3 Michael Hanselmann
      masterd_args = ""
288 f154a7a3 Michael Hanselmann
289 f154a7a3 Michael Hanselmann
    env = {
290 f154a7a3 Michael Hanselmann
      "EXTRA_MASTERD_ARGS": masterd_args,
291 f154a7a3 Michael Hanselmann
      }
292 f154a7a3 Michael Hanselmann
293 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
294 f154a7a3 Michael Hanselmann
    if result.failed:
295 f154a7a3 Michael Hanselmann
      msg = "Can't start Ganeti master: %s" % result.output
296 f154a7a3 Michael Hanselmann
      logging.error(msg)
297 f154a7a3 Michael Hanselmann
      err_msgs.append(msg)
298 b726aff0 Iustin Pop
299 396b5733 Iustin Pop
  if err_msgs:
300 396b5733 Iustin Pop
    _Fail("; ".join(err_msgs))
301 afdc3985 Iustin Pop
302 a8083063 Iustin Pop
303 1c65840b Iustin Pop
def StopMaster(stop_daemons):
304 a8083063 Iustin Pop
  """Deactivate this node as master.
305 a8083063 Iustin Pop

306 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
307 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
308 10c2650b Iustin Pop
  stop_daemons parameter.
309 10c2650b Iustin Pop

310 10c2650b Iustin Pop
  @type stop_daemons: boolean
311 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
312 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
313 10c2650b Iustin Pop
  @rtype: None
314 a8083063 Iustin Pop

315 a8083063 Iustin Pop
  """
316 6c00d19a Iustin Pop
  # TODO: log and report back to the caller the error failures; we
317 6c00d19a Iustin Pop
  # need to decide in which case we fail the RPC for this
318 2a52a064 Iustin Pop
319 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
320 541741d3 Guido Trotter
  master_netdev, master_ip, _ = GetMasterInfo()
321 a8083063 Iustin Pop
322 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
323 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
324 a8083063 Iustin Pop
  if result.failed:
325 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
326 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
327 b1b6ea87 Iustin Pop
328 b1b6ea87 Iustin Pop
  if stop_daemons:
329 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
330 f154a7a3 Michael Hanselmann
    if result.failed:
331 f154a7a3 Michael Hanselmann
      logging.error("Could not stop Ganeti master, command %s had exitcode %s"
332 f154a7a3 Michael Hanselmann
                    " and error %s",
333 f154a7a3 Michael Hanselmann
                    result.cmd, result.exit_code, result.output)
334 a8083063 Iustin Pop
335 a8083063 Iustin Pop
336 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
337 7900ed01 Iustin Pop
  """Joins this node to the cluster.
338 a8083063 Iustin Pop

339 7900ed01 Iustin Pop
  This does the following:
340 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
341 7900ed01 Iustin Pop
      - adds the ssh private key to the user
342 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
343 a8083063 Iustin Pop

344 10c2650b Iustin Pop
  @type dsa: str
345 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
346 10c2650b Iustin Pop
  @type dsapub: str
347 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
348 10c2650b Iustin Pop
  @type rsa: str
349 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
350 10c2650b Iustin Pop
  @type rsapub: str
351 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
352 10c2650b Iustin Pop
  @type sshkey: str
353 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
354 10c2650b Iustin Pop
  @type sshpub: str
355 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
356 10c2650b Iustin Pop
  @rtype: boolean
357 10c2650b Iustin Pop
  @return: the success of the operation
358 10c2650b Iustin Pop

359 7900ed01 Iustin Pop
  """
360 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
361 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
362 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
363 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
364 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
365 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
366 a8083063 Iustin Pop
367 70d9e3d8 Iustin Pop
  try:
368 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
369 70d9e3d8 Iustin Pop
                                                    mkdir=True)
370 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
371 2cc6781a Iustin Pop
    _Fail("Error while processing user ssh files: %s", err, exc=True)
372 a8083063 Iustin Pop
373 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
374 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
375 a8083063 Iustin Pop
376 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
377 a8083063 Iustin Pop
378 7e1fac25 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "reload-ssh-keys"])
379 7e1fac25 Michael Hanselmann
  if result.failed:
380 7e1fac25 Michael Hanselmann
    _Fail("Unable to reload SSH keys (command %r, exit code %s, output %r)",
381 7e1fac25 Michael Hanselmann
          result.cmd, result.exit_code, result.output)
382 a8083063 Iustin Pop
383 a8083063 Iustin Pop
384 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
385 10c2650b Iustin Pop
  """Cleans up and remove the current node.
386 10c2650b Iustin Pop

387 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
388 10c2650b Iustin Pop
  from the cluster.
389 10c2650b Iustin Pop

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

394 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
395 b989b9d9 Ken Wehr

396 a8083063 Iustin Pop
  """
397 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
398 f942a838 Michael Hanselmann
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
399 1bc59f76 Michael Hanselmann
  JobQueuePurge()
400 f78346f5 Michael Hanselmann
401 b989b9d9 Ken Wehr
  if modify_ssh_setup:
402 b989b9d9 Ken Wehr
    try:
403 b989b9d9 Ken Wehr
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
404 7900ed01 Iustin Pop
405 b989b9d9 Ken Wehr
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
406 a8083063 Iustin Pop
407 b989b9d9 Ken Wehr
      utils.RemoveFile(priv_key)
408 b989b9d9 Ken Wehr
      utils.RemoveFile(pub_key)
409 b989b9d9 Ken Wehr
    except errors.OpExecError:
410 b989b9d9 Ken Wehr
      logging.exception("Error while processing ssh files")
411 a8083063 Iustin Pop
412 ed008420 Guido Trotter
  try:
413 6b7d5878 Michael Hanselmann
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
414 ed008420 Guido Trotter
    utils.RemoveFile(constants.RAPI_CERT_FILE)
415 168c1de2 Michael Hanselmann
    utils.RemoveFile(constants.NODED_CERT_FILE)
416 7260cfbe Iustin Pop
  except: # pylint: disable-msg=W0702
417 ed008420 Guido Trotter
    logging.exception("Error while removing cluster secrets")
418 ed008420 Guido Trotter
419 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
420 f154a7a3 Michael Hanselmann
  if result.failed:
421 f154a7a3 Michael Hanselmann
    logging.error("Command %s failed with exitcode %s and error %s",
422 f154a7a3 Michael Hanselmann
                  result.cmd, result.exit_code, result.output)
423 ed008420 Guido Trotter
424 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
425 0623d351 Iustin Pop
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
426 6d8b6238 Guido Trotter
427 a8083063 Iustin Pop
428 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
429 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
430 a8083063 Iustin Pop

431 e69d05fd Iustin Pop
  @type vgname: C{string}
432 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
433 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
434 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
435 e69d05fd Iustin Pop
      memory information
436 e69d05fd Iustin Pop
  @rtype: C{dict}
437 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
438 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
439 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
440 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
441 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
442 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
443 a8083063 Iustin Pop

444 098c0958 Michael Hanselmann
  """
445 a8083063 Iustin Pop
  outputarray = {}
446 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
447 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
448 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
449 a8083063 Iustin Pop
450 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
451 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
452 a8083063 Iustin Pop
  if hyp_info is not None:
453 a8083063 Iustin Pop
    outputarray.update(hyp_info)
454 a8083063 Iustin Pop
455 13998ef2 Michael Hanselmann
  outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
456 3ef10550 Michael Hanselmann
457 c26a6bd2 Iustin Pop
  return outputarray
458 a8083063 Iustin Pop
459 a8083063 Iustin Pop
460 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
461 a8083063 Iustin Pop
  """Verify the status of the local node.
462 a8083063 Iustin Pop

463 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
464 e69d05fd Iustin Pop
  local node.
465 e69d05fd Iustin Pop

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

469 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
470 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
471 e69d05fd Iustin Pop
  report).
472 a8083063 Iustin Pop

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

477 e69d05fd Iustin Pop
  @type what: C{dict}
478 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
479 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
480 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
481 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
482 e69d05fd Iustin Pop
        connectivity with
483 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
484 10c2650b Iustin Pop
  @rtype: dict
485 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
486 10c2650b Iustin Pop
      values representing the result of the checks
487 a8083063 Iustin Pop

488 a8083063 Iustin Pop
  """
489 a8083063 Iustin Pop
  result = {}
490 a3a5f850 Iustin Pop
  my_name = utils.HostInfo().name
491 a3a5f850 Iustin Pop
  port = utils.GetDaemonPort(constants.NODED)
492 a8083063 Iustin Pop
493 25361b9a Iustin Pop
  if constants.NV_HYPERVISOR in what:
494 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
495 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
496 0cf5e7f5 Iustin Pop
      try:
497 0cf5e7f5 Iustin Pop
        val = hypervisor.GetHypervisor(hv_name).Verify()
498 0cf5e7f5 Iustin Pop
      except errors.HypervisorError, err:
499 0cf5e7f5 Iustin Pop
        val = "Error while checking hypervisor: %s" % str(err)
500 0cf5e7f5 Iustin Pop
      tmp[hv_name] = val
501 25361b9a Iustin Pop
502 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
503 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
504 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
505 25361b9a Iustin Pop
506 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
507 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
508 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
509 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
510 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
511 a8083063 Iustin Pop
      if not success:
512 25361b9a Iustin Pop
        tmp[node] = message
513 25361b9a Iustin Pop
514 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
515 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
516 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
517 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
518 9d4bfc96 Iustin Pop
      if name == my_name:
519 9d4bfc96 Iustin Pop
        my_pip = pip
520 9d4bfc96 Iustin Pop
        my_sip = sip
521 9d4bfc96 Iustin Pop
        break
522 9d4bfc96 Iustin Pop
    if not my_pip:
523 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
524 25361b9a Iustin Pop
                      " in the node list")
525 9d4bfc96 Iustin Pop
    else:
526 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
527 9d4bfc96 Iustin Pop
        fail = []
528 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
529 9d4bfc96 Iustin Pop
          fail.append("primary")
530 9d4bfc96 Iustin Pop
        if sip != pip:
531 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
532 9d4bfc96 Iustin Pop
            fail.append("secondary")
533 9d4bfc96 Iustin Pop
        if fail:
534 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
535 25361b9a Iustin Pop
                       " and ".join(fail))
536 25361b9a Iustin Pop
537 a3a5f850 Iustin Pop
  if constants.NV_MASTERIP in what:
538 a3a5f850 Iustin Pop
    # FIXME: add checks on incoming data structures (here and in the
539 a3a5f850 Iustin Pop
    # rest of the function)
540 a3a5f850 Iustin Pop
    master_name, master_ip = what[constants.NV_MASTERIP]
541 a3a5f850 Iustin Pop
    if master_name == my_name:
542 a3a5f850 Iustin Pop
      source = constants.LOCALHOST_IP_ADDRESS
543 a3a5f850 Iustin Pop
    else:
544 a3a5f850 Iustin Pop
      source = None
545 a3a5f850 Iustin Pop
    result[constants.NV_MASTERIP] = utils.TcpPing(master_ip, port,
546 a3a5f850 Iustin Pop
                                                  source=source)
547 a3a5f850 Iustin Pop
548 25361b9a Iustin Pop
  if constants.NV_LVLIST in what:
549 ed904904 Iustin Pop
    try:
550 ed904904 Iustin Pop
      val = GetVolumeList(what[constants.NV_LVLIST])
551 ed904904 Iustin Pop
    except RPCFail, err:
552 ed904904 Iustin Pop
      val = str(err)
553 ed904904 Iustin Pop
    result[constants.NV_LVLIST] = val
554 25361b9a Iustin Pop
555 25361b9a Iustin Pop
  if constants.NV_INSTANCELIST in what:
556 0cf5e7f5 Iustin Pop
    # GetInstanceList can fail
557 0cf5e7f5 Iustin Pop
    try:
558 0cf5e7f5 Iustin Pop
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
559 0cf5e7f5 Iustin Pop
    except RPCFail, err:
560 0cf5e7f5 Iustin Pop
      val = str(err)
561 0cf5e7f5 Iustin Pop
    result[constants.NV_INSTANCELIST] = val
562 25361b9a Iustin Pop
563 25361b9a Iustin Pop
  if constants.NV_VGLIST in what:
564 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
565 25361b9a Iustin Pop
566 d091393e Iustin Pop
  if constants.NV_PVLIST in what:
567 d091393e Iustin Pop
    result[constants.NV_PVLIST] = \
568 d091393e Iustin Pop
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
569 d091393e Iustin Pop
                                   filter_allocatable=False)
570 d091393e Iustin Pop
571 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
572 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
573 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
574 25361b9a Iustin Pop
575 25361b9a Iustin Pop
  if constants.NV_HVINFO in what:
576 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
577 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
578 9d4bfc96 Iustin Pop
579 6d2e83d5 Iustin Pop
  if constants.NV_DRBDLIST in what:
580 6d2e83d5 Iustin Pop
    try:
581 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
582 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
583 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
584 f6eaed12 Iustin Pop
      used_minors = str(err)
585 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
586 6d2e83d5 Iustin Pop
587 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
588 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
589 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
590 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
591 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
592 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
593 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
594 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
595 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
596 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
597 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
598 313b2dd4 Michael Hanselmann
599 313b2dd4 Michael Hanselmann
  if constants.NV_TIME in what:
600 313b2dd4 Michael Hanselmann
    result[constants.NV_TIME] = utils.SplitTime(time.time())
601 313b2dd4 Michael Hanselmann
602 c26a6bd2 Iustin Pop
  return result
603 a8083063 Iustin Pop
604 a8083063 Iustin Pop
605 a8083063 Iustin Pop
def GetVolumeList(vg_name):
606 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
607 a8083063 Iustin Pop

608 10c2650b Iustin Pop
  @type vg_name: str
609 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
610 10c2650b Iustin Pop
  @rtype: dict
611 10c2650b Iustin Pop
  @return:
612 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
613 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
614 10c2650b Iustin Pop

615 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
616 10c2650b Iustin Pop

617 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
618 10c2650b Iustin Pop
      details.
619 a8083063 Iustin Pop

620 a8083063 Iustin Pop
  """
621 cb2037a2 Iustin Pop
  lvs = {}
622 cb2037a2 Iustin Pop
  sep = '|'
623 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
624 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
625 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
626 a8083063 Iustin Pop
  if result.failed:
627 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
628 cb2037a2 Iustin Pop
629 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
630 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
631 df4c2628 Iustin Pop
    line = line.strip()
632 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
633 df4c2628 Iustin Pop
    if not match:
634 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
635 df4c2628 Iustin Pop
      continue
636 df4c2628 Iustin Pop
    name, size, attr = match.groups()
637 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
638 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
639 33f2a81a Iustin Pop
    virtual = attr[0] == 'v'
640 33f2a81a Iustin Pop
    if virtual:
641 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
642 33f2a81a Iustin Pop
      # don't really hold data
643 33f2a81a Iustin Pop
      continue
644 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
645 cb2037a2 Iustin Pop
646 cb2037a2 Iustin Pop
  return lvs
647 a8083063 Iustin Pop
648 a8083063 Iustin Pop
649 a8083063 Iustin Pop
def ListVolumeGroups():
650 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
651 a8083063 Iustin Pop

652 10c2650b Iustin Pop
  @rtype: dict
653 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
654 10c2650b Iustin Pop
      size of the volume
655 a8083063 Iustin Pop

656 a8083063 Iustin Pop
  """
657 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
658 a8083063 Iustin Pop
659 a8083063 Iustin Pop
660 dcb93971 Michael Hanselmann
def NodeVolumes():
661 dcb93971 Michael Hanselmann
  """List all volumes on this node.
662 dcb93971 Michael Hanselmann

663 10c2650b Iustin Pop
  @rtype: list
664 10c2650b Iustin Pop
  @return:
665 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
666 10c2650b Iustin Pop
      - name: the logical volume name,
667 10c2650b Iustin Pop
      - size: the size of the logical volume
668 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
669 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
670 10c2650b Iustin Pop

671 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
672 10c2650b Iustin Pop
    error.
673 10c2650b Iustin Pop

674 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
675 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
676 10c2650b Iustin Pop
    multiple times.
677 10c2650b Iustin Pop

678 dcb93971 Michael Hanselmann
  """
679 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
680 dcb93971 Michael Hanselmann
                         "--separator=|",
681 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
682 dcb93971 Michael Hanselmann
  if result.failed:
683 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
684 10bfe6cb Iustin Pop
          result.output)
685 dcb93971 Michael Hanselmann
686 dcb93971 Michael Hanselmann
  def parse_dev(dev):
687 89e5ab02 Iustin Pop
    return dev.split('(')[0]
688 89e5ab02 Iustin Pop
689 89e5ab02 Iustin Pop
  def handle_dev(dev):
690 89e5ab02 Iustin Pop
    return [parse_dev(x) for x in dev.split(",")]
691 dcb93971 Michael Hanselmann
692 dcb93971 Michael Hanselmann
  def map_line(line):
693 89e5ab02 Iustin Pop
    line = [v.strip() for v in line]
694 89e5ab02 Iustin Pop
    return [{'name': line[0], 'size': line[1],
695 89e5ab02 Iustin Pop
             'dev': dev, 'vg': line[3]} for dev in handle_dev(line[2])]
696 89e5ab02 Iustin Pop
697 89e5ab02 Iustin Pop
  all_devs = []
698 89e5ab02 Iustin Pop
  for line in result.stdout.splitlines():
699 89e5ab02 Iustin Pop
    if line.count('|') >= 3:
700 89e5ab02 Iustin Pop
      all_devs.extend(map_line(line.split('|')))
701 89e5ab02 Iustin Pop
    else:
702 89e5ab02 Iustin Pop
      logging.warning("Strange line in the output from lvs: '%s'", line)
703 89e5ab02 Iustin Pop
  return all_devs
704 dcb93971 Michael Hanselmann
705 dcb93971 Michael Hanselmann
706 a8083063 Iustin Pop
def BridgesExist(bridges_list):
707 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
708 a8083063 Iustin Pop

709 b1206984 Iustin Pop
  @rtype: boolean
710 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
711 a8083063 Iustin Pop

712 a8083063 Iustin Pop
  """
713 35c0c8da Iustin Pop
  missing = []
714 a8083063 Iustin Pop
  for bridge in bridges_list:
715 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
716 35c0c8da Iustin Pop
      missing.append(bridge)
717 a8083063 Iustin Pop
718 35c0c8da Iustin Pop
  if missing:
719 1f864b60 Iustin Pop
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
720 35c0c8da Iustin Pop
721 a8083063 Iustin Pop
722 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
723 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
724 a8083063 Iustin Pop

725 e69d05fd Iustin Pop
  @type hypervisor_list: list
726 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
727 e69d05fd Iustin Pop

728 e69d05fd Iustin Pop
  @rtype: list
729 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
730 10c2650b Iustin Pop
    - instance1.example.com
731 10c2650b Iustin Pop
    - instance2.example.com
732 a8083063 Iustin Pop

733 098c0958 Michael Hanselmann
  """
734 e69d05fd Iustin Pop
  results = []
735 e69d05fd Iustin Pop
  for hname in hypervisor_list:
736 e69d05fd Iustin Pop
    try:
737 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
738 e69d05fd Iustin Pop
      results.extend(names)
739 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
740 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
741 aca13712 Iustin Pop
            hname, err, exc=True)
742 a8083063 Iustin Pop
743 e69d05fd Iustin Pop
  return results
744 a8083063 Iustin Pop
745 a8083063 Iustin Pop
746 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
747 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
748 a8083063 Iustin Pop

749 e69d05fd Iustin Pop
  @type instance: string
750 e69d05fd Iustin Pop
  @param instance: the instance name
751 e69d05fd Iustin Pop
  @type hname: string
752 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
753 a8083063 Iustin Pop

754 e69d05fd Iustin Pop
  @rtype: dict
755 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
756 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
757 e69d05fd Iustin Pop
      - state: xen state of instance (string)
758 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
759 a8083063 Iustin Pop

760 098c0958 Michael Hanselmann
  """
761 a8083063 Iustin Pop
  output = {}
762 a8083063 Iustin Pop
763 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
764 a8083063 Iustin Pop
  if iinfo is not None:
765 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
766 a8083063 Iustin Pop
    output['state'] = iinfo[4]
767 a8083063 Iustin Pop
    output['time'] = iinfo[5]
768 a8083063 Iustin Pop
769 c26a6bd2 Iustin Pop
  return output
770 a8083063 Iustin Pop
771 a8083063 Iustin Pop
772 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
773 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
774 56e7640c Iustin Pop

775 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
776 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
777 56e7640c Iustin Pop

778 56e7640c Iustin Pop
  @rtype: tuple
779 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
780 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
781 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
782 56e7640c Iustin Pop

783 56e7640c Iustin Pop
  """
784 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
785 afdc3985 Iustin Pop
  iname = instance.name
786 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
787 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
788 56e7640c Iustin Pop
789 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
790 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
791 56e7640c Iustin Pop
    if not os.path.islink(link_name):
792 afdc3985 Iustin Pop
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
793 56e7640c Iustin Pop
794 56e7640c Iustin Pop
795 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
796 a8083063 Iustin Pop
  """Gather data about all instances.
797 a8083063 Iustin Pop

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

802 e69d05fd Iustin Pop
  @type hypervisor_list: list
803 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
804 e69d05fd Iustin Pop

805 955db481 Guido Trotter
  @rtype: dict
806 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
807 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
808 e69d05fd Iustin Pop
      - state: xen state of instance (string)
809 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
810 10c2650b Iustin Pop
      - vcpus: the number of vcpus
811 a8083063 Iustin Pop

812 098c0958 Michael Hanselmann
  """
813 a8083063 Iustin Pop
  output = {}
814 a8083063 Iustin Pop
815 e69d05fd Iustin Pop
  for hname in hypervisor_list:
816 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
817 e69d05fd Iustin Pop
    if iinfo:
818 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
819 f23b5ae8 Iustin Pop
        value = {
820 e69d05fd Iustin Pop
          'memory': memory,
821 e69d05fd Iustin Pop
          'vcpus': vcpus,
822 e69d05fd Iustin Pop
          'state': state,
823 e69d05fd Iustin Pop
          'time': times,
824 e69d05fd Iustin Pop
          }
825 b33b6f55 Iustin Pop
        if name in output:
826 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
827 b33b6f55 Iustin Pop
          # and not state and time which can change between the
828 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
829 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
830 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
831 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
832 2fa74ef4 Iustin Pop
                    " with different parameters", name)
833 f23b5ae8 Iustin Pop
        output[name] = value
834 a8083063 Iustin Pop
835 c26a6bd2 Iustin Pop
  return output
836 a8083063 Iustin Pop
837 a8083063 Iustin Pop
838 81a3406c Iustin Pop
def _InstanceLogName(kind, os_name, instance):
839 81a3406c Iustin Pop
  """Compute the OS log filename for a given instance and operation.
840 81a3406c Iustin Pop

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

844 81a3406c Iustin Pop
  @type kind: string
845 81a3406c Iustin Pop
  @param kind: the operation type (e.g. add, import, etc.)
846 81a3406c Iustin Pop
  @type os_name: string
847 81a3406c Iustin Pop
  @param os_name: the os name
848 81a3406c Iustin Pop
  @type instance: string
849 81a3406c Iustin Pop
  @param instance: the name of the instance being imported/added/etc.
850 81a3406c Iustin Pop

851 81a3406c Iustin Pop
  """
852 1651d116 Michael Hanselmann
  # TODO: Use tempfile.mkstemp to create unique filename
853 1d466a4f Michael Hanselmann
  base = ("%s-%s-%s-%s.log" %
854 1d466a4f Michael Hanselmann
          (kind, os_name, instance, utils.TimestampForFilename()))
855 81a3406c Iustin Pop
  return utils.PathJoin(constants.LOG_OS_DIR, base)
856 81a3406c Iustin Pop
857 81a3406c Iustin Pop
858 4a0e011f Iustin Pop
def InstanceOsAdd(instance, reinstall, debug):
859 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
860 a8083063 Iustin Pop

861 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
862 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
863 e557bae9 Guido Trotter
  @type reinstall: boolean
864 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
865 4a0e011f Iustin Pop
  @type debug: integer
866 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
867 c26a6bd2 Iustin Pop
  @rtype: None
868 a8083063 Iustin Pop

869 a8083063 Iustin Pop
  """
870 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
871 255dcebd Iustin Pop
872 4a0e011f Iustin Pop
  create_env = OSEnvironment(instance, inst_os, debug)
873 e557bae9 Guido Trotter
  if reinstall:
874 e557bae9 Guido Trotter
    create_env['INSTANCE_REINSTALL'] = "1"
875 a8083063 Iustin Pop
876 81a3406c Iustin Pop
  logfile = _InstanceLogName("add", instance.os, instance.name)
877 decd5f45 Iustin Pop
878 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
879 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
880 decd5f45 Iustin Pop
  if result.failed:
881 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
882 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
883 18682bca Iustin Pop
                  result.output)
884 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
885 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
886 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
887 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
888 decd5f45 Iustin Pop
889 decd5f45 Iustin Pop
890 4a0e011f Iustin Pop
def RunRenameInstance(instance, old_name, debug):
891 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
892 decd5f45 Iustin Pop

893 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
894 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
895 d15a9ad3 Guido Trotter
  @type old_name: string
896 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
897 4a0e011f Iustin Pop
  @type debug: integer
898 4a0e011f Iustin Pop
  @param debug: debug level, passed to the OS scripts
899 10c2650b Iustin Pop
  @rtype: boolean
900 10c2650b Iustin Pop
  @return: the success of the operation
901 decd5f45 Iustin Pop

902 decd5f45 Iustin Pop
  """
903 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
904 decd5f45 Iustin Pop
905 4a0e011f Iustin Pop
  rename_env = OSEnvironment(instance, inst_os, debug)
906 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
907 decd5f45 Iustin Pop
908 81a3406c Iustin Pop
  logfile = _InstanceLogName("rename", instance.os,
909 81a3406c Iustin Pop
                             "%s-%s" % (old_name, instance.name))
910 a8083063 Iustin Pop
911 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
912 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
913 a8083063 Iustin Pop
914 a8083063 Iustin Pop
  if result.failed:
915 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
916 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
917 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
918 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
919 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
920 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
921 a8083063 Iustin Pop
922 a8083063 Iustin Pop
923 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
924 5bbd3f7f Michael Hanselmann
  """Get information about the volume group.
925 a8083063 Iustin Pop

926 10c2650b Iustin Pop
  @type vg_name: str
927 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
928 10c2650b Iustin Pop
  @rtype: dict
929 10c2650b Iustin Pop
  @return:
930 10c2650b Iustin Pop
    A dictionary with the following keys:
931 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
932 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
933 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
934 a8083063 Iustin Pop

935 10c2650b Iustin Pop
    If an error occurs during gathering of data, we return the same dict
936 10c2650b Iustin Pop
    with keys all set to None.
937 f4d377e7 Iustin Pop

938 a8083063 Iustin Pop
  """
939 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
940 f4d377e7 Iustin Pop
941 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
942 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
943 a8083063 Iustin Pop
944 a8083063 Iustin Pop
  if retval.failed:
945 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
946 f4d377e7 Iustin Pop
    return retdic
947 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
948 f4d377e7 Iustin Pop
  if len(valarr) == 3:
949 f4d377e7 Iustin Pop
    try:
950 f4d377e7 Iustin Pop
      retdic = {
951 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
952 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
953 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
954 f4d377e7 Iustin Pop
        }
955 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
956 29921401 Iustin Pop
      logging.exception("Fail to parse vgs output: %s", err)
957 f4d377e7 Iustin Pop
  else:
958 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
959 18682bca Iustin Pop
                  " three): %s", str(valarr))
960 a8083063 Iustin Pop
  return retdic
961 a8083063 Iustin Pop
962 a8083063 Iustin Pop
963 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
964 c4feafe8 Iustin Pop
  return utils.PathJoin(constants.DISK_LINKS_DIR,
965 c4feafe8 Iustin Pop
                        "%s:%d" % (instance_name, idx))
966 5282084b Iustin Pop
967 5282084b Iustin Pop
968 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
969 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
970 9332fd8a Iustin Pop

971 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
972 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
973 9332fd8a Iustin Pop

974 9332fd8a Iustin Pop

975 5282084b Iustin Pop
  @param instance_name: the name of the target instance
976 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
977 5282084b Iustin Pop
  @param idx: the disk index
978 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
979 9332fd8a Iustin Pop

980 9332fd8a Iustin Pop
  """
981 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
982 9332fd8a Iustin Pop
  try:
983 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
984 5282084b Iustin Pop
  except OSError, err:
985 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
986 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
987 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
988 9332fd8a Iustin Pop
        os.remove(link_name)
989 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
990 9332fd8a Iustin Pop
    else:
991 9332fd8a Iustin Pop
      raise
992 9332fd8a Iustin Pop
993 9332fd8a Iustin Pop
  return link_name
994 9332fd8a Iustin Pop
995 9332fd8a Iustin Pop
996 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
997 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
998 3c9c571d Iustin Pop

999 3c9c571d Iustin Pop
  """
1000 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
1001 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1002 5282084b Iustin Pop
    if os.path.islink(link_name):
1003 3c9c571d Iustin Pop
      try:
1004 03dfa658 Iustin Pop
        os.remove(link_name)
1005 03dfa658 Iustin Pop
      except OSError:
1006 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
1007 3c9c571d Iustin Pop
1008 3c9c571d Iustin Pop
1009 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
1010 a8083063 Iustin Pop
  """Set up an instance's block device(s).
1011 a8083063 Iustin Pop

1012 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
1013 a8083063 Iustin Pop
  devices must be already assembled.
1014 a8083063 Iustin Pop

1015 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1016 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
1017 069cfbf1 Iustin Pop
  @rtype: list
1018 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
1019 10c2650b Iustin Pop

1020 a8083063 Iustin Pop
  """
1021 a8083063 Iustin Pop
  block_devices = []
1022 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
1023 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
1024 a8083063 Iustin Pop
    if device is None:
1025 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1026 a8083063 Iustin Pop
                                    str(disk))
1027 a8083063 Iustin Pop
    device.Open()
1028 9332fd8a Iustin Pop
    try:
1029 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1030 9332fd8a Iustin Pop
    except OSError, e:
1031 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1032 9332fd8a Iustin Pop
                                    e.strerror)
1033 9332fd8a Iustin Pop
1034 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
1035 9332fd8a Iustin Pop
1036 a8083063 Iustin Pop
  return block_devices
1037 a8083063 Iustin Pop
1038 a8083063 Iustin Pop
1039 07813a9e Iustin Pop
def StartInstance(instance):
1040 a8083063 Iustin Pop
  """Start an instance.
1041 a8083063 Iustin Pop

1042 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1043 e69d05fd Iustin Pop
  @param instance: the instance object
1044 c26a6bd2 Iustin Pop
  @rtype: None
1045 a8083063 Iustin Pop

1046 098c0958 Michael Hanselmann
  """
1047 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1048 a8083063 Iustin Pop
1049 a8083063 Iustin Pop
  if instance.name in running_instances:
1050 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
1051 c26a6bd2 Iustin Pop
    return
1052 a8083063 Iustin Pop
1053 a8083063 Iustin Pop
  try:
1054 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
1055 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1056 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
1057 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
1058 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
1059 a8083063 Iustin Pop
  except errors.HypervisorError, err:
1060 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
1061 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
1062 a8083063 Iustin Pop
1063 a8083063 Iustin Pop
1064 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
1065 a8083063 Iustin Pop
  """Shut an instance down.
1066 a8083063 Iustin Pop

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

1069 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1070 e69d05fd Iustin Pop
  @param instance: the instance object
1071 6263189c Guido Trotter
  @type timeout: integer
1072 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
1073 c26a6bd2 Iustin Pop
  @rtype: None
1074 a8083063 Iustin Pop

1075 098c0958 Michael Hanselmann
  """
1076 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
1077 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
1078 c26a6bd2 Iustin Pop
  iname = instance.name
1079 a8083063 Iustin Pop
1080 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1081 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1082 c26a6bd2 Iustin Pop
    return
1083 a8083063 Iustin Pop
1084 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1085 3c0cdc83 Michael Hanselmann
    def __init__(self):
1086 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1087 a8083063 Iustin Pop
1088 3c0cdc83 Michael Hanselmann
    def __call__(self):
1089 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1090 3c0cdc83 Michael Hanselmann
        return
1091 3c0cdc83 Michael Hanselmann
1092 3c0cdc83 Michael Hanselmann
      try:
1093 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1094 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1095 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1096 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1097 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1098 3c0cdc83 Michael Hanselmann
          return
1099 3c0cdc83 Michael Hanselmann
1100 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1101 3c0cdc83 Michael Hanselmann
1102 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1103 3c0cdc83 Michael Hanselmann
1104 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1105 3c0cdc83 Michael Hanselmann
1106 3c0cdc83 Michael Hanselmann
  try:
1107 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1108 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1109 a8083063 Iustin Pop
    # the shutdown did not succeed
1110 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1111 a8083063 Iustin Pop
1112 a8083063 Iustin Pop
    try:
1113 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1114 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1115 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1116 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1117 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1118 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1119 a8083063 Iustin Pop
1120 a8083063 Iustin Pop
    time.sleep(1)
1121 3c0cdc83 Michael Hanselmann
1122 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1123 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1124 3c9c571d Iustin Pop
1125 f28ec899 Guido Trotter
  try:
1126 f28ec899 Guido Trotter
    hyper.CleanupInstance(instance.name)
1127 f28ec899 Guido Trotter
  except errors.HypervisorError, err:
1128 f28ec899 Guido Trotter
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1129 f28ec899 Guido Trotter
1130 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1131 a8083063 Iustin Pop
1132 a8083063 Iustin Pop
1133 17c3f802 Guido Trotter
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1134 007a2f3e Alexander Schreiber
  """Reboot an instance.
1135 007a2f3e Alexander Schreiber

1136 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1137 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1138 10c2650b Iustin Pop
  @type reboot_type: str
1139 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1140 10c2650b Iustin Pop
    constants:
1141 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1142 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1143 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1144 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1145 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1146 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1147 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1148 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1149 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1150 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1151 c26a6bd2 Iustin Pop
  @rtype: None
1152 007a2f3e Alexander Schreiber

1153 007a2f3e Alexander Schreiber
  """
1154 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1155 007a2f3e Alexander Schreiber
1156 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1157 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1158 007a2f3e Alexander Schreiber
1159 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1160 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1161 007a2f3e Alexander Schreiber
    try:
1162 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1163 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1164 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1165 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1166 007a2f3e Alexander Schreiber
    try:
1167 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1168 07813a9e Iustin Pop
      return StartInstance(instance)
1169 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1170 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1171 007a2f3e Alexander Schreiber
  else:
1172 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1173 007a2f3e Alexander Schreiber
1174 007a2f3e Alexander Schreiber
1175 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1176 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1177 6906a9d8 Guido Trotter

1178 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1179 6906a9d8 Guido Trotter
  @param instance: the instance definition
1180 6906a9d8 Guido Trotter

1181 6906a9d8 Guido Trotter
  """
1182 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1183 cd42d0ad Guido Trotter
  try:
1184 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1185 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1186 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1187 c26a6bd2 Iustin Pop
  return info
1188 6906a9d8 Guido Trotter
1189 6906a9d8 Guido Trotter
1190 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1191 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1192 6906a9d8 Guido Trotter

1193 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1194 6906a9d8 Guido Trotter
  @param instance: the instance definition
1195 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1196 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1197 6906a9d8 Guido Trotter
  @type target: string
1198 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1199 6906a9d8 Guido Trotter

1200 6906a9d8 Guido Trotter
  """
1201 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1202 cd42d0ad Guido Trotter
  try:
1203 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1204 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1205 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1206 6906a9d8 Guido Trotter
1207 6906a9d8 Guido Trotter
1208 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1209 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1210 6906a9d8 Guido Trotter

1211 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1212 6906a9d8 Guido Trotter
  @param instance: the instance definition
1213 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1214 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1215 6906a9d8 Guido Trotter
  @type success: boolean
1216 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1217 6906a9d8 Guido Trotter

1218 6906a9d8 Guido Trotter
  """
1219 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1220 cd42d0ad Guido Trotter
  try:
1221 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1222 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1223 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1224 6906a9d8 Guido Trotter
1225 6906a9d8 Guido Trotter
1226 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1227 2a10865c Iustin Pop
  """Migrates an instance to another node.
1228 2a10865c Iustin Pop

1229 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1230 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1231 9f0e6b37 Iustin Pop
  @type target: string
1232 9f0e6b37 Iustin Pop
  @param target: the target node name
1233 9f0e6b37 Iustin Pop
  @type live: boolean
1234 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1235 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1236 9f0e6b37 Iustin Pop
  @rtype: tuple
1237 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1238 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1239 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1240 9f0e6b37 Iustin Pop

1241 2a10865c Iustin Pop
  """
1242 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1243 2a10865c Iustin Pop
1244 2a10865c Iustin Pop
  try:
1245 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1246 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1247 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1248 2a10865c Iustin Pop
1249 2a10865c Iustin Pop
1250 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1251 a8083063 Iustin Pop
  """Creates a block device for an instance.
1252 a8083063 Iustin Pop

1253 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1254 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1255 b1206984 Iustin Pop
  @type size: int
1256 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1257 b1206984 Iustin Pop
  @type owner: str
1258 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1259 b1206984 Iustin Pop
      used for device cache data
1260 b1206984 Iustin Pop
  @type on_primary: boolean
1261 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1262 b1206984 Iustin Pop
  @type info: string
1263 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1264 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1265 b1206984 Iustin Pop

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

1270 a8083063 Iustin Pop
  """
1271 7260cfbe Iustin Pop
  # TODO: remove the obsolete 'size' argument
1272 7260cfbe Iustin Pop
  # pylint: disable-msg=W0613
1273 a8083063 Iustin Pop
  clist = []
1274 a8083063 Iustin Pop
  if disk.children:
1275 a8083063 Iustin Pop
    for child in disk.children:
1276 1063abd1 Iustin Pop
      try:
1277 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1278 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1279 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1280 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1281 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1282 a8083063 Iustin Pop
        # be assembled
1283 1063abd1 Iustin Pop
        try:
1284 fe267188 Iustin Pop
          # pylint: disable-msg=E1103
1285 1063abd1 Iustin Pop
          crdev.Open()
1286 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1287 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1288 a8083063 Iustin Pop
      clist.append(crdev)
1289 a8083063 Iustin Pop
1290 dab69e97 Iustin Pop
  try:
1291 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1292 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1293 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1294 6c626518 Iustin Pop
1295 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1296 1063abd1 Iustin Pop
    try:
1297 1063abd1 Iustin Pop
      device.Assemble()
1298 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1299 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1300 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1301 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1302 1063abd1 Iustin Pop
      try:
1303 1063abd1 Iustin Pop
        device.Open(force=True)
1304 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1305 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1306 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1307 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1308 a0c3fea1 Michael Hanselmann
1309 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1310 a0c3fea1 Michael Hanselmann
1311 c26a6bd2 Iustin Pop
  return device.unique_id
1312 a8083063 Iustin Pop
1313 a8083063 Iustin Pop
1314 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1315 a8083063 Iustin Pop
  """Remove a block device.
1316 a8083063 Iustin Pop

1317 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1318 10c2650b Iustin Pop

1319 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1320 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1321 10c2650b Iustin Pop
  @rtype: boolean
1322 10c2650b Iustin Pop
  @return: the success of the operation
1323 a8083063 Iustin Pop

1324 a8083063 Iustin Pop
  """
1325 e1bc0878 Iustin Pop
  msgs = []
1326 a8083063 Iustin Pop
  try:
1327 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1328 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1329 a8083063 Iustin Pop
    # probably can't attach
1330 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1331 a8083063 Iustin Pop
    rdev = None
1332 a8083063 Iustin Pop
  if rdev is not None:
1333 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1334 e1bc0878 Iustin Pop
    try:
1335 0c6c04ec Iustin Pop
      rdev.Remove()
1336 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1337 e1bc0878 Iustin Pop
      msgs.append(str(err))
1338 c26a6bd2 Iustin Pop
    if not msgs:
1339 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1340 e1bc0878 Iustin Pop
1341 a8083063 Iustin Pop
  if disk.children:
1342 a8083063 Iustin Pop
    for child in disk.children:
1343 c26a6bd2 Iustin Pop
      try:
1344 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1345 c26a6bd2 Iustin Pop
      except RPCFail, err:
1346 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1347 e1bc0878 Iustin Pop
1348 c26a6bd2 Iustin Pop
  if msgs:
1349 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1350 afdc3985 Iustin Pop
1351 a8083063 Iustin Pop
1352 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1353 a8083063 Iustin Pop
  """Activate a block device for an instance.
1354 a8083063 Iustin Pop

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

1357 10c2650b Iustin Pop
  @note: this function is called recursively.
1358 a8083063 Iustin Pop

1359 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1360 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1361 10c2650b Iustin Pop
  @type owner: str
1362 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1363 10c2650b Iustin Pop
  @type as_primary: boolean
1364 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1365 10c2650b Iustin Pop
      read/write
1366 a8083063 Iustin Pop

1367 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1368 10c2650b Iustin Pop
      was assembled)
1369 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1370 10c2650b Iustin Pop
      during the activation of the children or the device
1371 10c2650b Iustin Pop
      itself
1372 a8083063 Iustin Pop

1373 a8083063 Iustin Pop
  """
1374 a8083063 Iustin Pop
  children = []
1375 a8083063 Iustin Pop
  if disk.children:
1376 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1377 fc1dc9d7 Iustin Pop
    if mcn == -1:
1378 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1379 fc1dc9d7 Iustin Pop
    else:
1380 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1381 a8083063 Iustin Pop
    for chld_disk in disk.children:
1382 fc1dc9d7 Iustin Pop
      try:
1383 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1384 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1385 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1386 fc1dc9d7 Iustin Pop
          raise
1387 fc1dc9d7 Iustin Pop
        cdev = None
1388 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1389 1063abd1 Iustin Pop
                      str(err))
1390 fc1dc9d7 Iustin Pop
      children.append(cdev)
1391 a8083063 Iustin Pop
1392 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1393 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1394 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1395 a8083063 Iustin Pop
    result = r_dev
1396 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1397 a8083063 Iustin Pop
      r_dev.Open()
1398 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1399 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1400 3f78eef2 Iustin Pop
1401 a8083063 Iustin Pop
  else:
1402 a8083063 Iustin Pop
    result = True
1403 a8083063 Iustin Pop
  return result
1404 a8083063 Iustin Pop
1405 a8083063 Iustin Pop
1406 821d1bd1 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary):
1407 a8083063 Iustin Pop
  """Activate a block device for an instance.
1408 a8083063 Iustin Pop

1409 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1410 a8083063 Iustin Pop

1411 b1206984 Iustin Pop
  @rtype: str or boolean
1412 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1413 b1206984 Iustin Pop
      C{True} for secondary nodes
1414 a8083063 Iustin Pop

1415 a8083063 Iustin Pop
  """
1416 53c14ef1 Iustin Pop
  try:
1417 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1418 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1419 fe267188 Iustin Pop
      # pylint: disable-msg=E1103
1420 53c14ef1 Iustin Pop
      result = result.dev_path
1421 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1422 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1423 afdc3985 Iustin Pop
1424 c26a6bd2 Iustin Pop
  return result
1425 a8083063 Iustin Pop
1426 a8083063 Iustin Pop
1427 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1428 a8083063 Iustin Pop
  """Shut down a block device.
1429 a8083063 Iustin Pop

1430 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1431 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1432 c41eea6e Iustin Pop
  shutdown.
1433 a8083063 Iustin Pop

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

1438 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1439 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1440 10c2650b Iustin Pop
      shutdown
1441 c26a6bd2 Iustin Pop
  @rtype: None
1442 10c2650b Iustin Pop

1443 a8083063 Iustin Pop
  """
1444 cacfd1fd Iustin Pop
  msgs = []
1445 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1446 a8083063 Iustin Pop
  if r_dev is not None:
1447 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1448 cacfd1fd Iustin Pop
    try:
1449 746f7476 Iustin Pop
      r_dev.Shutdown()
1450 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1451 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1452 cacfd1fd Iustin Pop
      msgs.append(str(err))
1453 746f7476 Iustin Pop
1454 a8083063 Iustin Pop
  if disk.children:
1455 a8083063 Iustin Pop
    for child in disk.children:
1456 c26a6bd2 Iustin Pop
      try:
1457 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1458 c26a6bd2 Iustin Pop
      except RPCFail, err:
1459 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1460 746f7476 Iustin Pop
1461 c26a6bd2 Iustin Pop
  if msgs:
1462 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1463 a8083063 Iustin Pop
1464 a8083063 Iustin Pop
1465 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1466 153d9724 Iustin Pop
  """Extend a mirrored block device.
1467 a8083063 Iustin Pop

1468 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1469 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1470 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1471 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1472 c26a6bd2 Iustin Pop
  @rtype: None
1473 10c2650b Iustin Pop

1474 a8083063 Iustin Pop
  """
1475 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1476 153d9724 Iustin Pop
  if parent_bdev is None:
1477 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1478 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1479 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1480 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1481 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1482 a8083063 Iustin Pop
1483 a8083063 Iustin Pop
1484 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1485 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1486 a8083063 Iustin Pop

1487 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1488 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1489 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1490 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1491 c26a6bd2 Iustin Pop
  @rtype: None
1492 10c2650b Iustin Pop

1493 a8083063 Iustin Pop
  """
1494 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1495 153d9724 Iustin Pop
  if parent_bdev is None:
1496 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1497 e739bd57 Iustin Pop
  devs = []
1498 e739bd57 Iustin Pop
  for disk in new_cdevs:
1499 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1500 e739bd57 Iustin Pop
    if rpath is None:
1501 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1502 e739bd57 Iustin Pop
      if bd is None:
1503 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1504 e739bd57 Iustin Pop
      else:
1505 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1506 e739bd57 Iustin Pop
    else:
1507 e51db2a6 Iustin Pop
      if not utils.IsNormAbsPath(rpath):
1508 e51db2a6 Iustin Pop
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1509 e739bd57 Iustin Pop
      devs.append(rpath)
1510 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1511 a8083063 Iustin Pop
1512 a8083063 Iustin Pop
1513 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1514 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1515 a8083063 Iustin Pop

1516 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1517 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1518 10c2650b Iustin Pop
  @rtype: disk
1519 10c2650b Iustin Pop
  @return:
1520 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1521 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1522 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1523 10c2650b Iustin Pop
      found
1524 a8083063 Iustin Pop

1525 a8083063 Iustin Pop
  """
1526 a8083063 Iustin Pop
  stats = []
1527 a8083063 Iustin Pop
  for dsk in disks:
1528 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1529 a8083063 Iustin Pop
    if rbd is None:
1530 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1531 96acbc09 Michael Hanselmann
1532 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1533 96acbc09 Michael Hanselmann
1534 c26a6bd2 Iustin Pop
  return stats
1535 a8083063 Iustin Pop
1536 a8083063 Iustin Pop
1537 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1538 a8083063 Iustin Pop
  """Check if a device is activated.
1539 a8083063 Iustin Pop

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

1542 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1543 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1544 a8083063 Iustin Pop

1545 10c2650b Iustin Pop
  @return: None if the device can't be found,
1546 10c2650b Iustin Pop
      otherwise the device instance
1547 a8083063 Iustin Pop

1548 a8083063 Iustin Pop
  """
1549 a8083063 Iustin Pop
  children = []
1550 a8083063 Iustin Pop
  if disk.children:
1551 a8083063 Iustin Pop
    for chdisk in disk.children:
1552 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1553 a8083063 Iustin Pop
1554 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1555 a8083063 Iustin Pop
1556 a8083063 Iustin Pop
1557 f2e07bb4 Michael Hanselmann
def _OpenRealBD(disk):
1558 f2e07bb4 Michael Hanselmann
  """Opens the underlying block device of a disk.
1559 f2e07bb4 Michael Hanselmann

1560 f2e07bb4 Michael Hanselmann
  @type disk: L{objects.Disk}
1561 f2e07bb4 Michael Hanselmann
  @param disk: the disk object we want to open
1562 f2e07bb4 Michael Hanselmann

1563 f2e07bb4 Michael Hanselmann
  """
1564 f2e07bb4 Michael Hanselmann
  real_disk = _RecursiveFindBD(disk)
1565 f2e07bb4 Michael Hanselmann
  if real_disk is None:
1566 f2e07bb4 Michael Hanselmann
    _Fail("Block device '%s' is not set up", disk)
1567 f2e07bb4 Michael Hanselmann
1568 f2e07bb4 Michael Hanselmann
  real_disk.Open()
1569 f2e07bb4 Michael Hanselmann
1570 f2e07bb4 Michael Hanselmann
  return real_disk
1571 f2e07bb4 Michael Hanselmann
1572 f2e07bb4 Michael Hanselmann
1573 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1574 a8083063 Iustin Pop
  """Check if a device is activated.
1575 a8083063 Iustin Pop

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

1578 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1579 10c2650b Iustin Pop
  @param disk: the disk to find
1580 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1581 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1582 96acbc09 Michael Hanselmann
           information
1583 a8083063 Iustin Pop

1584 a8083063 Iustin Pop
  """
1585 23829f6f Iustin Pop
  try:
1586 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1587 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1588 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1589 96acbc09 Michael Hanselmann
1590 a8083063 Iustin Pop
  if rbd is None:
1591 c26a6bd2 Iustin Pop
    return None
1592 96acbc09 Michael Hanselmann
1593 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
1594 a8083063 Iustin Pop
1595 a8083063 Iustin Pop
1596 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1597 968a7623 Iustin Pop
  """Computes the size of the given disks.
1598 968a7623 Iustin Pop

1599 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
1600 968a7623 Iustin Pop

1601 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
1602 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
1603 968a7623 Iustin Pop
  @rtype: list
1604 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
1605 968a7623 Iustin Pop
      otherwise the size
1606 968a7623 Iustin Pop

1607 968a7623 Iustin Pop
  """
1608 968a7623 Iustin Pop
  result = []
1609 968a7623 Iustin Pop
  for cf in disks:
1610 968a7623 Iustin Pop
    try:
1611 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
1612 1122eb25 Iustin Pop
    except errors.BlockDeviceError:
1613 968a7623 Iustin Pop
      result.append(None)
1614 968a7623 Iustin Pop
      continue
1615 968a7623 Iustin Pop
    if rbd is None:
1616 968a7623 Iustin Pop
      result.append(None)
1617 968a7623 Iustin Pop
    else:
1618 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
1619 968a7623 Iustin Pop
  return result
1620 968a7623 Iustin Pop
1621 968a7623 Iustin Pop
1622 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1623 858f3d18 Iustin Pop
  """Export a block device to a remote node.
1624 858f3d18 Iustin Pop

1625 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
1626 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
1627 858f3d18 Iustin Pop
  @type dest_node: str
1628 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
1629 858f3d18 Iustin Pop
  @type dest_path: str
1630 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
1631 858f3d18 Iustin Pop
  @type cluster_name: str
1632 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1633 858f3d18 Iustin Pop
  @rtype: None
1634 858f3d18 Iustin Pop

1635 858f3d18 Iustin Pop
  """
1636 f2e07bb4 Michael Hanselmann
  real_disk = _OpenRealBD(disk)
1637 858f3d18 Iustin Pop
1638 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
1639 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1640 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
1641 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
1642 858f3d18 Iustin Pop
1643 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
1644 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
1645 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
1646 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
1647 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
1648 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
1649 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
1650 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
1651 858f3d18 Iustin Pop
1652 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1653 858f3d18 Iustin Pop
                                                   constants.GANETI_RUNAS,
1654 858f3d18 Iustin Pop
                                                   destcmd)
1655 858f3d18 Iustin Pop
1656 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1657 858f3d18 Iustin Pop
  command = '|'.join([expcmd, utils.ShellQuoteArgs(remotecmd)])
1658 858f3d18 Iustin Pop
1659 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
1660 858f3d18 Iustin Pop
1661 858f3d18 Iustin Pop
  if result.failed:
1662 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
1663 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1664 858f3d18 Iustin Pop
1665 858f3d18 Iustin Pop
1666 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1667 a8083063 Iustin Pop
  """Write a file to the filesystem.
1668 a8083063 Iustin Pop

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

1672 10c2650b Iustin Pop
  @type file_name: str
1673 10c2650b Iustin Pop
  @param file_name: the target file name
1674 10c2650b Iustin Pop
  @type data: str
1675 10c2650b Iustin Pop
  @param data: the new contents of the file
1676 10c2650b Iustin Pop
  @type mode: int
1677 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1678 10c2650b Iustin Pop
  @type uid: int
1679 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1680 10c2650b Iustin Pop
  @type gid: int
1681 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1682 10c2650b Iustin Pop
  @type atime: float
1683 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1684 10c2650b Iustin Pop
  @type mtime: float
1685 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1686 c26a6bd2 Iustin Pop
  @rtype: None
1687 10c2650b Iustin Pop

1688 a8083063 Iustin Pop
  """
1689 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1690 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1691 a8083063 Iustin Pop
1692 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
1693 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1694 2cc6781a Iustin Pop
          file_name)
1695 a8083063 Iustin Pop
1696 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1697 12bce260 Michael Hanselmann
1698 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1699 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1700 a8083063 Iustin Pop
1701 386b57af Iustin Pop
1702 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1703 89b14f05 Iustin Pop
  """Update all ssconf files.
1704 89b14f05 Iustin Pop

1705 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1706 89b14f05 Iustin Pop

1707 89b14f05 Iustin Pop
  """
1708 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1709 6ddc95ec Michael Hanselmann
1710 6ddc95ec Michael Hanselmann
1711 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1712 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1713 a8083063 Iustin Pop

1714 10c2650b Iustin Pop
  If the L{err} argument has an errno attribute, it will be looked up
1715 10c2650b Iustin Pop
  and converted into a textual C{E...} description. Otherwise the
1716 10c2650b Iustin Pop
  string representation of the error will be returned.
1717 10c2650b Iustin Pop

1718 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1719 10c2650b Iustin Pop
  @param err: the exception to format
1720 a8083063 Iustin Pop

1721 a8083063 Iustin Pop
  """
1722 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1723 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1724 a8083063 Iustin Pop
  else:
1725 a8083063 Iustin Pop
    detail = str(err)
1726 a8083063 Iustin Pop
  return detail
1727 a8083063 Iustin Pop
1728 5d0fe286 Iustin Pop
1729 c19f9810 Iustin Pop
def _OSOndiskAPIVersion(os_dir):
1730 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1731 a8083063 Iustin Pop

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

1735 10c2650b Iustin Pop
  @type os_dir: str
1736 c19f9810 Iustin Pop
  @param os_dir: the directory in which we should look for the OS
1737 8e70b181 Iustin Pop
  @rtype: tuple
1738 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
1739 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
1740 a8083063 Iustin Pop

1741 a8083063 Iustin Pop
  """
1742 e02b9114 Iustin Pop
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1743 a8083063 Iustin Pop
1744 a8083063 Iustin Pop
  try:
1745 a8083063 Iustin Pop
    st = os.stat(api_file)
1746 a8083063 Iustin Pop
  except EnvironmentError, err:
1747 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
1748 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1749 a8083063 Iustin Pop
1750 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1751 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
1752 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
1753 a8083063 Iustin Pop
1754 a8083063 Iustin Pop
  try:
1755 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
1756 a8083063 Iustin Pop
  except EnvironmentError, err:
1757 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
1758 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
1759 a8083063 Iustin Pop
1760 a8083063 Iustin Pop
  try:
1761 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
1762 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1763 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
1764 255dcebd Iustin Pop
                   str(err))
1765 a8083063 Iustin Pop
1766 255dcebd Iustin Pop
  return True, api_versions
1767 a8083063 Iustin Pop
1768 386b57af Iustin Pop
1769 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1770 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1771 a8083063 Iustin Pop

1772 10c2650b Iustin Pop
  @type top_dirs: list
1773 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1774 10c2650b Iustin Pop
      search (if not given defaults to
1775 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1776 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1777 ba00557a Guido Trotter
  @return: a list of tuples (name, path, status, diagnose, variants)
1778 255dcebd Iustin Pop
      for all (potential) OSes under all search paths, where:
1779 255dcebd Iustin Pop
          - name is the (potential) OS name
1780 255dcebd Iustin Pop
          - path is the full path to the OS
1781 255dcebd Iustin Pop
          - status True/False is the validity of the OS
1782 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
1783 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
1784 a8083063 Iustin Pop

1785 a8083063 Iustin Pop
  """
1786 7c3d51d4 Guido Trotter
  if top_dirs is None:
1787 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1788 a8083063 Iustin Pop
1789 a8083063 Iustin Pop
  result = []
1790 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1791 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1792 7c3d51d4 Guido Trotter
      try:
1793 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1794 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1795 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1796 7c3d51d4 Guido Trotter
        break
1797 7c3d51d4 Guido Trotter
      for name in f_names:
1798 e02b9114 Iustin Pop
        os_path = utils.PathJoin(dir_name, name)
1799 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1800 255dcebd Iustin Pop
        if status:
1801 255dcebd Iustin Pop
          diagnose = ""
1802 ba00557a Guido Trotter
          variants = os_inst.supported_variants
1803 255dcebd Iustin Pop
        else:
1804 255dcebd Iustin Pop
          diagnose = os_inst
1805 ba00557a Guido Trotter
          variants = []
1806 ba00557a Guido Trotter
        result.append((name, os_path, status, diagnose, variants))
1807 a8083063 Iustin Pop
1808 c26a6bd2 Iustin Pop
  return result
1809 a8083063 Iustin Pop
1810 a8083063 Iustin Pop
1811 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
1812 a8083063 Iustin Pop
  """Create an OS instance from disk.
1813 a8083063 Iustin Pop

1814 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1815 8e70b181 Iustin Pop
  valid OS name.
1816 a8083063 Iustin Pop

1817 8ee4dc80 Guido Trotter
  @type base_dir: string
1818 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1819 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1820 255dcebd Iustin Pop
  @rtype: tuple
1821 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
1822 255dcebd Iustin Pop
      or error message
1823 7c3d51d4 Guido Trotter

1824 a8083063 Iustin Pop
  """
1825 56bcd3f4 Guido Trotter
  if base_dir is None:
1826 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1827 c34c0cfd Iustin Pop
  else:
1828 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1829 f95c81bf Iustin Pop
1830 f95c81bf Iustin Pop
  if os_dir is None:
1831 5c0433d6 Iustin Pop
    return False, "Directory for OS %s not found in search path" % name
1832 a8083063 Iustin Pop
1833 c19f9810 Iustin Pop
  status, api_versions = _OSOndiskAPIVersion(os_dir)
1834 255dcebd Iustin Pop
  if not status:
1835 255dcebd Iustin Pop
    # push the error up
1836 255dcebd Iustin Pop
    return status, api_versions
1837 a8083063 Iustin Pop
1838 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1839 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1840 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1841 a8083063 Iustin Pop
1842 41ba4061 Guido Trotter
  # OS Files dictionary, we will populate it with the absolute path names
1843 41ba4061 Guido Trotter
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1844 a8083063 Iustin Pop
1845 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
1846 95075fba Guido Trotter
    os_files[constants.OS_VARIANTS_FILE] = ''
1847 95075fba Guido Trotter
1848 ea79fc15 Michael Hanselmann
  for filename in os_files:
1849 e02b9114 Iustin Pop
    os_files[filename] = utils.PathJoin(os_dir, filename)
1850 a8083063 Iustin Pop
1851 a8083063 Iustin Pop
    try:
1852 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
1853 a8083063 Iustin Pop
    except EnvironmentError, err:
1854 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
1855 ea79fc15 Michael Hanselmann
                     (filename, os_dir, _ErrnoOrStr(err)))
1856 a8083063 Iustin Pop
1857 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1858 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
1859 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
1860 255dcebd Iustin Pop
1861 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
1862 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1863 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
1864 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
1865 0757c107 Guido Trotter
1866 95075fba Guido Trotter
  variants = None
1867 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
1868 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
1869 95075fba Guido Trotter
    try:
1870 95075fba Guido Trotter
      variants = utils.ReadFile(variants_file).splitlines()
1871 95075fba Guido Trotter
    except EnvironmentError, err:
1872 95075fba Guido Trotter
      return False, ("Error while reading the OS variants file at %s: %s" %
1873 95075fba Guido Trotter
                     (variants_file, _ErrnoOrStr(err)))
1874 95075fba Guido Trotter
    if not variants:
1875 95075fba Guido Trotter
      return False, ("No supported os variant found")
1876 0757c107 Guido Trotter
1877 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
1878 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
1879 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
1880 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
1881 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
1882 95075fba Guido Trotter
                      supported_variants=variants,
1883 255dcebd Iustin Pop
                      api_versions=api_versions)
1884 255dcebd Iustin Pop
  return True, os_obj
1885 255dcebd Iustin Pop
1886 255dcebd Iustin Pop
1887 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
1888 255dcebd Iustin Pop
  """Create an OS instance from disk.
1889 255dcebd Iustin Pop

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

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

1897 255dcebd Iustin Pop
  @type base_dir: string
1898 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
1899 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1900 255dcebd Iustin Pop
  @rtype: L{objects.OS}
1901 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
1902 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
1903 255dcebd Iustin Pop

1904 255dcebd Iustin Pop
  """
1905 69b99987 Michael Hanselmann
  name_only = name.split("+", 1)[0]
1906 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
1907 255dcebd Iustin Pop
1908 255dcebd Iustin Pop
  if not status:
1909 255dcebd Iustin Pop
    _Fail(payload)
1910 a8083063 Iustin Pop
1911 255dcebd Iustin Pop
  return payload
1912 a8083063 Iustin Pop
1913 a8083063 Iustin Pop
1914 099c52ad Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
1915 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1916 2266edb2 Guido Trotter

1917 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1918 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1919 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
1920 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
1921 2266edb2 Guido Trotter
  @type debug: integer
1922 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1923 2266edb2 Guido Trotter
  @rtype: dict
1924 2266edb2 Guido Trotter
  @return: dict of environment variables
1925 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1926 10c2650b Iustin Pop
      cannot be found
1927 2266edb2 Guido Trotter

1928 2266edb2 Guido Trotter
  """
1929 2266edb2 Guido Trotter
  result = {}
1930 099c52ad Iustin Pop
  api_version = \
1931 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
1932 d1a7d66f Guido Trotter
  result['OS_API_VERSION'] = '%d' % api_version
1933 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1934 15552312 Iustin Pop
  result['INSTANCE_OS'] = instance.os
1935 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1936 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1937 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1938 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1939 f11280b5 Guido Trotter
  if api_version >= constants.OS_API_V15:
1940 f11280b5 Guido Trotter
    try:
1941 f11280b5 Guido Trotter
      variant = instance.os.split('+', 1)[1]
1942 f11280b5 Guido Trotter
    except IndexError:
1943 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
1944 f11280b5 Guido Trotter
    result['OS_VARIANT'] = variant
1945 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1946 f2e07bb4 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
1947 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1948 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
1949 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1950 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1951 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1952 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1953 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1954 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1955 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1956 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1957 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1958 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1959 2266edb2 Guido Trotter
    if nic.ip:
1960 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1961 1ba9227f Guido Trotter
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1962 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1963 1ba9227f Guido Trotter
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1964 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
1965 1ba9227f Guido Trotter
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1966 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1967 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1968 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1969 2266edb2 Guido Trotter
1970 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1971 67fc3042 Iustin Pop
    for key, value in source.items():
1972 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1973 67fc3042 Iustin Pop
1974 2266edb2 Guido Trotter
  return result
1975 a8083063 Iustin Pop
1976 f2e07bb4 Michael Hanselmann
1977 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
1978 594609c0 Iustin Pop
  """Grow a stack of block devices.
1979 594609c0 Iustin Pop

1980 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1981 10c2650b Iustin Pop
  first ones to resize.
1982 594609c0 Iustin Pop

1983 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1984 10c2650b Iustin Pop
  @param disk: the disk to be grown
1985 10c2650b Iustin Pop
  @rtype: (status, result)
1986 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1987 10c2650b Iustin Pop
      (True/False), and the errors message if status
1988 10c2650b Iustin Pop
      is False
1989 594609c0 Iustin Pop

1990 594609c0 Iustin Pop
  """
1991 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1992 594609c0 Iustin Pop
  if r_dev is None:
1993 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
1994 594609c0 Iustin Pop
1995 594609c0 Iustin Pop
  try:
1996 594609c0 Iustin Pop
    r_dev.Grow(amount)
1997 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1998 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
1999 594609c0 Iustin Pop
2000 594609c0 Iustin Pop
2001 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
2002 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
2003 a8083063 Iustin Pop

2004 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
2005 a8083063 Iustin Pop
  just for the leaf lvm backend device.
2006 a8083063 Iustin Pop

2007 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
2008 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
2009 e9e9263d Guido Trotter
  @rtype: string
2010 e9e9263d Guido Trotter
  @return: snapshot disk path
2011 a8083063 Iustin Pop

2012 098c0958 Michael Hanselmann
  """
2013 433c63aa Iustin Pop
  if disk.dev_type == constants.LD_DRBD8:
2014 433c63aa Iustin Pop
    if not disk.children:
2015 433c63aa Iustin Pop
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2016 433c63aa Iustin Pop
            disk.unique_id)
2017 433c63aa Iustin Pop
    return BlockdevSnapshot(disk.children[0])
2018 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
2019 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
2020 a8083063 Iustin Pop
    if r_dev is not None:
2021 433c63aa Iustin Pop
      # FIXME: choose a saner value for the snapshot size
2022 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
2023 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
2024 a8083063 Iustin Pop
    else:
2025 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
2026 a8083063 Iustin Pop
  else:
2027 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2028 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
2029 a8083063 Iustin Pop
2030 a8083063 Iustin Pop
2031 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
2032 a8083063 Iustin Pop
  """Write out the export configuration information.
2033 a8083063 Iustin Pop

2034 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2035 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2036 10c2650b Iustin Pop
      saving configuration
2037 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2038 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2039 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2040 a8083063 Iustin Pop

2041 c26a6bd2 Iustin Pop
  @rtype: None
2042 a8083063 Iustin Pop

2043 098c0958 Michael Hanselmann
  """
2044 c4feafe8 Iustin Pop
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2045 c4feafe8 Iustin Pop
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2046 a8083063 Iustin Pop
2047 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2048 a8083063 Iustin Pop
2049 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2050 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
2051 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2052 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2053 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
2054 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
2055 a8083063 Iustin Pop
2056 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2057 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
2058 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
2059 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
2060 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
2061 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2062 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2063 3c8954ad Iustin Pop
  config.set(constants.INISECT_INS, 'hypervisor', instance.hypervisor)
2064 66f93869 Manuel Franceschini
2065 95268cc3 Iustin Pop
  nic_total = 0
2066 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2067 95268cc3 Iustin Pop
    nic_total += 1
2068 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2069 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
2070 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2071 6801eb5c Iustin Pop
    for param in constants.NICS_PARAMETER_TYPES:
2072 6801eb5c Iustin Pop
      config.set(constants.INISECT_INS, 'nic%d_%s' % (nic_count, param),
2073 6801eb5c Iustin Pop
                 '%s' % nic.nicparams.get(param, None))
2074 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2075 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2076 a8083063 Iustin Pop
2077 726d7d68 Iustin Pop
  disk_total = 0
2078 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2079 19d7f90a Guido Trotter
    if disk:
2080 726d7d68 Iustin Pop
      disk_total += 1
2081 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2082 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
2083 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2084 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
2085 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2086 19d7f90a Guido Trotter
                 ('%d' % disk.size))
2087 a8083063 Iustin Pop
2088 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2089 a8083063 Iustin Pop
2090 3c8954ad Iustin Pop
  # New-style hypervisor/backend parameters
2091 3c8954ad Iustin Pop
2092 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_HYP)
2093 3c8954ad Iustin Pop
  for name, value in instance.hvparams.items():
2094 3c8954ad Iustin Pop
    if name not in constants.HVC_GLOBALS:
2095 3c8954ad Iustin Pop
      config.set(constants.INISECT_HYP, name, str(value))
2096 3c8954ad Iustin Pop
2097 3c8954ad Iustin Pop
  config.add_section(constants.INISECT_BEP)
2098 3c8954ad Iustin Pop
  for name, value in instance.beparams.items():
2099 3c8954ad Iustin Pop
    config.set(constants.INISECT_BEP, name, str(value))
2100 3c8954ad Iustin Pop
2101 c4feafe8 Iustin Pop
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2102 726d7d68 Iustin Pop
                  data=config.Dumps())
2103 56569f4e Michael Hanselmann
  shutil.rmtree(finaldestdir, ignore_errors=True)
2104 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2105 a8083063 Iustin Pop
2106 a8083063 Iustin Pop
2107 a8083063 Iustin Pop
def ExportInfo(dest):
2108 a8083063 Iustin Pop
  """Get export configuration information.
2109 a8083063 Iustin Pop

2110 10c2650b Iustin Pop
  @type dest: str
2111 10c2650b Iustin Pop
  @param dest: directory containing the export
2112 a8083063 Iustin Pop

2113 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2114 10c2650b Iustin Pop
  @return: a serializable config file containing the
2115 10c2650b Iustin Pop
      export info
2116 a8083063 Iustin Pop

2117 a8083063 Iustin Pop
  """
2118 c4feafe8 Iustin Pop
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2119 a8083063 Iustin Pop
2120 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2121 a8083063 Iustin Pop
  config.read(cff)
2122 a8083063 Iustin Pop
2123 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2124 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2125 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2126 a8083063 Iustin Pop
2127 c26a6bd2 Iustin Pop
  return config.Dumps()
2128 a8083063 Iustin Pop
2129 a8083063 Iustin Pop
2130 a8083063 Iustin Pop
def ListExports():
2131 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2132 098c0958 Michael Hanselmann

2133 10c2650b Iustin Pop
  @rtype: list
2134 10c2650b Iustin Pop
  @return: list of the exports
2135 10c2650b Iustin Pop

2136 a8083063 Iustin Pop
  """
2137 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
2138 c26a6bd2 Iustin Pop
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
2139 a8083063 Iustin Pop
  else:
2140 afdc3985 Iustin Pop
    _Fail("No exports directory")
2141 a8083063 Iustin Pop
2142 a8083063 Iustin Pop
2143 a8083063 Iustin Pop
def RemoveExport(export):
2144 a8083063 Iustin Pop
  """Remove an existing export from the node.
2145 a8083063 Iustin Pop

2146 10c2650b Iustin Pop
  @type export: str
2147 10c2650b Iustin Pop
  @param export: the name of the export to remove
2148 c26a6bd2 Iustin Pop
  @rtype: None
2149 a8083063 Iustin Pop

2150 098c0958 Michael Hanselmann
  """
2151 c4feafe8 Iustin Pop
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2152 a8083063 Iustin Pop
2153 35fbcd11 Iustin Pop
  try:
2154 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2155 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2156 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2157 a8083063 Iustin Pop
2158 a8083063 Iustin Pop
2159 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2160 f3e513ad Iustin Pop
  """Rename a list of block devices.
2161 f3e513ad Iustin Pop

2162 10c2650b Iustin Pop
  @type devlist: list of tuples
2163 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2164 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2165 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2166 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2167 10c2650b Iustin Pop
      rename it to
2168 10c2650b Iustin Pop
  @rtype: boolean
2169 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2170 f3e513ad Iustin Pop

2171 f3e513ad Iustin Pop
  """
2172 6b5e3f70 Iustin Pop
  msgs = []
2173 f3e513ad Iustin Pop
  result = True
2174 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2175 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2176 f3e513ad Iustin Pop
    if dev is None:
2177 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2178 f3e513ad Iustin Pop
      result = False
2179 f3e513ad Iustin Pop
      continue
2180 f3e513ad Iustin Pop
    try:
2181 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2182 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2183 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2184 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2185 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2186 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2187 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2188 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2189 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2190 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2191 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2192 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2193 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2194 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2195 f3e513ad Iustin Pop
      result = False
2196 afdc3985 Iustin Pop
  if not result:
2197 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2198 f3e513ad Iustin Pop
2199 f3e513ad Iustin Pop
2200 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2201 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2202 778b75bb Manuel Franceschini

2203 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2204 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2205 778b75bb Manuel Franceschini
  directory are allowed.
2206 778b75bb Manuel Franceschini

2207 b1206984 Iustin Pop
  @type file_storage_dir: str
2208 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2209 d61cbe76 Iustin Pop

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

2212 778b75bb Manuel Franceschini
  """
2213 cb7c0198 Iustin Pop
  if not constants.ENABLE_FILE_STORAGE:
2214 cb7c0198 Iustin Pop
    _Fail("File storage disabled at configure time")
2215 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2216 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2217 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2218 56569f4e Michael Hanselmann
  if (os.path.commonprefix([file_storage_dir, base_file_storage_dir]) !=
2219 778b75bb Manuel Franceschini
      base_file_storage_dir):
2220 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2221 b2b8bcce Iustin Pop
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2222 778b75bb Manuel Franceschini
  return file_storage_dir
2223 778b75bb Manuel Franceschini
2224 778b75bb Manuel Franceschini
2225 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2226 778b75bb Manuel Franceschini
  """Create file storage directory.
2227 778b75bb Manuel Franceschini

2228 b1206984 Iustin Pop
  @type file_storage_dir: str
2229 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2230 778b75bb Manuel Franceschini

2231 b1206984 Iustin Pop
  @rtype: tuple
2232 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2233 b1206984 Iustin Pop
      creation was successful or not
2234 778b75bb Manuel Franceschini

2235 778b75bb Manuel Franceschini
  """
2236 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2237 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2238 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2239 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2240 b2b8bcce Iustin Pop
            file_storage_dir)
2241 778b75bb Manuel Franceschini
  else:
2242 b2b8bcce Iustin Pop
    try:
2243 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2244 b2b8bcce Iustin Pop
    except OSError, err:
2245 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2246 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2247 778b75bb Manuel Franceschini
2248 778b75bb Manuel Franceschini
2249 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2250 778b75bb Manuel Franceschini
  """Remove file storage directory.
2251 778b75bb Manuel Franceschini

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

2254 10c2650b Iustin Pop
  @type file_storage_dir: str
2255 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2256 10c2650b Iustin Pop
  @rtype: tuple (success,)
2257 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2258 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2259 778b75bb Manuel Franceschini

2260 778b75bb Manuel Franceschini
  """
2261 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2262 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2263 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2264 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2265 b2b8bcce Iustin Pop
            file_storage_dir)
2266 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2267 b2b8bcce Iustin Pop
    try:
2268 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2269 b2b8bcce Iustin Pop
    except OSError, err:
2270 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2271 b2b8bcce Iustin Pop
            file_storage_dir, err)
2272 b2b8bcce Iustin Pop
2273 778b75bb Manuel Franceschini
2274 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2275 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2276 778b75bb Manuel Franceschini

2277 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2278 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2279 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2280 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2281 10c2650b Iustin Pop
  @rtype: tuple (success,)
2282 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2283 10c2650b Iustin Pop
      whether the operation was successful
2284 778b75bb Manuel Franceschini

2285 778b75bb Manuel Franceschini
  """
2286 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2287 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2288 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2289 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2290 b2b8bcce Iustin Pop
      try:
2291 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2292 b2b8bcce Iustin Pop
      except OSError, err:
2293 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2294 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2295 778b75bb Manuel Franceschini
    else:
2296 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2297 b2b8bcce Iustin Pop
            old_file_storage_dir)
2298 b2b8bcce Iustin Pop
  else:
2299 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2300 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2301 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2302 778b75bb Manuel Franceschini
2303 778b75bb Manuel Franceschini
2304 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2305 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2306 ca52cdeb Michael Hanselmann

2307 10c2650b Iustin Pop
  @type file_name: str
2308 10c2650b Iustin Pop
  @param file_name: the file name we should check
2309 c8457ce7 Iustin Pop
  @rtype: None
2310 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2311 10c2650b Iustin Pop

2312 ca52cdeb Michael Hanselmann
  """
2313 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2314 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2315 dc31eae3 Michael Hanselmann
2316 dc31eae3 Michael Hanselmann
  if not result:
2317 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2318 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2319 dc31eae3 Michael Hanselmann
2320 dc31eae3 Michael Hanselmann
2321 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2322 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2323 dc31eae3 Michael Hanselmann

2324 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2325 10c2650b Iustin Pop
  checking.
2326 10c2650b Iustin Pop

2327 10c2650b Iustin Pop
  @type file_name: str
2328 10c2650b Iustin Pop
  @param file_name: the job file name
2329 10c2650b Iustin Pop
  @type content: str
2330 10c2650b Iustin Pop
  @param content: the new job contents
2331 10c2650b Iustin Pop
  @rtype: boolean
2332 10c2650b Iustin Pop
  @return: the success of the operation
2333 10c2650b Iustin Pop

2334 dc31eae3 Michael Hanselmann
  """
2335 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2336 ca52cdeb Michael Hanselmann
2337 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2338 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2339 ca52cdeb Michael Hanselmann
2340 ca52cdeb Michael Hanselmann
2341 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2342 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2343 af5ebcb1 Michael Hanselmann

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

2346 10c2650b Iustin Pop
  @type old: str
2347 10c2650b Iustin Pop
  @param old: the old (actual) file name
2348 10c2650b Iustin Pop
  @type new: str
2349 10c2650b Iustin Pop
  @param new: the desired file name
2350 c8457ce7 Iustin Pop
  @rtype: tuple
2351 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2352 10c2650b Iustin Pop

2353 af5ebcb1 Michael Hanselmann
  """
2354 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2355 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2356 af5ebcb1 Michael Hanselmann
2357 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2358 af5ebcb1 Michael Hanselmann
2359 af5ebcb1 Michael Hanselmann
2360 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2361 d61cbe76 Iustin Pop
  """Closes the given block devices.
2362 d61cbe76 Iustin Pop

2363 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2364 10c2650b Iustin Pop
  DRBD).
2365 10c2650b Iustin Pop

2366 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2367 b2e7666a Iustin Pop
      of this instance will be removed
2368 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2369 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2370 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2371 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2372 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2373 10c2650b Iustin Pop
      which will contain the error details in case we
2374 10c2650b Iustin Pop
      failed
2375 d61cbe76 Iustin Pop

2376 d61cbe76 Iustin Pop
  """
2377 d61cbe76 Iustin Pop
  bdevs = []
2378 d61cbe76 Iustin Pop
  for cf in disks:
2379 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2380 d61cbe76 Iustin Pop
    if rd is None:
2381 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2382 d61cbe76 Iustin Pop
    bdevs.append(rd)
2383 d61cbe76 Iustin Pop
2384 d61cbe76 Iustin Pop
  msg = []
2385 d61cbe76 Iustin Pop
  for rd in bdevs:
2386 d61cbe76 Iustin Pop
    try:
2387 d61cbe76 Iustin Pop
      rd.Close()
2388 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2389 d61cbe76 Iustin Pop
      msg.append(str(err))
2390 d61cbe76 Iustin Pop
  if msg:
2391 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2392 d61cbe76 Iustin Pop
  else:
2393 b2e7666a Iustin Pop
    if instance_name:
2394 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2395 d61cbe76 Iustin Pop
2396 d61cbe76 Iustin Pop
2397 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2398 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2399 6217e295 Iustin Pop

2400 6217e295 Iustin Pop
  @type hvname: string
2401 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2402 6217e295 Iustin Pop
  @type hvparams: dict
2403 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2404 c26a6bd2 Iustin Pop
  @rtype: None
2405 6217e295 Iustin Pop

2406 6217e295 Iustin Pop
  """
2407 6217e295 Iustin Pop
  try:
2408 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2409 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2410 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2411 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2412 6217e295 Iustin Pop
2413 6217e295 Iustin Pop
2414 56aa9fd5 Iustin Pop
def DemoteFromMC():
2415 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2416 56aa9fd5 Iustin Pop

2417 56aa9fd5 Iustin Pop
  """
2418 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2419 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2420 56aa9fd5 Iustin Pop
  if master == myself:
2421 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2422 f154a7a3 Michael Hanselmann
2423 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2424 f154a7a3 Michael Hanselmann
  if not result.failed:
2425 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2426 f154a7a3 Michael Hanselmann
2427 56aa9fd5 Iustin Pop
  try:
2428 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2429 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2430 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2431 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2432 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2433 f154a7a3 Michael Hanselmann
2434 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2435 56aa9fd5 Iustin Pop
2436 56aa9fd5 Iustin Pop
2437 f942a838 Michael Hanselmann
def _GetX509Filenames(cryptodir, name):
2438 f942a838 Michael Hanselmann
  """Returns the full paths for the private key and certificate.
2439 f942a838 Michael Hanselmann

2440 f942a838 Michael Hanselmann
  """
2441 f942a838 Michael Hanselmann
  return (utils.PathJoin(cryptodir, name),
2442 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2443 f942a838 Michael Hanselmann
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2444 f942a838 Michael Hanselmann
2445 f942a838 Michael Hanselmann
2446 f942a838 Michael Hanselmann
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2447 f942a838 Michael Hanselmann
  """Creates a new X509 certificate for SSL/TLS.
2448 f942a838 Michael Hanselmann

2449 f942a838 Michael Hanselmann
  @type validity: int
2450 f942a838 Michael Hanselmann
  @param validity: Validity in seconds
2451 f942a838 Michael Hanselmann
  @rtype: tuple; (string, string)
2452 f942a838 Michael Hanselmann
  @return: Certificate name and public part
2453 f942a838 Michael Hanselmann

2454 f942a838 Michael Hanselmann
  """
2455 f942a838 Michael Hanselmann
  (key_pem, cert_pem) = \
2456 f942a838 Michael Hanselmann
    utils.GenerateSelfSignedX509Cert(utils.HostInfo.SysName(),
2457 f942a838 Michael Hanselmann
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2458 f942a838 Michael Hanselmann
2459 f942a838 Michael Hanselmann
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2460 f942a838 Michael Hanselmann
                              prefix="x509-%s-" % utils.TimestampForFilename())
2461 f942a838 Michael Hanselmann
  try:
2462 f942a838 Michael Hanselmann
    name = os.path.basename(cert_dir)
2463 f942a838 Michael Hanselmann
    assert len(name) > 5
2464 f942a838 Michael Hanselmann
2465 f942a838 Michael Hanselmann
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2466 f942a838 Michael Hanselmann
2467 f942a838 Michael Hanselmann
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2468 f942a838 Michael Hanselmann
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2469 f942a838 Michael Hanselmann
2470 f942a838 Michael Hanselmann
    # Never return private key as it shouldn't leave the node
2471 f942a838 Michael Hanselmann
    return (name, cert_pem)
2472 f942a838 Michael Hanselmann
  except Exception:
2473 f942a838 Michael Hanselmann
    shutil.rmtree(cert_dir, ignore_errors=True)
2474 f942a838 Michael Hanselmann
    raise
2475 f942a838 Michael Hanselmann
2476 f942a838 Michael Hanselmann
2477 f942a838 Michael Hanselmann
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2478 f942a838 Michael Hanselmann
  """Removes a X509 certificate.
2479 f942a838 Michael Hanselmann

2480 f942a838 Michael Hanselmann
  @type name: string
2481 f942a838 Michael Hanselmann
  @param name: Certificate name
2482 f942a838 Michael Hanselmann

2483 f942a838 Michael Hanselmann
  """
2484 f942a838 Michael Hanselmann
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2485 f942a838 Michael Hanselmann
2486 f942a838 Michael Hanselmann
  utils.RemoveFile(key_file)
2487 f942a838 Michael Hanselmann
  utils.RemoveFile(cert_file)
2488 f942a838 Michael Hanselmann
2489 f942a838 Michael Hanselmann
  try:
2490 f942a838 Michael Hanselmann
    os.rmdir(cert_dir)
2491 f942a838 Michael Hanselmann
  except EnvironmentError, err:
2492 f942a838 Michael Hanselmann
    _Fail("Cannot remove certificate directory '%s': %s",
2493 f942a838 Michael Hanselmann
          cert_dir, err)
2494 f942a838 Michael Hanselmann
2495 f942a838 Michael Hanselmann
2496 1651d116 Michael Hanselmann
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2497 1651d116 Michael Hanselmann
  """Returns the command for the requested input/output.
2498 1651d116 Michael Hanselmann

2499 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
2500 1651d116 Michael Hanselmann
  @param instance: The instance object
2501 1651d116 Michael Hanselmann
  @param mode: Import/export mode
2502 1651d116 Michael Hanselmann
  @param ieio: Input/output type
2503 1651d116 Michael Hanselmann
  @param ieargs: Input/output arguments
2504 1651d116 Michael Hanselmann

2505 1651d116 Michael Hanselmann
  """
2506 1651d116 Michael Hanselmann
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2507 1651d116 Michael Hanselmann
2508 1651d116 Michael Hanselmann
  env = None
2509 1651d116 Michael Hanselmann
  prefix = None
2510 1651d116 Michael Hanselmann
  suffix = None
2511 2ad5550d Michael Hanselmann
  exp_size = None
2512 1651d116 Michael Hanselmann
2513 1651d116 Michael Hanselmann
  if ieio == constants.IEIO_FILE:
2514 1651d116 Michael Hanselmann
    (filename, ) = ieargs
2515 1651d116 Michael Hanselmann
2516 1651d116 Michael Hanselmann
    if not utils.IsNormAbsPath(filename):
2517 1651d116 Michael Hanselmann
      _Fail("Path '%s' is not normalized or absolute", filename)
2518 1651d116 Michael Hanselmann
2519 1651d116 Michael Hanselmann
    directory = os.path.normpath(os.path.dirname(filename))
2520 1651d116 Michael Hanselmann
2521 1651d116 Michael Hanselmann
    if (os.path.commonprefix([constants.EXPORT_DIR, directory]) !=
2522 1651d116 Michael Hanselmann
        constants.EXPORT_DIR):
2523 1651d116 Michael Hanselmann
      _Fail("File '%s' is not under exports directory '%s'",
2524 1651d116 Michael Hanselmann
            filename, constants.EXPORT_DIR)
2525 1651d116 Michael Hanselmann
2526 1651d116 Michael Hanselmann
    # Create directory
2527 1651d116 Michael Hanselmann
    utils.Makedirs(directory, mode=0750)
2528 1651d116 Michael Hanselmann
2529 1651d116 Michael Hanselmann
    quoted_filename = utils.ShellQuote(filename)
2530 1651d116 Michael Hanselmann
2531 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2532 1651d116 Michael Hanselmann
      suffix = "> %s" % quoted_filename
2533 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2534 1651d116 Michael Hanselmann
      suffix = "< %s" % quoted_filename
2535 1651d116 Michael Hanselmann
2536 2ad5550d Michael Hanselmann
      # Retrieve file size
2537 2ad5550d Michael Hanselmann
      try:
2538 2ad5550d Michael Hanselmann
        st = os.stat(filename)
2539 2ad5550d Michael Hanselmann
      except EnvironmentError, err:
2540 2ad5550d Michael Hanselmann
        logging.error("Can't stat(2) %s: %s", filename, err)
2541 2ad5550d Michael Hanselmann
      else:
2542 2ad5550d Michael Hanselmann
        exp_size = utils.BytesToMebibyte(st.st_size)
2543 2ad5550d Michael Hanselmann
2544 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_RAW_DISK:
2545 1651d116 Michael Hanselmann
    (disk, ) = ieargs
2546 1651d116 Michael Hanselmann
2547 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2548 1651d116 Michael Hanselmann
2549 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2550 1651d116 Michael Hanselmann
      # we set here a smaller block size as, due to transport buffering, more
2551 1651d116 Michael Hanselmann
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
2552 1651d116 Michael Hanselmann
      # is not already there or we pass a wrong path; we use notrunc to no
2553 1651d116 Michael Hanselmann
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
2554 1651d116 Michael Hanselmann
      # much memory; this means that at best, we flush every 64k, which will
2555 1651d116 Michael Hanselmann
      # not be very fast
2556 1651d116 Michael Hanselmann
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
2557 1651d116 Michael Hanselmann
                                    " bs=%s oflag=dsync"),
2558 1651d116 Michael Hanselmann
                                    real_disk.dev_path,
2559 1651d116 Michael Hanselmann
                                    str(64 * 1024))
2560 1651d116 Michael Hanselmann
2561 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2562 1651d116 Michael Hanselmann
      # the block size on the read dd is 1MiB to match our units
2563 1651d116 Michael Hanselmann
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2564 1651d116 Michael Hanselmann
                                   real_disk.dev_path,
2565 1651d116 Michael Hanselmann
                                   str(1024 * 1024), # 1 MB
2566 1651d116 Michael Hanselmann
                                   str(disk.size))
2567 2ad5550d Michael Hanselmann
      exp_size = disk.size
2568 1651d116 Michael Hanselmann
2569 1651d116 Michael Hanselmann
  elif ieio == constants.IEIO_SCRIPT:
2570 1651d116 Michael Hanselmann
    (disk, disk_index, ) = ieargs
2571 1651d116 Michael Hanselmann
2572 1651d116 Michael Hanselmann
    assert isinstance(disk_index, (int, long))
2573 1651d116 Michael Hanselmann
2574 1651d116 Michael Hanselmann
    real_disk = _OpenRealBD(disk)
2575 1651d116 Michael Hanselmann
2576 1651d116 Michael Hanselmann
    inst_os = OSFromDisk(instance.os)
2577 1651d116 Michael Hanselmann
    env = OSEnvironment(instance, inst_os)
2578 1651d116 Michael Hanselmann
2579 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2580 1651d116 Michael Hanselmann
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
2581 1651d116 Michael Hanselmann
      env["IMPORT_INDEX"] = str(disk_index)
2582 1651d116 Michael Hanselmann
      script = inst_os.import_script
2583 1651d116 Michael Hanselmann
2584 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2585 1651d116 Michael Hanselmann
      env["EXPORT_DEVICE"] = real_disk.dev_path
2586 1651d116 Michael Hanselmann
      env["EXPORT_INDEX"] = str(disk_index)
2587 1651d116 Michael Hanselmann
      script = inst_os.export_script
2588 1651d116 Michael Hanselmann
2589 1651d116 Michael Hanselmann
    # TODO: Pass special environment only to script
2590 1651d116 Michael Hanselmann
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
2591 1651d116 Michael Hanselmann
2592 1651d116 Michael Hanselmann
    if mode == constants.IEM_IMPORT:
2593 1651d116 Michael Hanselmann
      suffix = "| %s" % script_cmd
2594 1651d116 Michael Hanselmann
2595 1651d116 Michael Hanselmann
    elif mode == constants.IEM_EXPORT:
2596 1651d116 Michael Hanselmann
      prefix = "%s |" % script_cmd
2597 1651d116 Michael Hanselmann
2598 2ad5550d Michael Hanselmann
    # Let script predict size
2599 2ad5550d Michael Hanselmann
    exp_size = constants.IE_CUSTOM_SIZE
2600 2ad5550d Michael Hanselmann
2601 1651d116 Michael Hanselmann
  else:
2602 1651d116 Michael Hanselmann
    _Fail("Invalid %s I/O mode %r", mode, ieio)
2603 1651d116 Michael Hanselmann
2604 2ad5550d Michael Hanselmann
  return (env, prefix, suffix, exp_size)
2605 1651d116 Michael Hanselmann
2606 1651d116 Michael Hanselmann
2607 1651d116 Michael Hanselmann
def _CreateImportExportStatusDir(prefix):
2608 1651d116 Michael Hanselmann
  """Creates status directory for import/export.
2609 1651d116 Michael Hanselmann

2610 1651d116 Michael Hanselmann
  """
2611 1651d116 Michael Hanselmann
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
2612 1651d116 Michael Hanselmann
                          prefix=("%s-%s-" %
2613 1651d116 Michael Hanselmann
                                  (prefix, utils.TimestampForFilename())))
2614 1651d116 Michael Hanselmann
2615 1651d116 Michael Hanselmann
2616 eb630f50 Michael Hanselmann
def StartImportExportDaemon(mode, opts, host, port, instance, ieio, ieioargs):
2617 1651d116 Michael Hanselmann
  """Starts an import or export daemon.
2618 1651d116 Michael Hanselmann

2619 1651d116 Michael Hanselmann
  @param mode: Import/output mode
2620 eb630f50 Michael Hanselmann
  @type opts: L{objects.ImportExportOptions}
2621 eb630f50 Michael Hanselmann
  @param opts: Daemon options
2622 1651d116 Michael Hanselmann
  @type host: string
2623 1651d116 Michael Hanselmann
  @param host: Remote host for export (None for import)
2624 1651d116 Michael Hanselmann
  @type port: int
2625 1651d116 Michael Hanselmann
  @param port: Remote port for export (None for import)
2626 1651d116 Michael Hanselmann
  @type instance: L{objects.Instance}
2627 1651d116 Michael Hanselmann
  @param instance: Instance object
2628 1651d116 Michael Hanselmann
  @param ieio: Input/output type
2629 1651d116 Michael Hanselmann
  @param ieioargs: Input/output arguments
2630 1651d116 Michael Hanselmann

2631 1651d116 Michael Hanselmann
  """
2632 1651d116 Michael Hanselmann
  if mode == constants.IEM_IMPORT:
2633 1651d116 Michael Hanselmann
    prefix = "import"
2634 1651d116 Michael Hanselmann
2635 1651d116 Michael Hanselmann
    if not (host is None and port is None):
2636 1651d116 Michael Hanselmann
      _Fail("Can not specify host or port on import")
2637 1651d116 Michael Hanselmann
2638 1651d116 Michael Hanselmann
  elif mode == constants.IEM_EXPORT:
2639 1651d116 Michael Hanselmann
    prefix = "export"
2640 1651d116 Michael Hanselmann
2641 1651d116 Michael Hanselmann
    if host is None or port is None:
2642 1651d116 Michael Hanselmann
      _Fail("Host and port must be specified for an export")
2643 1651d116 Michael Hanselmann
2644 1651d116 Michael Hanselmann
  else:
2645 1651d116 Michael Hanselmann
    _Fail("Invalid mode %r", mode)
2646 1651d116 Michael Hanselmann
2647 eb630f50 Michael Hanselmann
  if (opts.key_name is None) ^ (opts.ca_pem is None):
2648 1651d116 Michael Hanselmann
    _Fail("Cluster certificate can only be used for both key and CA")
2649 1651d116 Michael Hanselmann
2650 2ad5550d Michael Hanselmann
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
2651 1651d116 Michael Hanselmann
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
2652 1651d116 Michael Hanselmann
2653 eb630f50 Michael Hanselmann
  if opts.key_name is None:
2654 1651d116 Michael Hanselmann
    # Use server.pem
2655 1651d116 Michael Hanselmann
    key_path = constants.NODED_CERT_FILE
2656 1651d116 Michael Hanselmann
    cert_path = constants.NODED_CERT_FILE
2657 eb630f50 Michael Hanselmann
    assert opts.ca_pem is None
2658 1651d116 Michael Hanselmann
  else:
2659 1651d116 Michael Hanselmann
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
2660 eb630f50 Michael Hanselmann
                                                 opts.key_name)
2661 eb630f50 Michael Hanselmann
    assert opts.ca_pem is not None
2662 1651d116 Michael Hanselmann
2663 63bcea2a Michael Hanselmann
  for i in [key_path, cert_path]:
2664 dcaabc4f Michael Hanselmann
    if not os.path.exists(i):
2665 63bcea2a Michael Hanselmann
      _Fail("File '%s' does not exist" % i)
2666 63bcea2a Michael Hanselmann
2667 1651d116 Michael Hanselmann
  status_dir = _CreateImportExportStatusDir(prefix)
2668 1651d116 Michael Hanselmann
  try:
2669 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
2670 1651d116 Michael Hanselmann
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
2671 63bcea2a Michael Hanselmann
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
2672 1651d116 Michael Hanselmann
2673 eb630f50 Michael Hanselmann
    if opts.ca_pem is None:
2674 1651d116 Michael Hanselmann
      # Use server.pem
2675 63bcea2a Michael Hanselmann
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
2676 eb630f50 Michael Hanselmann
    else:
2677 eb630f50 Michael Hanselmann
      ca = opts.ca_pem
2678 63bcea2a Michael Hanselmann
2679 eb630f50 Michael Hanselmann
    # Write CA file
2680 63bcea2a Michael Hanselmann
    utils.WriteFile(ca_file, data=ca, mode=0400)
2681 1651d116 Michael Hanselmann
2682 1651d116 Michael Hanselmann
    cmd = [
2683 1651d116 Michael Hanselmann
      constants.IMPORT_EXPORT_DAEMON,
2684 1651d116 Michael Hanselmann
      status_file, mode,
2685 1651d116 Michael Hanselmann
      "--key=%s" % key_path,
2686 1651d116 Michael Hanselmann
      "--cert=%s" % cert_path,
2687 63bcea2a Michael Hanselmann
      "--ca=%s" % ca_file,
2688 1651d116 Michael Hanselmann
      ]
2689 1651d116 Michael Hanselmann
2690 1651d116 Michael Hanselmann
    if host:
2691 1651d116 Michael Hanselmann
      cmd.append("--host=%s" % host)
2692 1651d116 Michael Hanselmann
2693 1651d116 Michael Hanselmann
    if port:
2694 1651d116 Michael Hanselmann
      cmd.append("--port=%s" % port)
2695 1651d116 Michael Hanselmann
2696 a5310c2a Michael Hanselmann
    if opts.compress:
2697 a5310c2a Michael Hanselmann
      cmd.append("--compress=%s" % opts.compress)
2698 a5310c2a Michael Hanselmann
2699 2ad5550d Michael Hanselmann
    if exp_size is not None:
2700 2ad5550d Michael Hanselmann
      cmd.append("--expected-size=%s" % exp_size)
2701 2ad5550d Michael Hanselmann
2702 1651d116 Michael Hanselmann
    if cmd_prefix:
2703 1651d116 Michael Hanselmann
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
2704 1651d116 Michael Hanselmann
2705 1651d116 Michael Hanselmann
    if cmd_suffix:
2706 1651d116 Michael Hanselmann
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
2707 1651d116 Michael Hanselmann
2708 1651d116 Michael Hanselmann
    logfile = _InstanceLogName(prefix, instance.os, instance.name)
2709 1651d116 Michael Hanselmann
2710 1651d116 Michael Hanselmann
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
2711 1651d116 Michael Hanselmann
    # support for receiving a file descriptor for output
2712 1651d116 Michael Hanselmann
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
2713 1651d116 Michael Hanselmann
                      output=logfile)
2714 1651d116 Michael Hanselmann
2715 1651d116 Michael Hanselmann
    # The import/export name is simply the status directory name
2716 1651d116 Michael Hanselmann
    return os.path.basename(status_dir)
2717 1651d116 Michael Hanselmann
2718 1651d116 Michael Hanselmann
  except Exception:
2719 1651d116 Michael Hanselmann
    shutil.rmtree(status_dir, ignore_errors=True)
2720 1651d116 Michael Hanselmann
    raise
2721 1651d116 Michael Hanselmann
2722 1651d116 Michael Hanselmann
2723 1651d116 Michael Hanselmann
def GetImportExportStatus(names):
2724 1651d116 Michael Hanselmann
  """Returns import/export daemon status.
2725 1651d116 Michael Hanselmann

2726 1651d116 Michael Hanselmann
  @type names: sequence
2727 1651d116 Michael Hanselmann
  @param names: List of names
2728 1651d116 Michael Hanselmann
  @rtype: List of dicts
2729 1651d116 Michael Hanselmann
  @return: Returns a list of the state of each named import/export or None if a
2730 1651d116 Michael Hanselmann
           status couldn't be read
2731 1651d116 Michael Hanselmann

2732 1651d116 Michael Hanselmann
  """
2733 1651d116 Michael Hanselmann
  result = []
2734 1651d116 Michael Hanselmann
2735 1651d116 Michael Hanselmann
  for name in names:
2736 1651d116 Michael Hanselmann
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
2737 1651d116 Michael Hanselmann
                                 _IES_STATUS_FILE)
2738 1651d116 Michael Hanselmann
2739 1651d116 Michael Hanselmann
    try:
2740 1651d116 Michael Hanselmann
      data = utils.ReadFile(status_file)
2741 1651d116 Michael Hanselmann
    except EnvironmentError, err:
2742 1651d116 Michael Hanselmann
      if err.errno != errno.ENOENT:
2743 1651d116 Michael Hanselmann
        raise
2744 1651d116 Michael Hanselmann
      data = None
2745 1651d116 Michael Hanselmann
2746 1651d116 Michael Hanselmann
    if not data:
2747 1651d116 Michael Hanselmann
      result.append(None)
2748 1651d116 Michael Hanselmann
      continue
2749 1651d116 Michael Hanselmann
2750 1651d116 Michael Hanselmann
    result.append(serializer.LoadJson(data))
2751 1651d116 Michael Hanselmann
2752 1651d116 Michael Hanselmann
  return result
2753 1651d116 Michael Hanselmann
2754 1651d116 Michael Hanselmann
2755 f81c4737 Michael Hanselmann
def AbortImportExport(name):
2756 f81c4737 Michael Hanselmann
  """Sends SIGTERM to a running import/export daemon.
2757 f81c4737 Michael Hanselmann

2758 f81c4737 Michael Hanselmann
  """
2759 f81c4737 Michael Hanselmann
  logging.info("Abort import/export %s", name)
2760 f81c4737 Michael Hanselmann
2761 f81c4737 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
2762 f81c4737 Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
2763 f81c4737 Michael Hanselmann
2764 f81c4737 Michael Hanselmann
  if pid:
2765 f81c4737 Michael Hanselmann
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
2766 f81c4737 Michael Hanselmann
                 name, pid)
2767 f81c4737 Michael Hanselmann
    os.kill(pid, signal.SIGTERM)
2768 f81c4737 Michael Hanselmann
2769 f81c4737 Michael Hanselmann
2770 1651d116 Michael Hanselmann
def CleanupImportExport(name):
2771 1651d116 Michael Hanselmann
  """Cleanup after an import or export.
2772 1651d116 Michael Hanselmann

2773 1651d116 Michael Hanselmann
  If the import/export daemon is still running it's killed. Afterwards the
2774 1651d116 Michael Hanselmann
  whole status directory is removed.
2775 1651d116 Michael Hanselmann

2776 1651d116 Michael Hanselmann
  """
2777 1651d116 Michael Hanselmann
  logging.info("Finalizing import/export %s", name)
2778 1651d116 Michael Hanselmann
2779 1651d116 Michael Hanselmann
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
2780 1651d116 Michael Hanselmann
2781 debed9ae Michael Hanselmann
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
2782 1651d116 Michael Hanselmann
2783 1651d116 Michael Hanselmann
  if pid:
2784 1651d116 Michael Hanselmann
    logging.info("Import/export %s is still running with PID %s",
2785 1651d116 Michael Hanselmann
                 name, pid)
2786 1651d116 Michael Hanselmann
    utils.KillProcess(pid, waitpid=False)
2787 1651d116 Michael Hanselmann
2788 1651d116 Michael Hanselmann
  shutil.rmtree(status_dir, ignore_errors=True)
2789 1651d116 Michael Hanselmann
2790 1651d116 Michael Hanselmann
2791 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2792 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2793 6b93ec9d Iustin Pop

2794 6b93ec9d Iustin Pop
  """
2795 6b93ec9d Iustin Pop
  # set the correct physical ID
2796 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2797 6b93ec9d Iustin Pop
  for cf in disks:
2798 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2799 6b93ec9d Iustin Pop
2800 6b93ec9d Iustin Pop
  bdevs = []
2801 6b93ec9d Iustin Pop
2802 6b93ec9d Iustin Pop
  for cf in disks:
2803 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2804 6b93ec9d Iustin Pop
    if rd is None:
2805 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
2806 6b93ec9d Iustin Pop
    bdevs.append(rd)
2807 5a533f8a Iustin Pop
  return bdevs
2808 6b93ec9d Iustin Pop
2809 6b93ec9d Iustin Pop
2810 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2811 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2812 6b93ec9d Iustin Pop

2813 6b93ec9d Iustin Pop
  """
2814 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2815 6b93ec9d Iustin Pop
2816 6b93ec9d Iustin Pop
  # disconnect disks
2817 6b93ec9d Iustin Pop
  for rd in bdevs:
2818 6b93ec9d Iustin Pop
    try:
2819 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2820 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2821 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
2822 2cc6781a Iustin Pop
            err, exc=True)
2823 6b93ec9d Iustin Pop
2824 6b93ec9d Iustin Pop
2825 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2826 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2827 6b93ec9d Iustin Pop

2828 6b93ec9d Iustin Pop
  """
2829 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2830 6b93ec9d Iustin Pop
2831 6b93ec9d Iustin Pop
  if multimaster:
2832 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2833 6b93ec9d Iustin Pop
      try:
2834 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2835 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2836 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
2837 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2838 6b93ec9d Iustin Pop
  # needed primary mode
2839 6b93ec9d Iustin Pop
  for rd in bdevs:
2840 6b93ec9d Iustin Pop
    try:
2841 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2842 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2843 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
2844 3c0cdc83 Michael Hanselmann
2845 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2846 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2847 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2848 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2849 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2850 3c0cdc83 Michael Hanselmann
2851 3c0cdc83 Michael Hanselmann
  def _Attach():
2852 6b93ec9d Iustin Pop
    all_connected = True
2853 3c0cdc83 Michael Hanselmann
2854 6b93ec9d Iustin Pop
    for rd in bdevs:
2855 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2856 3c0cdc83 Michael Hanselmann
2857 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
2858 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
2859 3c0cdc83 Michael Hanselmann
2860 6b93ec9d Iustin Pop
      if stats.is_standalone:
2861 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2862 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2863 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2864 6b93ec9d Iustin Pop
        try:
2865 c738375b Iustin Pop
          rd.AttachNet(multimaster)
2866 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2867 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
2868 3c0cdc83 Michael Hanselmann
2869 3c0cdc83 Michael Hanselmann
    if not all_connected:
2870 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
2871 3c0cdc83 Michael Hanselmann
2872 3c0cdc83 Michael Hanselmann
  try:
2873 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
2874 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
2875 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
2876 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
2877 3c0cdc83 Michael Hanselmann
2878 6b93ec9d Iustin Pop
  if multimaster:
2879 6b93ec9d Iustin Pop
    # change to primary mode
2880 6b93ec9d Iustin Pop
    for rd in bdevs:
2881 d3da87b8 Iustin Pop
      try:
2882 d3da87b8 Iustin Pop
        rd.Open()
2883 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
2884 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
2885 6b93ec9d Iustin Pop
2886 6b93ec9d Iustin Pop
2887 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2888 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2889 6b93ec9d Iustin Pop

2890 6b93ec9d Iustin Pop
  """
2891 db8667b7 Iustin Pop
  def _helper(rd):
2892 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
2893 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2894 db8667b7 Iustin Pop
      raise utils.RetryAgain()
2895 db8667b7 Iustin Pop
    return stats
2896 db8667b7 Iustin Pop
2897 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2898 6b93ec9d Iustin Pop
2899 6b93ec9d Iustin Pop
  min_resync = 100
2900 6b93ec9d Iustin Pop
  alldone = True
2901 6b93ec9d Iustin Pop
  for rd in bdevs:
2902 db8667b7 Iustin Pop
    try:
2903 db8667b7 Iustin Pop
      # poll each second for 15 seconds
2904 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
2905 db8667b7 Iustin Pop
    except utils.RetryTimeout:
2906 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
2907 db8667b7 Iustin Pop
      # last check
2908 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2909 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2910 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2911 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2912 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2913 afdc3985 Iustin Pop
2914 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
2915 6b93ec9d Iustin Pop
2916 6b93ec9d Iustin Pop
2917 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
2918 f5118ade Iustin Pop
  """Hard-powercycle the node.
2919 f5118ade Iustin Pop

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

2923 f5118ade Iustin Pop
  """
2924 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2925 f5118ade Iustin Pop
  try:
2926 f5118ade Iustin Pop
    pid = os.fork()
2927 29921401 Iustin Pop
  except OSError:
2928 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
2929 f5118ade Iustin Pop
    pid = 0
2930 f5118ade Iustin Pop
  if pid > 0:
2931 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
2932 1af6ac0f Luca Bigliardi
  # ensure the child is running on ram
2933 1af6ac0f Luca Bigliardi
  try:
2934 1af6ac0f Luca Bigliardi
    utils.Mlockall()
2935 20601361 Luca Bigliardi
  except Exception: # pylint: disable-msg=W0703
2936 1af6ac0f Luca Bigliardi
    pass
2937 f5118ade Iustin Pop
  time.sleep(5)
2938 f5118ade Iustin Pop
  hyper.PowercycleNode()
2939 f5118ade Iustin Pop
2940 f5118ade Iustin Pop
2941 a8083063 Iustin Pop
class HooksRunner(object):
2942 a8083063 Iustin Pop
  """Hook runner.
2943 a8083063 Iustin Pop

2944 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2945 10c2650b Iustin Pop
  on the master side.
2946 a8083063 Iustin Pop

2947 a8083063 Iustin Pop
  """
2948 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2949 a8083063 Iustin Pop
    """Constructor for hooks runner.
2950 a8083063 Iustin Pop

2951 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2952 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2953 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2954 a8083063 Iustin Pop

2955 a8083063 Iustin Pop
    """
2956 a8083063 Iustin Pop
    if hooks_base_dir is None:
2957 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2958 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
2959 fe267188 Iustin Pop
    # constant
2960 fe267188 Iustin Pop
    self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
2961 a8083063 Iustin Pop
2962 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2963 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2964 a8083063 Iustin Pop

2965 10c2650b Iustin Pop
    @type hpath: str
2966 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2967 10c2650b Iustin Pop
        holds the scripts
2968 10c2650b Iustin Pop
    @type phase: str
2969 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2970 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2971 10c2650b Iustin Pop
    @type env: dict
2972 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2973 10c2650b Iustin Pop
    @rtype: list
2974 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2975 10c2650b Iustin Pop
      - script path
2976 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2977 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2978 10c2650b Iustin Pop
      - output of the script
2979 10c2650b Iustin Pop

2980 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2981 10c2650b Iustin Pop
        parameters
2982 a8083063 Iustin Pop

2983 a8083063 Iustin Pop
    """
2984 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2985 a8083063 Iustin Pop
      suffix = "pre"
2986 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2987 a8083063 Iustin Pop
      suffix = "post"
2988 a8083063 Iustin Pop
    else:
2989 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
2990 3fb4f740 Iustin Pop
2991 a8083063 Iustin Pop
2992 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2993 0411c011 Iustin Pop
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
2994 6bb65e3a Guido Trotter
2995 6bb65e3a Guido Trotter
    results = []
2996 a9b7e346 Iustin Pop
2997 a9b7e346 Iustin Pop
    if not os.path.isdir(dir_name):
2998 a9b7e346 Iustin Pop
      # for non-existing/non-dirs, we simply exit instead of logging a
2999 a9b7e346 Iustin Pop
      # warning at every operation
3000 a9b7e346 Iustin Pop
      return results
3001 a9b7e346 Iustin Pop
3002 a9b7e346 Iustin Pop
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3003 a9b7e346 Iustin Pop
3004 6bb65e3a Guido Trotter
    for (relname, relstatus, runresult)  in runparts_results:
3005 6bb65e3a Guido Trotter
      if relstatus == constants.RUNPARTS_SKIP:
3006 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
3007 a8083063 Iustin Pop
        output = ""
3008 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_ERR:
3009 6bb65e3a Guido Trotter
        rrval = constants.HKR_FAIL
3010 6bb65e3a Guido Trotter
        output = "Hook script execution error: %s" % runresult
3011 6bb65e3a Guido Trotter
      elif relstatus == constants.RUNPARTS_RUN:
3012 6bb65e3a Guido Trotter
        if runresult.failed:
3013 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
3014 a8083063 Iustin Pop
        else:
3015 6bb65e3a Guido Trotter
          rrval = constants.HKR_SUCCESS
3016 6bb65e3a Guido Trotter
        output = utils.SafeEncode(runresult.output.strip())
3017 6bb65e3a Guido Trotter
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3018 6bb65e3a Guido Trotter
3019 6bb65e3a Guido Trotter
    return results
3020 3f78eef2 Iustin Pop
3021 3f78eef2 Iustin Pop
3022 8d528b7c Iustin Pop
class IAllocatorRunner(object):
3023 8d528b7c Iustin Pop
  """IAllocator runner.
3024 8d528b7c Iustin Pop

3025 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
3026 8d528b7c Iustin Pop
  the master side.
3027 8d528b7c Iustin Pop

3028 8d528b7c Iustin Pop
  """
3029 7e950d31 Iustin Pop
  @staticmethod
3030 7e950d31 Iustin Pop
  def Run(name, idata):
3031 8d528b7c Iustin Pop
    """Run an iallocator script.
3032 8d528b7c Iustin Pop

3033 10c2650b Iustin Pop
    @type name: str
3034 10c2650b Iustin Pop
    @param name: the iallocator script name
3035 10c2650b Iustin Pop
    @type idata: str
3036 10c2650b Iustin Pop
    @param idata: the allocator input data
3037 10c2650b Iustin Pop

3038 10c2650b Iustin Pop
    @rtype: tuple
3039 87f5c298 Iustin Pop
    @return: two element tuple of:
3040 87f5c298 Iustin Pop
       - status
3041 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
3042 8d528b7c Iustin Pop

3043 8d528b7c Iustin Pop
    """
3044 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3045 8d528b7c Iustin Pop
                                  os.path.isfile)
3046 8d528b7c Iustin Pop
    if alloc_script is None:
3047 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
3048 8d528b7c Iustin Pop
3049 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3050 8d528b7c Iustin Pop
    try:
3051 8d528b7c Iustin Pop
      os.write(fd, idata)
3052 8d528b7c Iustin Pop
      os.close(fd)
3053 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
3054 8d528b7c Iustin Pop
      if result.failed:
3055 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3056 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
3057 8d528b7c Iustin Pop
    finally:
3058 8d528b7c Iustin Pop
      os.unlink(fin_name)
3059 8d528b7c Iustin Pop
3060 c26a6bd2 Iustin Pop
    return result.stdout
3061 8d528b7c Iustin Pop
3062 8d528b7c Iustin Pop
3063 3f78eef2 Iustin Pop
class DevCacheManager(object):
3064 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
3065 3f78eef2 Iustin Pop

3066 3f78eef2 Iustin Pop
  """
3067 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
3068 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3069 3f78eef2 Iustin Pop
3070 3f78eef2 Iustin Pop
  @classmethod
3071 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
3072 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
3073 3f78eef2 Iustin Pop

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

3077 10c2650b Iustin Pop
    @type dev_path: str
3078 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
3079 10c2650b Iustin Pop
    @rtype: str
3080 10c2650b Iustin Pop
    @return: the converted path name
3081 3f78eef2 Iustin Pop

3082 3f78eef2 Iustin Pop
    """
3083 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
3084 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3085 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
3086 0411c011 Iustin Pop
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3087 3f78eef2 Iustin Pop
    return fpath
3088 3f78eef2 Iustin Pop
3089 3f78eef2 Iustin Pop
  @classmethod
3090 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3091 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
3092 3f78eef2 Iustin Pop

3093 10c2650b Iustin Pop
    @type dev_path: str
3094 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3095 10c2650b Iustin Pop
    @type owner: str
3096 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
3097 10c2650b Iustin Pop
    @type on_primary: bool
3098 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
3099 10c2650b Iustin Pop
        node nor not
3100 10c2650b Iustin Pop
    @type iv_name: str
3101 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
3102 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
3103 10c2650b Iustin Pop

3104 10c2650b Iustin Pop
    @rtype: None
3105 10c2650b Iustin Pop

3106 3f78eef2 Iustin Pop
    """
3107 cf5a8306 Iustin Pop
    if dev_path is None:
3108 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3109 cf5a8306 Iustin Pop
      return
3110 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3111 3f78eef2 Iustin Pop
    if on_primary:
3112 3f78eef2 Iustin Pop
      state = "primary"
3113 3f78eef2 Iustin Pop
    else:
3114 3f78eef2 Iustin Pop
      state = "secondary"
3115 3f78eef2 Iustin Pop
    if iv_name is None:
3116 3f78eef2 Iustin Pop
      iv_name = "not_visible"
3117 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3118 3f78eef2 Iustin Pop
    try:
3119 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
3120 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3121 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3122 3f78eef2 Iustin Pop
3123 3f78eef2 Iustin Pop
  @classmethod
3124 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
3125 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
3126 3f78eef2 Iustin Pop

3127 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
3128 10c2650b Iustin Pop
    path name and logging.
3129 10c2650b Iustin Pop

3130 10c2650b Iustin Pop
    @type dev_path: str
3131 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
3132 10c2650b Iustin Pop

3133 10c2650b Iustin Pop
    @rtype: None
3134 10c2650b Iustin Pop

3135 3f78eef2 Iustin Pop
    """
3136 cf5a8306 Iustin Pop
    if dev_path is None:
3137 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3138 cf5a8306 Iustin Pop
      return
3139 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
3140 3f78eef2 Iustin Pop
    try:
3141 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
3142 3f78eef2 Iustin Pop
    except EnvironmentError, err:
3143 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)