Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ f154a7a3

History | View | Annotate | Download (86.3 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 360b0dc2 Iustin Pop

27 360b0dc2 Iustin Pop
"""
28 a8083063 Iustin Pop
29 a8083063 Iustin Pop
30 a8083063 Iustin Pop
import os
31 a8083063 Iustin Pop
import os.path
32 a8083063 Iustin Pop
import shutil
33 a8083063 Iustin Pop
import time
34 a8083063 Iustin Pop
import stat
35 a8083063 Iustin Pop
import errno
36 a8083063 Iustin Pop
import re
37 a8083063 Iustin Pop
import subprocess
38 b544cfe0 Iustin Pop
import random
39 18682bca Iustin Pop
import logging
40 3b9e6a30 Iustin Pop
import tempfile
41 12bce260 Michael Hanselmann
import zlib
42 12bce260 Michael Hanselmann
import base64
43 a8083063 Iustin Pop
44 a8083063 Iustin Pop
from ganeti import errors
45 a8083063 Iustin Pop
from ganeti import utils
46 a8083063 Iustin Pop
from ganeti import ssh
47 a8083063 Iustin Pop
from ganeti import hypervisor
48 a8083063 Iustin Pop
from ganeti import constants
49 a8083063 Iustin Pop
from ganeti import bdev
50 a8083063 Iustin Pop
from ganeti import objects
51 880478f8 Iustin Pop
from ganeti import ssconf
52 a8083063 Iustin Pop
53 a8083063 Iustin Pop
54 13998ef2 Michael Hanselmann
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
55 13998ef2 Michael Hanselmann
56 13998ef2 Michael Hanselmann
57 2cc6781a Iustin Pop
class RPCFail(Exception):
58 2cc6781a Iustin Pop
  """Class denoting RPC failure.
59 2cc6781a Iustin Pop

60 2cc6781a Iustin Pop
  Its argument is the error message.
61 2cc6781a Iustin Pop

62 2cc6781a Iustin Pop
  """
63 2cc6781a Iustin Pop
64 13998ef2 Michael Hanselmann
65 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
66 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
67 2cc6781a Iustin Pop

68 2cc6781a Iustin Pop
  This exception is then handled specially in the ganeti daemon and
69 2cc6781a Iustin Pop
  turned into a 'failed' return type. As such, this function is a
70 2cc6781a Iustin Pop
  useful shortcut for logging the error and returning it to the master
71 2cc6781a Iustin Pop
  daemon.
72 2cc6781a Iustin Pop

73 2cc6781a Iustin Pop
  @type msg: string
74 2cc6781a Iustin Pop
  @param msg: the text of the exception
75 2cc6781a Iustin Pop
  @raise RPCFail
76 2cc6781a Iustin Pop

77 2cc6781a Iustin Pop
  """
78 2cc6781a Iustin Pop
  if args:
79 2cc6781a Iustin Pop
    msg = msg % args
80 afdc3985 Iustin Pop
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
81 afdc3985 Iustin Pop
    if "exc" in kwargs and kwargs["exc"]:
82 afdc3985 Iustin Pop
      logging.exception(msg)
83 afdc3985 Iustin Pop
    else:
84 afdc3985 Iustin Pop
      logging.error(msg)
85 2cc6781a Iustin Pop
  raise RPCFail(msg)
86 2cc6781a Iustin Pop
87 2cc6781a Iustin Pop
88 c657dcc9 Michael Hanselmann
def _GetConfig():
89 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
90 10c2650b Iustin Pop

91 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
92 93384844 Iustin Pop
  @return: a SimpleStore instance
93 10c2650b Iustin Pop

94 10c2650b Iustin Pop
  """
95 93384844 Iustin Pop
  return ssconf.SimpleStore()
96 c657dcc9 Michael Hanselmann
97 c657dcc9 Michael Hanselmann
98 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
99 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
100 10c2650b Iustin Pop

101 10c2650b Iustin Pop
  @type cluster_name: str
102 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
103 10c2650b Iustin Pop
      by the SshRunner constructor
104 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
105 10c2650b Iustin Pop
  @return: an SshRunner instance
106 10c2650b Iustin Pop

107 10c2650b Iustin Pop
  """
108 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
109 c92b310a Michael Hanselmann
110 c92b310a Michael Hanselmann
111 12bce260 Michael Hanselmann
def _Decompress(data):
112 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
113 12bce260 Michael Hanselmann

114 12bce260 Michael Hanselmann
  @type data: list or tuple
115 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
116 12bce260 Michael Hanselmann
  @rtype: str
117 12bce260 Michael Hanselmann
  @return: Decompressed data
118 12bce260 Michael Hanselmann

119 12bce260 Michael Hanselmann
  """
120 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
121 12bce260 Michael Hanselmann
  assert len(data) == 2
122 12bce260 Michael Hanselmann
  (encoding, content) = data
123 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
124 12bce260 Michael Hanselmann
    return content
125 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
126 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
127 12bce260 Michael Hanselmann
  else:
128 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
129 12bce260 Michael Hanselmann
130 12bce260 Michael Hanselmann
131 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
132 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
133 76ab5558 Michael Hanselmann

134 10c2650b Iustin Pop
  @type path: str
135 10c2650b Iustin Pop
  @param path: the directory to clean
136 76ab5558 Michael Hanselmann
  @type exclude: list
137 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
138 10c2650b Iustin Pop
      to the empty list
139 76ab5558 Michael Hanselmann

140 76ab5558 Michael Hanselmann
  """
141 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
142 3956cee1 Michael Hanselmann
    return
143 3bc6be5c Iustin Pop
  if exclude is None:
144 3bc6be5c Iustin Pop
    exclude = []
145 3bc6be5c Iustin Pop
  else:
146 3bc6be5c Iustin Pop
    # Normalize excluded paths
147 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
148 76ab5558 Michael Hanselmann
149 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
150 76ab5558 Michael Hanselmann
    full_name = os.path.normpath(os.path.join(path, rel_name))
151 76ab5558 Michael Hanselmann
    if full_name in exclude:
152 76ab5558 Michael Hanselmann
      continue
153 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
154 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
155 3956cee1 Michael Hanselmann
156 3956cee1 Michael Hanselmann
157 360b0dc2 Iustin Pop
def _BuildUploadFileList():
158 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
159 360b0dc2 Iustin Pop

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

162 360b0dc2 Iustin Pop
  """
163 b397a7d2 Iustin Pop
  allowed_files = set([
164 b397a7d2 Iustin Pop
    constants.CLUSTER_CONF_FILE,
165 b397a7d2 Iustin Pop
    constants.ETC_HOSTS,
166 b397a7d2 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
167 b397a7d2 Iustin Pop
    constants.VNC_PASSWORD_FILE,
168 b397a7d2 Iustin Pop
    constants.RAPI_CERT_FILE,
169 b397a7d2 Iustin Pop
    constants.RAPI_USERS_FILE,
170 4a34c5cf Guido Trotter
    constants.HMAC_CLUSTER_KEY,
171 b397a7d2 Iustin Pop
    ])
172 b397a7d2 Iustin Pop
173 b397a7d2 Iustin Pop
  for hv_name in constants.HYPER_TYPES:
174 e5a45a16 Iustin Pop
    hv_class = hypervisor.GetHypervisorClass(hv_name)
175 b397a7d2 Iustin Pop
    allowed_files.update(hv_class.GetAncillaryFiles())
176 b397a7d2 Iustin Pop
177 b397a7d2 Iustin Pop
  return frozenset(allowed_files)
178 360b0dc2 Iustin Pop
179 360b0dc2 Iustin Pop
180 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
181 360b0dc2 Iustin Pop
182 360b0dc2 Iustin Pop
183 1bc59f76 Michael Hanselmann
def JobQueuePurge():
184 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
185 10c2650b Iustin Pop

186 c8457ce7 Iustin Pop
  @rtype: tuple
187 c8457ce7 Iustin Pop
  @return: True, None
188 24fc781f Michael Hanselmann

189 24fc781f Michael Hanselmann
  """
190 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
191 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
192 24fc781f Michael Hanselmann
193 24fc781f Michael Hanselmann
194 bd1e4562 Iustin Pop
def GetMasterInfo():
195 bd1e4562 Iustin Pop
  """Returns master information.
196 bd1e4562 Iustin Pop

197 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
198 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
199 bd1e4562 Iustin Pop

200 bd1e4562 Iustin Pop
  @rtype: tuple
201 c26a6bd2 Iustin Pop
  @return: master_netdev, master_ip, master_name
202 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
203 b1b6ea87 Iustin Pop

204 b1b6ea87 Iustin Pop
  """
205 b1b6ea87 Iustin Pop
  try:
206 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
207 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
208 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
209 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
210 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
211 29921401 Iustin Pop
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
212 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
213 b1b6ea87 Iustin Pop
214 b1b6ea87 Iustin Pop
215 3583908a Guido Trotter
def StartMaster(start_daemons, no_voting):
216 a8083063 Iustin Pop
  """Activate local node as master node.
217 a8083063 Iustin Pop

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

222 10c2650b Iustin Pop
  @type start_daemons: boolean
223 c26a6bd2 Iustin Pop
  @param start_daemons: whether to also start the master
224 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
225 3583908a Guido Trotter
  @type no_voting: boolean
226 3583908a Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
227 3583908a Guido Trotter
      (if start_daemons is True), but still non-interactively
228 10c2650b Iustin Pop
  @rtype: None
229 a8083063 Iustin Pop

230 a8083063 Iustin Pop
  """
231 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
232 541741d3 Guido Trotter
  master_netdev, master_ip, _ = GetMasterInfo()
233 a8083063 Iustin Pop
234 396b5733 Iustin Pop
  err_msgs = []
235 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
236 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
237 b1b6ea87 Iustin Pop
      # we already have the ip:
238 b726aff0 Iustin Pop
      logging.debug("Master IP already configured, doing nothing")
239 b1b6ea87 Iustin Pop
    else:
240 b726aff0 Iustin Pop
      msg = "Someone else has the master ip, not activating"
241 b726aff0 Iustin Pop
      logging.error(msg)
242 396b5733 Iustin Pop
      err_msgs.append(msg)
243 b1b6ea87 Iustin Pop
  else:
244 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
245 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
246 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
247 b1b6ea87 Iustin Pop
    if result.failed:
248 b726aff0 Iustin Pop
      msg = "Can't activate master IP: %s" % result.output
249 b726aff0 Iustin Pop
      logging.error(msg)
250 396b5733 Iustin Pop
      err_msgs.append(msg)
251 b1b6ea87 Iustin Pop
252 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
253 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
254 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
255 b1b6ea87 Iustin Pop
256 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
257 b1b6ea87 Iustin Pop
  if start_daemons:
258 3583908a Guido Trotter
    if no_voting:
259 f154a7a3 Michael Hanselmann
      masterd_args = "--no-voting --yes-do-it"
260 f154a7a3 Michael Hanselmann
    else:
261 f154a7a3 Michael Hanselmann
      masterd_args = ""
262 f154a7a3 Michael Hanselmann
263 f154a7a3 Michael Hanselmann
    env = {
264 f154a7a3 Michael Hanselmann
      "EXTRA_MASTERD_ARGS": masterd_args,
265 f154a7a3 Michael Hanselmann
      }
266 f154a7a3 Michael Hanselmann
267 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
268 f154a7a3 Michael Hanselmann
    if result.failed:
269 f154a7a3 Michael Hanselmann
      msg = "Can't start Ganeti master: %s" % result.output
270 f154a7a3 Michael Hanselmann
      logging.error(msg)
271 f154a7a3 Michael Hanselmann
      err_msgs.append(msg)
272 b726aff0 Iustin Pop
273 396b5733 Iustin Pop
  if err_msgs:
274 396b5733 Iustin Pop
    _Fail("; ".join(err_msgs))
275 afdc3985 Iustin Pop
276 a8083063 Iustin Pop
277 1c65840b Iustin Pop
def StopMaster(stop_daemons):
278 a8083063 Iustin Pop
  """Deactivate this node as master.
279 a8083063 Iustin Pop

280 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
281 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
282 10c2650b Iustin Pop
  stop_daemons parameter.
283 10c2650b Iustin Pop

284 10c2650b Iustin Pop
  @type stop_daemons: boolean
285 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
286 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
287 10c2650b Iustin Pop
  @rtype: None
288 a8083063 Iustin Pop

289 a8083063 Iustin Pop
  """
290 6c00d19a Iustin Pop
  # TODO: log and report back to the caller the error failures; we
291 6c00d19a Iustin Pop
  # need to decide in which case we fail the RPC for this
292 2a52a064 Iustin Pop
293 2a52a064 Iustin Pop
  # GetMasterInfo will raise an exception if not able to return data
294 541741d3 Guido Trotter
  master_netdev, master_ip, _ = GetMasterInfo()
295 a8083063 Iustin Pop
296 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
297 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
298 a8083063 Iustin Pop
  if result.failed:
299 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
300 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
301 b1b6ea87 Iustin Pop
302 b1b6ea87 Iustin Pop
  if stop_daemons:
303 f154a7a3 Michael Hanselmann
    result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
304 f154a7a3 Michael Hanselmann
    if result.failed:
305 f154a7a3 Michael Hanselmann
      logging.error("Could not stop Ganeti master, command %s had exitcode %s"
306 f154a7a3 Michael Hanselmann
                    " and error %s",
307 f154a7a3 Michael Hanselmann
                    result.cmd, result.exit_code, result.output)
308 a8083063 Iustin Pop
309 a8083063 Iustin Pop
310 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
311 7900ed01 Iustin Pop
  """Joins this node to the cluster.
312 a8083063 Iustin Pop

313 7900ed01 Iustin Pop
  This does the following:
314 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
315 7900ed01 Iustin Pop
      - adds the ssh private key to the user
316 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
317 a8083063 Iustin Pop

318 10c2650b Iustin Pop
  @type dsa: str
319 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
320 10c2650b Iustin Pop
  @type dsapub: str
321 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
322 10c2650b Iustin Pop
  @type rsa: str
323 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
324 10c2650b Iustin Pop
  @type rsapub: str
325 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
326 10c2650b Iustin Pop
  @type sshkey: str
327 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
328 10c2650b Iustin Pop
  @type sshpub: str
329 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
330 10c2650b Iustin Pop
  @rtype: boolean
331 10c2650b Iustin Pop
  @return: the success of the operation
332 10c2650b Iustin Pop

333 7900ed01 Iustin Pop
  """
334 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
335 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
336 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
337 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
338 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
339 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
340 a8083063 Iustin Pop
341 70d9e3d8 Iustin Pop
  try:
342 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
343 70d9e3d8 Iustin Pop
                                                    mkdir=True)
344 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
345 2cc6781a Iustin Pop
    _Fail("Error while processing user ssh files: %s", err, exc=True)
346 a8083063 Iustin Pop
347 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
348 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
349 a8083063 Iustin Pop
350 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
351 a8083063 Iustin Pop
352 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
353 a8083063 Iustin Pop
354 a8083063 Iustin Pop
355 b989b9d9 Ken Wehr
def LeaveCluster(modify_ssh_setup):
356 10c2650b Iustin Pop
  """Cleans up and remove the current node.
357 10c2650b Iustin Pop

358 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
359 10c2650b Iustin Pop
  from the cluster.
360 10c2650b Iustin Pop

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

365 b989b9d9 Ken Wehr
  @param modify_ssh_setup: boolean
366 b989b9d9 Ken Wehr

367 a8083063 Iustin Pop
  """
368 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
369 1bc59f76 Michael Hanselmann
  JobQueuePurge()
370 f78346f5 Michael Hanselmann
371 b989b9d9 Ken Wehr
  if modify_ssh_setup:
372 b989b9d9 Ken Wehr
    try:
373 b989b9d9 Ken Wehr
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
374 7900ed01 Iustin Pop
375 b989b9d9 Ken Wehr
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
376 a8083063 Iustin Pop
377 b989b9d9 Ken Wehr
      utils.RemoveFile(priv_key)
378 b989b9d9 Ken Wehr
      utils.RemoveFile(pub_key)
379 b989b9d9 Ken Wehr
    except errors.OpExecError:
380 b989b9d9 Ken Wehr
      logging.exception("Error while processing ssh files")
381 a8083063 Iustin Pop
382 ed008420 Guido Trotter
  try:
383 ed008420 Guido Trotter
    utils.RemoveFile(constants.HMAC_CLUSTER_KEY)
384 ed008420 Guido Trotter
    utils.RemoveFile(constants.RAPI_CERT_FILE)
385 ed008420 Guido Trotter
    utils.RemoveFile(constants.SSL_CERT_FILE)
386 ed008420 Guido Trotter
  except:
387 ed008420 Guido Trotter
    logging.exception("Error while removing cluster secrets")
388 ed008420 Guido Trotter
389 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
390 f154a7a3 Michael Hanselmann
  if result.failed:
391 f154a7a3 Michael Hanselmann
    logging.error("Command %s failed with exitcode %s and error %s",
392 f154a7a3 Michael Hanselmann
                  result.cmd, result.exit_code, result.output)
393 ed008420 Guido Trotter
394 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
395 0623d351 Iustin Pop
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
396 6d8b6238 Guido Trotter
397 a8083063 Iustin Pop
398 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
399 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
400 a8083063 Iustin Pop

401 e69d05fd Iustin Pop
  @type vgname: C{string}
402 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
403 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
404 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
405 e69d05fd Iustin Pop
      memory information
406 e69d05fd Iustin Pop
  @rtype: C{dict}
407 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
408 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
409 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
410 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
411 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
412 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
413 a8083063 Iustin Pop

414 098c0958 Michael Hanselmann
  """
415 a8083063 Iustin Pop
  outputarray = {}
416 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
417 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
418 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
419 a8083063 Iustin Pop
420 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
421 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
422 a8083063 Iustin Pop
  if hyp_info is not None:
423 a8083063 Iustin Pop
    outputarray.update(hyp_info)
424 a8083063 Iustin Pop
425 13998ef2 Michael Hanselmann
  outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
426 3ef10550 Michael Hanselmann
427 c26a6bd2 Iustin Pop
  return outputarray
428 a8083063 Iustin Pop
429 a8083063 Iustin Pop
430 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
431 a8083063 Iustin Pop
  """Verify the status of the local node.
432 a8083063 Iustin Pop

433 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
434 e69d05fd Iustin Pop
  local node.
435 e69d05fd Iustin Pop

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

439 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
440 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
441 e69d05fd Iustin Pop
  report).
442 a8083063 Iustin Pop

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

447 e69d05fd Iustin Pop
  @type what: C{dict}
448 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
449 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
450 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
451 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
452 e69d05fd Iustin Pop
        connectivity with
453 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
454 10c2650b Iustin Pop
  @rtype: dict
455 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
456 10c2650b Iustin Pop
      values representing the result of the checks
457 a8083063 Iustin Pop

458 a8083063 Iustin Pop
  """
459 a8083063 Iustin Pop
  result = {}
460 a8083063 Iustin Pop
461 25361b9a Iustin Pop
  if constants.NV_HYPERVISOR in what:
462 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
463 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
464 25361b9a Iustin Pop
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
465 25361b9a Iustin Pop
466 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
467 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
468 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
469 25361b9a Iustin Pop
470 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
471 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
472 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
473 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
474 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
475 a8083063 Iustin Pop
      if not success:
476 25361b9a Iustin Pop
        tmp[node] = message
477 25361b9a Iustin Pop
478 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
479 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
480 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
481 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
482 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
483 9d4bfc96 Iustin Pop
      if name == my_name:
484 9d4bfc96 Iustin Pop
        my_pip = pip
485 9d4bfc96 Iustin Pop
        my_sip = sip
486 9d4bfc96 Iustin Pop
        break
487 9d4bfc96 Iustin Pop
    if not my_pip:
488 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
489 25361b9a Iustin Pop
                      " in the node list")
490 9d4bfc96 Iustin Pop
    else:
491 cd50653c Guido Trotter
      port = utils.GetDaemonPort(constants.NODED)
492 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
493 9d4bfc96 Iustin Pop
        fail = []
494 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
495 9d4bfc96 Iustin Pop
          fail.append("primary")
496 9d4bfc96 Iustin Pop
        if sip != pip:
497 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
498 9d4bfc96 Iustin Pop
            fail.append("secondary")
499 9d4bfc96 Iustin Pop
        if fail:
500 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
501 25361b9a Iustin Pop
                       " and ".join(fail))
502 25361b9a Iustin Pop
503 25361b9a Iustin Pop
  if constants.NV_LVLIST in what:
504 25361b9a Iustin Pop
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
505 25361b9a Iustin Pop
506 25361b9a Iustin Pop
  if constants.NV_INSTANCELIST in what:
507 25361b9a Iustin Pop
    result[constants.NV_INSTANCELIST] = GetInstanceList(
508 25361b9a Iustin Pop
      what[constants.NV_INSTANCELIST])
509 25361b9a Iustin Pop
510 25361b9a Iustin Pop
  if constants.NV_VGLIST in what:
511 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
512 25361b9a Iustin Pop
513 d091393e Iustin Pop
  if constants.NV_PVLIST in what:
514 d091393e Iustin Pop
    result[constants.NV_PVLIST] = \
515 d091393e Iustin Pop
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
516 d091393e Iustin Pop
                                   filter_allocatable=False)
517 d091393e Iustin Pop
518 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
519 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
520 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
521 25361b9a Iustin Pop
522 25361b9a Iustin Pop
  if constants.NV_HVINFO in what:
523 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
524 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
525 9d4bfc96 Iustin Pop
526 6d2e83d5 Iustin Pop
  if constants.NV_DRBDLIST in what:
527 6d2e83d5 Iustin Pop
    try:
528 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
529 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
530 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
531 f6eaed12 Iustin Pop
      used_minors = str(err)
532 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
533 6d2e83d5 Iustin Pop
534 7c0aa8e9 Iustin Pop
  if constants.NV_NODESETUP in what:
535 7c0aa8e9 Iustin Pop
    result[constants.NV_NODESETUP] = tmpr = []
536 7c0aa8e9 Iustin Pop
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
537 7c0aa8e9 Iustin Pop
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
538 7c0aa8e9 Iustin Pop
                  " under /sys, missing required directories /sys/block"
539 7c0aa8e9 Iustin Pop
                  " and /sys/class/net")
540 7c0aa8e9 Iustin Pop
    if (not os.path.isdir("/proc/sys") or
541 7c0aa8e9 Iustin Pop
        not os.path.isfile("/proc/sysrq-trigger")):
542 7c0aa8e9 Iustin Pop
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
543 7c0aa8e9 Iustin Pop
                  " under /proc, missing required directory /proc/sys and"
544 7c0aa8e9 Iustin Pop
                  " the file /proc/sysrq-trigger")
545 c26a6bd2 Iustin Pop
  return result
546 a8083063 Iustin Pop
547 a8083063 Iustin Pop
548 a8083063 Iustin Pop
def GetVolumeList(vg_name):
549 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
550 a8083063 Iustin Pop

551 10c2650b Iustin Pop
  @type vg_name: str
552 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
553 10c2650b Iustin Pop
  @rtype: dict
554 10c2650b Iustin Pop
  @return:
555 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
556 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
557 10c2650b Iustin Pop

558 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
559 10c2650b Iustin Pop

560 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
561 10c2650b Iustin Pop
      details.
562 a8083063 Iustin Pop

563 a8083063 Iustin Pop
  """
564 cb2037a2 Iustin Pop
  lvs = {}
565 cb2037a2 Iustin Pop
  sep = '|'
566 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
567 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
568 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
569 a8083063 Iustin Pop
  if result.failed:
570 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
571 cb2037a2 Iustin Pop
572 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
573 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
574 df4c2628 Iustin Pop
    line = line.strip()
575 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
576 df4c2628 Iustin Pop
    if not match:
577 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
578 df4c2628 Iustin Pop
      continue
579 df4c2628 Iustin Pop
    name, size, attr = match.groups()
580 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
581 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
582 33f2a81a Iustin Pop
    virtual = attr[0] == 'v'
583 33f2a81a Iustin Pop
    if virtual:
584 33f2a81a Iustin Pop
      # we don't want to report such volumes as existing, since they
585 33f2a81a Iustin Pop
      # don't really hold data
586 33f2a81a Iustin Pop
      continue
587 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
588 cb2037a2 Iustin Pop
589 cb2037a2 Iustin Pop
  return lvs
590 a8083063 Iustin Pop
591 a8083063 Iustin Pop
592 a8083063 Iustin Pop
def ListVolumeGroups():
593 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
594 a8083063 Iustin Pop

595 10c2650b Iustin Pop
  @rtype: dict
596 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
597 10c2650b Iustin Pop
      size of the volume
598 a8083063 Iustin Pop

599 a8083063 Iustin Pop
  """
600 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
601 a8083063 Iustin Pop
602 a8083063 Iustin Pop
603 dcb93971 Michael Hanselmann
def NodeVolumes():
604 dcb93971 Michael Hanselmann
  """List all volumes on this node.
605 dcb93971 Michael Hanselmann

606 10c2650b Iustin Pop
  @rtype: list
607 10c2650b Iustin Pop
  @return:
608 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
609 10c2650b Iustin Pop
      - name: the logical volume name,
610 10c2650b Iustin Pop
      - size: the size of the logical volume
611 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
612 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
613 10c2650b Iustin Pop

614 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
615 10c2650b Iustin Pop
    error.
616 10c2650b Iustin Pop

617 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
618 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
619 10c2650b Iustin Pop
    multiple times.
620 10c2650b Iustin Pop

621 dcb93971 Michael Hanselmann
  """
622 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
623 dcb93971 Michael Hanselmann
                         "--separator=|",
624 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
625 dcb93971 Michael Hanselmann
  if result.failed:
626 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
627 10bfe6cb Iustin Pop
          result.output)
628 dcb93971 Michael Hanselmann
629 dcb93971 Michael Hanselmann
  def parse_dev(dev):
630 dcb93971 Michael Hanselmann
    if '(' in dev:
631 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
632 dcb93971 Michael Hanselmann
    else:
633 dcb93971 Michael Hanselmann
      return dev
634 dcb93971 Michael Hanselmann
635 dcb93971 Michael Hanselmann
  def map_line(line):
636 dcb93971 Michael Hanselmann
    return {
637 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
638 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
639 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
640 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
641 dcb93971 Michael Hanselmann
    }
642 dcb93971 Michael Hanselmann
643 c26a6bd2 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
644 c26a6bd2 Iustin Pop
          if line.count('|') >= 3]
645 dcb93971 Michael Hanselmann
646 dcb93971 Michael Hanselmann
647 a8083063 Iustin Pop
def BridgesExist(bridges_list):
648 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
649 a8083063 Iustin Pop

650 b1206984 Iustin Pop
  @rtype: boolean
651 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
652 a8083063 Iustin Pop

653 a8083063 Iustin Pop
  """
654 35c0c8da Iustin Pop
  missing = []
655 a8083063 Iustin Pop
  for bridge in bridges_list:
656 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
657 35c0c8da Iustin Pop
      missing.append(bridge)
658 a8083063 Iustin Pop
659 35c0c8da Iustin Pop
  if missing:
660 afdc3985 Iustin Pop
    _Fail("Missing bridges %s", ", ".join(missing))
661 35c0c8da Iustin Pop
662 a8083063 Iustin Pop
663 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
664 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
665 a8083063 Iustin Pop

666 e69d05fd Iustin Pop
  @type hypervisor_list: list
667 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
668 e69d05fd Iustin Pop

669 e69d05fd Iustin Pop
  @rtype: list
670 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
671 10c2650b Iustin Pop
    - instance1.example.com
672 10c2650b Iustin Pop
    - instance2.example.com
673 a8083063 Iustin Pop

674 098c0958 Michael Hanselmann
  """
675 e69d05fd Iustin Pop
  results = []
676 e69d05fd Iustin Pop
  for hname in hypervisor_list:
677 e69d05fd Iustin Pop
    try:
678 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
679 e69d05fd Iustin Pop
      results.extend(names)
680 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
681 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
682 aca13712 Iustin Pop
            hname, err, exc=True)
683 a8083063 Iustin Pop
684 e69d05fd Iustin Pop
  return results
685 a8083063 Iustin Pop
686 a8083063 Iustin Pop
687 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
688 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
689 a8083063 Iustin Pop

690 e69d05fd Iustin Pop
  @type instance: string
691 e69d05fd Iustin Pop
  @param instance: the instance name
692 e69d05fd Iustin Pop
  @type hname: string
693 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
694 a8083063 Iustin Pop

695 e69d05fd Iustin Pop
  @rtype: dict
696 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
697 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
698 e69d05fd Iustin Pop
      - state: xen state of instance (string)
699 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
700 a8083063 Iustin Pop

701 098c0958 Michael Hanselmann
  """
702 a8083063 Iustin Pop
  output = {}
703 a8083063 Iustin Pop
704 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
705 a8083063 Iustin Pop
  if iinfo is not None:
706 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
707 a8083063 Iustin Pop
    output['state'] = iinfo[4]
708 a8083063 Iustin Pop
    output['time'] = iinfo[5]
709 a8083063 Iustin Pop
710 c26a6bd2 Iustin Pop
  return output
711 a8083063 Iustin Pop
712 a8083063 Iustin Pop
713 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
714 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
715 56e7640c Iustin Pop

716 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
717 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
718 56e7640c Iustin Pop

719 56e7640c Iustin Pop
  @rtype: tuple
720 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
721 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
722 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
723 56e7640c Iustin Pop

724 56e7640c Iustin Pop
  """
725 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
726 afdc3985 Iustin Pop
  iname = instance.name
727 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
728 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
729 56e7640c Iustin Pop
730 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
731 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
732 56e7640c Iustin Pop
    if not os.path.islink(link_name):
733 afdc3985 Iustin Pop
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
734 56e7640c Iustin Pop
735 56e7640c Iustin Pop
736 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
737 a8083063 Iustin Pop
  """Gather data about all instances.
738 a8083063 Iustin Pop

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

743 e69d05fd Iustin Pop
  @type hypervisor_list: list
744 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
745 e69d05fd Iustin Pop

746 955db481 Guido Trotter
  @rtype: dict
747 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
748 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
749 e69d05fd Iustin Pop
      - state: xen state of instance (string)
750 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
751 10c2650b Iustin Pop
      - vcpus: the number of vcpus
752 a8083063 Iustin Pop

753 098c0958 Michael Hanselmann
  """
754 a8083063 Iustin Pop
  output = {}
755 a8083063 Iustin Pop
756 e69d05fd Iustin Pop
  for hname in hypervisor_list:
757 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
758 e69d05fd Iustin Pop
    if iinfo:
759 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
760 f23b5ae8 Iustin Pop
        value = {
761 e69d05fd Iustin Pop
          'memory': memory,
762 e69d05fd Iustin Pop
          'vcpus': vcpus,
763 e69d05fd Iustin Pop
          'state': state,
764 e69d05fd Iustin Pop
          'time': times,
765 e69d05fd Iustin Pop
          }
766 b33b6f55 Iustin Pop
        if name in output:
767 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
768 b33b6f55 Iustin Pop
          # and not state and time which can change between the
769 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
770 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
771 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
772 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
773 2fa74ef4 Iustin Pop
                    " with different parameters", name)
774 f23b5ae8 Iustin Pop
        output[name] = value
775 a8083063 Iustin Pop
776 c26a6bd2 Iustin Pop
  return output
777 a8083063 Iustin Pop
778 a8083063 Iustin Pop
779 e557bae9 Guido Trotter
def InstanceOsAdd(instance, reinstall):
780 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
781 a8083063 Iustin Pop

782 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
783 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
784 e557bae9 Guido Trotter
  @type reinstall: boolean
785 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
786 c26a6bd2 Iustin Pop
  @rtype: None
787 a8083063 Iustin Pop

788 a8083063 Iustin Pop
  """
789 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
790 255dcebd Iustin Pop
791 d1a7d66f Guido Trotter
  create_env = OSEnvironment(instance, inst_os)
792 e557bae9 Guido Trotter
  if reinstall:
793 e557bae9 Guido Trotter
    create_env['INSTANCE_REINSTALL'] = "1"
794 a8083063 Iustin Pop
795 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
796 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
797 decd5f45 Iustin Pop
798 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
799 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
800 decd5f45 Iustin Pop
  if result.failed:
801 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
802 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
803 18682bca Iustin Pop
                  result.output)
804 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
805 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
806 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
807 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
808 decd5f45 Iustin Pop
809 decd5f45 Iustin Pop
810 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
811 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
812 decd5f45 Iustin Pop

813 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
814 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
815 d15a9ad3 Guido Trotter
  @type old_name: string
816 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
817 10c2650b Iustin Pop
  @rtype: boolean
818 10c2650b Iustin Pop
  @return: the success of the operation
819 decd5f45 Iustin Pop

820 decd5f45 Iustin Pop
  """
821 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
822 decd5f45 Iustin Pop
823 d1a7d66f Guido Trotter
  rename_env = OSEnvironment(instance, inst_os)
824 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
825 decd5f45 Iustin Pop
826 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
827 decd5f45 Iustin Pop
                                           old_name,
828 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
829 a8083063 Iustin Pop
830 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
831 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
832 a8083063 Iustin Pop
833 a8083063 Iustin Pop
  if result.failed:
834 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
835 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
836 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
837 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
838 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
839 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
840 a8083063 Iustin Pop
841 a8083063 Iustin Pop
842 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
843 5bbd3f7f Michael Hanselmann
  """Get information about the volume group.
844 a8083063 Iustin Pop

845 10c2650b Iustin Pop
  @type vg_name: str
846 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
847 10c2650b Iustin Pop
  @rtype: dict
848 10c2650b Iustin Pop
  @return:
849 10c2650b Iustin Pop
    A dictionary with the following keys:
850 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
851 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
852 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
853 a8083063 Iustin Pop

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

857 a8083063 Iustin Pop
  """
858 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
859 f4d377e7 Iustin Pop
860 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
861 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
862 a8083063 Iustin Pop
863 a8083063 Iustin Pop
  if retval.failed:
864 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
865 f4d377e7 Iustin Pop
    return retdic
866 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
867 f4d377e7 Iustin Pop
  if len(valarr) == 3:
868 f4d377e7 Iustin Pop
    try:
869 f4d377e7 Iustin Pop
      retdic = {
870 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
871 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
872 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
873 f4d377e7 Iustin Pop
        }
874 f4d377e7 Iustin Pop
    except ValueError, err:
875 29921401 Iustin Pop
      logging.exception("Fail to parse vgs output: %s", err)
876 f4d377e7 Iustin Pop
  else:
877 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
878 18682bca Iustin Pop
                  " three): %s", str(valarr))
879 a8083063 Iustin Pop
  return retdic
880 a8083063 Iustin Pop
881 a8083063 Iustin Pop
882 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
883 5282084b Iustin Pop
  return os.path.join(constants.DISK_LINKS_DIR,
884 5282084b Iustin Pop
                      "%s:%d" % (instance_name, idx))
885 5282084b Iustin Pop
886 5282084b Iustin Pop
887 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
888 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
889 9332fd8a Iustin Pop

890 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
891 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
892 9332fd8a Iustin Pop

893 9332fd8a Iustin Pop

894 5282084b Iustin Pop
  @param instance_name: the name of the target instance
895 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
896 5282084b Iustin Pop
  @param idx: the disk index
897 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
898 9332fd8a Iustin Pop

899 9332fd8a Iustin Pop
  """
900 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
901 9332fd8a Iustin Pop
  try:
902 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
903 5282084b Iustin Pop
  except OSError, err:
904 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
905 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
906 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
907 9332fd8a Iustin Pop
        os.remove(link_name)
908 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
909 9332fd8a Iustin Pop
    else:
910 9332fd8a Iustin Pop
      raise
911 9332fd8a Iustin Pop
912 9332fd8a Iustin Pop
  return link_name
913 9332fd8a Iustin Pop
914 9332fd8a Iustin Pop
915 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
916 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
917 3c9c571d Iustin Pop

918 3c9c571d Iustin Pop
  """
919 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
920 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
921 5282084b Iustin Pop
    if os.path.islink(link_name):
922 3c9c571d Iustin Pop
      try:
923 03dfa658 Iustin Pop
        os.remove(link_name)
924 03dfa658 Iustin Pop
      except OSError:
925 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
926 3c9c571d Iustin Pop
927 3c9c571d Iustin Pop
928 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
929 a8083063 Iustin Pop
  """Set up an instance's block device(s).
930 a8083063 Iustin Pop

931 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
932 a8083063 Iustin Pop
  devices must be already assembled.
933 a8083063 Iustin Pop

934 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
935 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
936 069cfbf1 Iustin Pop
  @rtype: list
937 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
938 10c2650b Iustin Pop

939 a8083063 Iustin Pop
  """
940 a8083063 Iustin Pop
  block_devices = []
941 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
942 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
943 a8083063 Iustin Pop
    if device is None:
944 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
945 a8083063 Iustin Pop
                                    str(disk))
946 a8083063 Iustin Pop
    device.Open()
947 9332fd8a Iustin Pop
    try:
948 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
949 9332fd8a Iustin Pop
    except OSError, e:
950 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
951 9332fd8a Iustin Pop
                                    e.strerror)
952 9332fd8a Iustin Pop
953 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
954 9332fd8a Iustin Pop
955 a8083063 Iustin Pop
  return block_devices
956 a8083063 Iustin Pop
957 a8083063 Iustin Pop
958 07813a9e Iustin Pop
def StartInstance(instance):
959 a8083063 Iustin Pop
  """Start an instance.
960 a8083063 Iustin Pop

961 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
962 e69d05fd Iustin Pop
  @param instance: the instance object
963 c26a6bd2 Iustin Pop
  @rtype: None
964 a8083063 Iustin Pop

965 098c0958 Michael Hanselmann
  """
966 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
967 a8083063 Iustin Pop
968 a8083063 Iustin Pop
  if instance.name in running_instances:
969 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
970 c26a6bd2 Iustin Pop
    return
971 a8083063 Iustin Pop
972 a8083063 Iustin Pop
  try:
973 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
974 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
975 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
976 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
977 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
978 a8083063 Iustin Pop
  except errors.HypervisorError, err:
979 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
980 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
981 a8083063 Iustin Pop
982 a8083063 Iustin Pop
983 6263189c Guido Trotter
def InstanceShutdown(instance, timeout):
984 a8083063 Iustin Pop
  """Shut an instance down.
985 a8083063 Iustin Pop

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

988 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
989 e69d05fd Iustin Pop
  @param instance: the instance object
990 6263189c Guido Trotter
  @type timeout: integer
991 6263189c Guido Trotter
  @param timeout: maximum timeout for soft shutdown
992 c26a6bd2 Iustin Pop
  @rtype: None
993 a8083063 Iustin Pop

994 098c0958 Michael Hanselmann
  """
995 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
996 e4e9b806 Guido Trotter
  hyper = hypervisor.GetHypervisor(hv_name)
997 c26a6bd2 Iustin Pop
  iname = instance.name
998 a8083063 Iustin Pop
999 3c0cdc83 Michael Hanselmann
  if instance.name not in hyper.ListInstances():
1000 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
1001 c26a6bd2 Iustin Pop
    return
1002 a8083063 Iustin Pop
1003 3c0cdc83 Michael Hanselmann
  class _TryShutdown:
1004 3c0cdc83 Michael Hanselmann
    def __init__(self):
1005 3c0cdc83 Michael Hanselmann
      self.tried_once = False
1006 a8083063 Iustin Pop
1007 3c0cdc83 Michael Hanselmann
    def __call__(self):
1008 3c0cdc83 Michael Hanselmann
      if iname not in hyper.ListInstances():
1009 3c0cdc83 Michael Hanselmann
        return
1010 3c0cdc83 Michael Hanselmann
1011 3c0cdc83 Michael Hanselmann
      try:
1012 3c0cdc83 Michael Hanselmann
        hyper.StopInstance(instance, retry=self.tried_once)
1013 3c0cdc83 Michael Hanselmann
      except errors.HypervisorError, err:
1014 3c0cdc83 Michael Hanselmann
        if iname not in hyper.ListInstances():
1015 3c0cdc83 Michael Hanselmann
          # if the instance is no longer existing, consider this a
1016 3c0cdc83 Michael Hanselmann
          # success and go to cleanup
1017 3c0cdc83 Michael Hanselmann
          return
1018 3c0cdc83 Michael Hanselmann
1019 3c0cdc83 Michael Hanselmann
        _Fail("Failed to stop instance %s: %s", iname, err)
1020 3c0cdc83 Michael Hanselmann
1021 3c0cdc83 Michael Hanselmann
      self.tried_once = True
1022 3c0cdc83 Michael Hanselmann
1023 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
1024 3c0cdc83 Michael Hanselmann
1025 3c0cdc83 Michael Hanselmann
  try:
1026 3c0cdc83 Michael Hanselmann
    utils.Retry(_TryShutdown(), 5, timeout)
1027 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
1028 a8083063 Iustin Pop
    # the shutdown did not succeed
1029 e4e9b806 Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1030 a8083063 Iustin Pop
1031 a8083063 Iustin Pop
    try:
1032 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
1033 a8083063 Iustin Pop
    except errors.HypervisorError, err:
1034 3c0cdc83 Michael Hanselmann
      if iname in hyper.ListInstances():
1035 3782acd7 Iustin Pop
        # only raise an error if the instance still exists, otherwise
1036 3782acd7 Iustin Pop
        # the error could simply be "instance ... unknown"!
1037 3782acd7 Iustin Pop
        _Fail("Failed to force stop instance %s: %s", iname, err)
1038 a8083063 Iustin Pop
1039 a8083063 Iustin Pop
    time.sleep(1)
1040 3c0cdc83 Michael Hanselmann
1041 3c0cdc83 Michael Hanselmann
    if iname in hyper.ListInstances():
1042 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
1043 3c9c571d Iustin Pop
1044 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
1045 a8083063 Iustin Pop
1046 a8083063 Iustin Pop
1047 17c3f802 Guido Trotter
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1048 007a2f3e Alexander Schreiber
  """Reboot an instance.
1049 007a2f3e Alexander Schreiber

1050 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1051 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1052 10c2650b Iustin Pop
  @type reboot_type: str
1053 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1054 10c2650b Iustin Pop
    constants:
1055 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1056 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1057 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1058 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1059 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1060 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1061 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1062 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1063 23057d29 Michael Hanselmann
  @type shutdown_timeout: integer
1064 23057d29 Michael Hanselmann
  @param shutdown_timeout: maximum timeout for soft shutdown
1065 c26a6bd2 Iustin Pop
  @rtype: None
1066 007a2f3e Alexander Schreiber

1067 007a2f3e Alexander Schreiber
  """
1068 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1069 007a2f3e Alexander Schreiber
1070 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1071 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1072 007a2f3e Alexander Schreiber
1073 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1074 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1075 007a2f3e Alexander Schreiber
    try:
1076 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1077 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1078 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1079 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1080 007a2f3e Alexander Schreiber
    try:
1081 17c3f802 Guido Trotter
      InstanceShutdown(instance, shutdown_timeout)
1082 07813a9e Iustin Pop
      return StartInstance(instance)
1083 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1084 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1085 007a2f3e Alexander Schreiber
  else:
1086 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1087 007a2f3e Alexander Schreiber
1088 007a2f3e Alexander Schreiber
1089 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1090 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1091 6906a9d8 Guido Trotter

1092 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1093 6906a9d8 Guido Trotter
  @param instance: the instance definition
1094 6906a9d8 Guido Trotter

1095 6906a9d8 Guido Trotter
  """
1096 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1097 cd42d0ad Guido Trotter
  try:
1098 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1099 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1100 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1101 c26a6bd2 Iustin Pop
  return info
1102 6906a9d8 Guido Trotter
1103 6906a9d8 Guido Trotter
1104 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1105 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1106 6906a9d8 Guido Trotter

1107 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1108 6906a9d8 Guido Trotter
  @param instance: the instance definition
1109 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1110 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1111 6906a9d8 Guido Trotter
  @type target: string
1112 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1113 6906a9d8 Guido Trotter

1114 6906a9d8 Guido Trotter
  """
1115 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1116 cd42d0ad Guido Trotter
  try:
1117 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1118 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1119 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1120 6906a9d8 Guido Trotter
1121 6906a9d8 Guido Trotter
1122 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1123 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1124 6906a9d8 Guido Trotter

1125 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1126 6906a9d8 Guido Trotter
  @param instance: the instance definition
1127 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1128 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1129 6906a9d8 Guido Trotter
  @type success: boolean
1130 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1131 6906a9d8 Guido Trotter

1132 6906a9d8 Guido Trotter
  """
1133 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1134 cd42d0ad Guido Trotter
  try:
1135 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1136 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1137 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1138 6906a9d8 Guido Trotter
1139 6906a9d8 Guido Trotter
1140 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1141 2a10865c Iustin Pop
  """Migrates an instance to another node.
1142 2a10865c Iustin Pop

1143 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1144 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1145 9f0e6b37 Iustin Pop
  @type target: string
1146 9f0e6b37 Iustin Pop
  @param target: the target node name
1147 9f0e6b37 Iustin Pop
  @type live: boolean
1148 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1149 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1150 9f0e6b37 Iustin Pop
  @rtype: tuple
1151 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1152 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1153 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1154 9f0e6b37 Iustin Pop

1155 2a10865c Iustin Pop
  """
1156 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1157 2a10865c Iustin Pop
1158 2a10865c Iustin Pop
  try:
1159 58d38b02 Iustin Pop
    hyper.MigrateInstance(instance, target, live)
1160 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1161 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1162 2a10865c Iustin Pop
1163 2a10865c Iustin Pop
1164 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1165 a8083063 Iustin Pop
  """Creates a block device for an instance.
1166 a8083063 Iustin Pop

1167 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1168 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1169 b1206984 Iustin Pop
  @type size: int
1170 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1171 b1206984 Iustin Pop
  @type owner: str
1172 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1173 b1206984 Iustin Pop
      used for device cache data
1174 b1206984 Iustin Pop
  @type on_primary: boolean
1175 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1176 b1206984 Iustin Pop
  @type info: string
1177 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1178 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1179 b1206984 Iustin Pop

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

1184 a8083063 Iustin Pop
  """
1185 a8083063 Iustin Pop
  clist = []
1186 a8083063 Iustin Pop
  if disk.children:
1187 a8083063 Iustin Pop
    for child in disk.children:
1188 1063abd1 Iustin Pop
      try:
1189 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1190 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1191 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1192 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1193 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1194 a8083063 Iustin Pop
        # be assembled
1195 1063abd1 Iustin Pop
        try:
1196 1063abd1 Iustin Pop
          crdev.Open()
1197 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1198 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1199 a8083063 Iustin Pop
      clist.append(crdev)
1200 a8083063 Iustin Pop
1201 dab69e97 Iustin Pop
  try:
1202 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1203 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1204 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1205 6c626518 Iustin Pop
1206 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1207 1063abd1 Iustin Pop
    try:
1208 1063abd1 Iustin Pop
      device.Assemble()
1209 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1210 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1211 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1212 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1213 1063abd1 Iustin Pop
      try:
1214 1063abd1 Iustin Pop
        device.Open(force=True)
1215 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1216 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1217 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1218 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1219 a0c3fea1 Michael Hanselmann
1220 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1221 a0c3fea1 Michael Hanselmann
1222 c26a6bd2 Iustin Pop
  return device.unique_id
1223 a8083063 Iustin Pop
1224 a8083063 Iustin Pop
1225 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1226 a8083063 Iustin Pop
  """Remove a block device.
1227 a8083063 Iustin Pop

1228 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1229 10c2650b Iustin Pop

1230 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1231 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1232 10c2650b Iustin Pop
  @rtype: boolean
1233 10c2650b Iustin Pop
  @return: the success of the operation
1234 a8083063 Iustin Pop

1235 a8083063 Iustin Pop
  """
1236 e1bc0878 Iustin Pop
  msgs = []
1237 a8083063 Iustin Pop
  try:
1238 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1239 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1240 a8083063 Iustin Pop
    # probably can't attach
1241 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1242 a8083063 Iustin Pop
    rdev = None
1243 a8083063 Iustin Pop
  if rdev is not None:
1244 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1245 e1bc0878 Iustin Pop
    try:
1246 0c6c04ec Iustin Pop
      rdev.Remove()
1247 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1248 e1bc0878 Iustin Pop
      msgs.append(str(err))
1249 c26a6bd2 Iustin Pop
    if not msgs:
1250 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1251 e1bc0878 Iustin Pop
1252 a8083063 Iustin Pop
  if disk.children:
1253 a8083063 Iustin Pop
    for child in disk.children:
1254 c26a6bd2 Iustin Pop
      try:
1255 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1256 c26a6bd2 Iustin Pop
      except RPCFail, err:
1257 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1258 e1bc0878 Iustin Pop
1259 c26a6bd2 Iustin Pop
  if msgs:
1260 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1261 afdc3985 Iustin Pop
1262 a8083063 Iustin Pop
1263 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1264 a8083063 Iustin Pop
  """Activate a block device for an instance.
1265 a8083063 Iustin Pop

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

1268 10c2650b Iustin Pop
  @note: this function is called recursively.
1269 a8083063 Iustin Pop

1270 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1271 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1272 10c2650b Iustin Pop
  @type owner: str
1273 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1274 10c2650b Iustin Pop
  @type as_primary: boolean
1275 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1276 10c2650b Iustin Pop
      read/write
1277 a8083063 Iustin Pop

1278 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1279 10c2650b Iustin Pop
      was assembled)
1280 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1281 10c2650b Iustin Pop
      during the activation of the children or the device
1282 10c2650b Iustin Pop
      itself
1283 a8083063 Iustin Pop

1284 a8083063 Iustin Pop
  """
1285 a8083063 Iustin Pop
  children = []
1286 a8083063 Iustin Pop
  if disk.children:
1287 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1288 fc1dc9d7 Iustin Pop
    if mcn == -1:
1289 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1290 fc1dc9d7 Iustin Pop
    else:
1291 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1292 a8083063 Iustin Pop
    for chld_disk in disk.children:
1293 fc1dc9d7 Iustin Pop
      try:
1294 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1295 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1296 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1297 fc1dc9d7 Iustin Pop
          raise
1298 fc1dc9d7 Iustin Pop
        cdev = None
1299 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1300 1063abd1 Iustin Pop
                      str(err))
1301 fc1dc9d7 Iustin Pop
      children.append(cdev)
1302 a8083063 Iustin Pop
1303 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1304 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1305 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1306 a8083063 Iustin Pop
    result = r_dev
1307 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1308 a8083063 Iustin Pop
      r_dev.Open()
1309 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1310 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1311 3f78eef2 Iustin Pop
1312 a8083063 Iustin Pop
  else:
1313 a8083063 Iustin Pop
    result = True
1314 a8083063 Iustin Pop
  return result
1315 a8083063 Iustin Pop
1316 a8083063 Iustin Pop
1317 821d1bd1 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary):
1318 a8083063 Iustin Pop
  """Activate a block device for an instance.
1319 a8083063 Iustin Pop

1320 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1321 a8083063 Iustin Pop

1322 b1206984 Iustin Pop
  @rtype: str or boolean
1323 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1324 b1206984 Iustin Pop
      C{True} for secondary nodes
1325 a8083063 Iustin Pop

1326 a8083063 Iustin Pop
  """
1327 53c14ef1 Iustin Pop
  try:
1328 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1329 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1330 53c14ef1 Iustin Pop
      result = result.dev_path
1331 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1332 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1333 afdc3985 Iustin Pop
1334 c26a6bd2 Iustin Pop
  return result
1335 a8083063 Iustin Pop
1336 a8083063 Iustin Pop
1337 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1338 a8083063 Iustin Pop
  """Shut down a block device.
1339 a8083063 Iustin Pop

1340 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1341 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1342 c41eea6e Iustin Pop
  shutdown.
1343 a8083063 Iustin Pop

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

1348 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1349 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1350 10c2650b Iustin Pop
      shutdown
1351 c26a6bd2 Iustin Pop
  @rtype: None
1352 10c2650b Iustin Pop

1353 a8083063 Iustin Pop
  """
1354 cacfd1fd Iustin Pop
  msgs = []
1355 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1356 a8083063 Iustin Pop
  if r_dev is not None:
1357 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1358 cacfd1fd Iustin Pop
    try:
1359 746f7476 Iustin Pop
      r_dev.Shutdown()
1360 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1361 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1362 cacfd1fd Iustin Pop
      msgs.append(str(err))
1363 746f7476 Iustin Pop
1364 a8083063 Iustin Pop
  if disk.children:
1365 a8083063 Iustin Pop
    for child in disk.children:
1366 c26a6bd2 Iustin Pop
      try:
1367 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1368 c26a6bd2 Iustin Pop
      except RPCFail, err:
1369 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1370 746f7476 Iustin Pop
1371 c26a6bd2 Iustin Pop
  if msgs:
1372 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1373 a8083063 Iustin Pop
1374 a8083063 Iustin Pop
1375 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1376 153d9724 Iustin Pop
  """Extend a mirrored block device.
1377 a8083063 Iustin Pop

1378 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1379 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1380 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1381 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1382 c26a6bd2 Iustin Pop
  @rtype: None
1383 10c2650b Iustin Pop

1384 a8083063 Iustin Pop
  """
1385 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1386 153d9724 Iustin Pop
  if parent_bdev is None:
1387 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1388 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1389 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1390 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1391 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1392 a8083063 Iustin Pop
1393 a8083063 Iustin Pop
1394 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1395 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1396 a8083063 Iustin Pop

1397 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1398 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1399 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1400 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1401 c26a6bd2 Iustin Pop
  @rtype: None
1402 10c2650b Iustin Pop

1403 a8083063 Iustin Pop
  """
1404 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1405 153d9724 Iustin Pop
  if parent_bdev is None:
1406 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1407 e739bd57 Iustin Pop
  devs = []
1408 e739bd57 Iustin Pop
  for disk in new_cdevs:
1409 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1410 e739bd57 Iustin Pop
    if rpath is None:
1411 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1412 e739bd57 Iustin Pop
      if bd is None:
1413 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1414 e739bd57 Iustin Pop
      else:
1415 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1416 e739bd57 Iustin Pop
    else:
1417 e739bd57 Iustin Pop
      devs.append(rpath)
1418 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1419 a8083063 Iustin Pop
1420 a8083063 Iustin Pop
1421 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1422 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1423 a8083063 Iustin Pop

1424 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1425 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1426 10c2650b Iustin Pop
  @rtype: disk
1427 10c2650b Iustin Pop
  @return:
1428 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1429 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1430 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1431 10c2650b Iustin Pop
      found
1432 a8083063 Iustin Pop

1433 a8083063 Iustin Pop
  """
1434 a8083063 Iustin Pop
  stats = []
1435 a8083063 Iustin Pop
  for dsk in disks:
1436 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1437 a8083063 Iustin Pop
    if rbd is None:
1438 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1439 96acbc09 Michael Hanselmann
1440 36145b12 Michael Hanselmann
    stats.append(rbd.CombinedSyncStatus())
1441 96acbc09 Michael Hanselmann
1442 c26a6bd2 Iustin Pop
  return stats
1443 a8083063 Iustin Pop
1444 a8083063 Iustin Pop
1445 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1446 a8083063 Iustin Pop
  """Check if a device is activated.
1447 a8083063 Iustin Pop

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

1450 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1451 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1452 a8083063 Iustin Pop

1453 10c2650b Iustin Pop
  @return: None if the device can't be found,
1454 10c2650b Iustin Pop
      otherwise the device instance
1455 a8083063 Iustin Pop

1456 a8083063 Iustin Pop
  """
1457 a8083063 Iustin Pop
  children = []
1458 a8083063 Iustin Pop
  if disk.children:
1459 a8083063 Iustin Pop
    for chdisk in disk.children:
1460 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1461 a8083063 Iustin Pop
1462 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1463 a8083063 Iustin Pop
1464 a8083063 Iustin Pop
1465 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1466 a8083063 Iustin Pop
  """Check if a device is activated.
1467 a8083063 Iustin Pop

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

1470 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1471 10c2650b Iustin Pop
  @param disk: the disk to find
1472 96acbc09 Michael Hanselmann
  @rtype: None or objects.BlockDevStatus
1473 96acbc09 Michael Hanselmann
  @return: None if the disk cannot be found, otherwise a the current
1474 96acbc09 Michael Hanselmann
           information
1475 a8083063 Iustin Pop

1476 a8083063 Iustin Pop
  """
1477 23829f6f Iustin Pop
  try:
1478 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1479 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1480 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1481 96acbc09 Michael Hanselmann
1482 a8083063 Iustin Pop
  if rbd is None:
1483 c26a6bd2 Iustin Pop
    return None
1484 96acbc09 Michael Hanselmann
1485 96acbc09 Michael Hanselmann
  return rbd.GetSyncStatus()
1486 a8083063 Iustin Pop
1487 a8083063 Iustin Pop
1488 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1489 968a7623 Iustin Pop
  """Computes the size of the given disks.
1490 968a7623 Iustin Pop

1491 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
1492 968a7623 Iustin Pop

1493 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
1494 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
1495 968a7623 Iustin Pop
  @rtype: list
1496 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
1497 968a7623 Iustin Pop
      otherwise the size
1498 968a7623 Iustin Pop

1499 968a7623 Iustin Pop
  """
1500 968a7623 Iustin Pop
  result = []
1501 968a7623 Iustin Pop
  for cf in disks:
1502 968a7623 Iustin Pop
    try:
1503 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
1504 968a7623 Iustin Pop
    except errors.BlockDeviceError, err:
1505 968a7623 Iustin Pop
      result.append(None)
1506 968a7623 Iustin Pop
      continue
1507 968a7623 Iustin Pop
    if rbd is None:
1508 968a7623 Iustin Pop
      result.append(None)
1509 968a7623 Iustin Pop
    else:
1510 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
1511 968a7623 Iustin Pop
  return result
1512 968a7623 Iustin Pop
1513 968a7623 Iustin Pop
1514 858f3d18 Iustin Pop
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1515 858f3d18 Iustin Pop
  """Export a block device to a remote node.
1516 858f3d18 Iustin Pop

1517 858f3d18 Iustin Pop
  @type disk: L{objects.Disk}
1518 858f3d18 Iustin Pop
  @param disk: the description of the disk to export
1519 858f3d18 Iustin Pop
  @type dest_node: str
1520 858f3d18 Iustin Pop
  @param dest_node: the destination node to export to
1521 858f3d18 Iustin Pop
  @type dest_path: str
1522 858f3d18 Iustin Pop
  @param dest_path: the destination path on the target node
1523 858f3d18 Iustin Pop
  @type cluster_name: str
1524 858f3d18 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1525 858f3d18 Iustin Pop
  @rtype: None
1526 858f3d18 Iustin Pop

1527 858f3d18 Iustin Pop
  """
1528 858f3d18 Iustin Pop
  real_disk = _RecursiveFindBD(disk)
1529 858f3d18 Iustin Pop
  if real_disk is None:
1530 858f3d18 Iustin Pop
    _Fail("Block device '%s' is not set up", disk)
1531 858f3d18 Iustin Pop
1532 858f3d18 Iustin Pop
  real_disk.Open()
1533 858f3d18 Iustin Pop
1534 858f3d18 Iustin Pop
  # the block size on the read dd is 1MiB to match our units
1535 858f3d18 Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1536 858f3d18 Iustin Pop
                               "dd if=%s bs=1048576 count=%s",
1537 858f3d18 Iustin Pop
                               real_disk.dev_path, str(disk.size))
1538 858f3d18 Iustin Pop
1539 858f3d18 Iustin Pop
  # we set here a smaller block size as, due to ssh buffering, more
1540 858f3d18 Iustin Pop
  # than 64-128k will mostly ignored; we use nocreat to fail if the
1541 858f3d18 Iustin Pop
  # device is not already there or we pass a wrong path; we use
1542 858f3d18 Iustin Pop
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
1543 858f3d18 Iustin Pop
  # to not buffer too much memory; this means that at best, we flush
1544 858f3d18 Iustin Pop
  # every 64k, which will not be very fast
1545 858f3d18 Iustin Pop
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
1546 858f3d18 Iustin Pop
                                " oflag=dsync", dest_path)
1547 858f3d18 Iustin Pop
1548 858f3d18 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1549 858f3d18 Iustin Pop
                                                   constants.GANETI_RUNAS,
1550 858f3d18 Iustin Pop
                                                   destcmd)
1551 858f3d18 Iustin Pop
1552 858f3d18 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1553 858f3d18 Iustin Pop
  command = '|'.join([expcmd, utils.ShellQuoteArgs(remotecmd)])
1554 858f3d18 Iustin Pop
1555 858f3d18 Iustin Pop
  result = utils.RunCmd(["bash", "-c", command])
1556 858f3d18 Iustin Pop
1557 858f3d18 Iustin Pop
  if result.failed:
1558 858f3d18 Iustin Pop
    _Fail("Disk copy command '%s' returned error: %s"
1559 858f3d18 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1560 858f3d18 Iustin Pop
1561 858f3d18 Iustin Pop
1562 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1563 a8083063 Iustin Pop
  """Write a file to the filesystem.
1564 a8083063 Iustin Pop

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

1568 10c2650b Iustin Pop
  @type file_name: str
1569 10c2650b Iustin Pop
  @param file_name: the target file name
1570 10c2650b Iustin Pop
  @type data: str
1571 10c2650b Iustin Pop
  @param data: the new contents of the file
1572 10c2650b Iustin Pop
  @type mode: int
1573 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1574 10c2650b Iustin Pop
  @type uid: int
1575 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1576 10c2650b Iustin Pop
  @type gid: int
1577 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1578 10c2650b Iustin Pop
  @type atime: float
1579 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1580 10c2650b Iustin Pop
  @type mtime: float
1581 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1582 c26a6bd2 Iustin Pop
  @rtype: None
1583 10c2650b Iustin Pop

1584 a8083063 Iustin Pop
  """
1585 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1586 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1587 a8083063 Iustin Pop
1588 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
1589 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1590 2cc6781a Iustin Pop
          file_name)
1591 a8083063 Iustin Pop
1592 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1593 12bce260 Michael Hanselmann
1594 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1595 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1596 a8083063 Iustin Pop
1597 386b57af Iustin Pop
1598 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1599 89b14f05 Iustin Pop
  """Update all ssconf files.
1600 89b14f05 Iustin Pop

1601 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1602 89b14f05 Iustin Pop

1603 89b14f05 Iustin Pop
  """
1604 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1605 6ddc95ec Michael Hanselmann
1606 6ddc95ec Michael Hanselmann
1607 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1608 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1609 a8083063 Iustin Pop

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

1614 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1615 10c2650b Iustin Pop
  @param err: the exception to format
1616 a8083063 Iustin Pop

1617 a8083063 Iustin Pop
  """
1618 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1619 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1620 a8083063 Iustin Pop
  else:
1621 a8083063 Iustin Pop
    detail = str(err)
1622 a8083063 Iustin Pop
  return detail
1623 a8083063 Iustin Pop
1624 5d0fe286 Iustin Pop
1625 7ead9575 Guido Trotter
def _OSOndiskAPIVersion(name, os_dir):
1626 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1627 a8083063 Iustin Pop

1628 10c2650b Iustin Pop
  This function will try to read the API version of the OS given by
1629 7c3d51d4 Guido Trotter
  the 'name' parameter and residing in the 'os_dir' directory.
1630 7c3d51d4 Guido Trotter

1631 10c2650b Iustin Pop
  @type name: str
1632 10c2650b Iustin Pop
  @param name: the OS name we should look for
1633 10c2650b Iustin Pop
  @type os_dir: str
1634 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1635 8e70b181 Iustin Pop
  @rtype: tuple
1636 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
1637 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
1638 a8083063 Iustin Pop

1639 a8083063 Iustin Pop
  """
1640 b6b45e0d Guido Trotter
  api_file = os.path.sep.join([os_dir, constants.OS_API_FILE])
1641 a8083063 Iustin Pop
1642 a8083063 Iustin Pop
  try:
1643 a8083063 Iustin Pop
    st = os.stat(api_file)
1644 a8083063 Iustin Pop
  except EnvironmentError, err:
1645 b6b45e0d Guido Trotter
    return False, ("Required file '%s' not found under path %s: %s" %
1646 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1647 a8083063 Iustin Pop
1648 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1649 b6b45e0d Guido Trotter
    return False, ("File '%s' in %s is not a regular file" %
1650 b6b45e0d Guido Trotter
                   (constants.OS_API_FILE, os_dir))
1651 a8083063 Iustin Pop
1652 a8083063 Iustin Pop
  try:
1653 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
1654 a8083063 Iustin Pop
  except EnvironmentError, err:
1655 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
1656 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
1657 a8083063 Iustin Pop
1658 a8083063 Iustin Pop
  try:
1659 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
1660 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1661 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
1662 255dcebd Iustin Pop
                   str(err))
1663 a8083063 Iustin Pop
1664 255dcebd Iustin Pop
  return True, api_versions
1665 a8083063 Iustin Pop
1666 386b57af Iustin Pop
1667 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1668 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1669 a8083063 Iustin Pop

1670 10c2650b Iustin Pop
  @type top_dirs: list
1671 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1672 10c2650b Iustin Pop
      search (if not given defaults to
1673 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1674 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1675 ba00557a Guido Trotter
  @return: a list of tuples (name, path, status, diagnose, variants)
1676 255dcebd Iustin Pop
      for all (potential) OSes under all search paths, where:
1677 255dcebd Iustin Pop
          - name is the (potential) OS name
1678 255dcebd Iustin Pop
          - path is the full path to the OS
1679 255dcebd Iustin Pop
          - status True/False is the validity of the OS
1680 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
1681 ba00557a Guido Trotter
          - variants is a list of supported OS variants, if any
1682 a8083063 Iustin Pop

1683 a8083063 Iustin Pop
  """
1684 7c3d51d4 Guido Trotter
  if top_dirs is None:
1685 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1686 a8083063 Iustin Pop
1687 a8083063 Iustin Pop
  result = []
1688 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1689 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1690 7c3d51d4 Guido Trotter
      try:
1691 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1692 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1693 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1694 7c3d51d4 Guido Trotter
        break
1695 7c3d51d4 Guido Trotter
      for name in f_names:
1696 255dcebd Iustin Pop
        os_path = os.path.sep.join([dir_name, name])
1697 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1698 255dcebd Iustin Pop
        if status:
1699 255dcebd Iustin Pop
          diagnose = ""
1700 ba00557a Guido Trotter
          variants = os_inst.supported_variants
1701 255dcebd Iustin Pop
        else:
1702 255dcebd Iustin Pop
          diagnose = os_inst
1703 ba00557a Guido Trotter
          variants = []
1704 ba00557a Guido Trotter
        result.append((name, os_path, status, diagnose, variants))
1705 a8083063 Iustin Pop
1706 c26a6bd2 Iustin Pop
  return result
1707 a8083063 Iustin Pop
1708 a8083063 Iustin Pop
1709 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
1710 a8083063 Iustin Pop
  """Create an OS instance from disk.
1711 a8083063 Iustin Pop

1712 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1713 8e70b181 Iustin Pop
  valid OS name.
1714 a8083063 Iustin Pop

1715 8ee4dc80 Guido Trotter
  @type base_dir: string
1716 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1717 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1718 255dcebd Iustin Pop
  @rtype: tuple
1719 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
1720 255dcebd Iustin Pop
      or error message
1721 7c3d51d4 Guido Trotter

1722 a8083063 Iustin Pop
  """
1723 56bcd3f4 Guido Trotter
  if base_dir is None:
1724 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1725 c34c0cfd Iustin Pop
    if os_dir is None:
1726 255dcebd Iustin Pop
      return False, "Directory for OS %s not found in search path" % name
1727 c34c0cfd Iustin Pop
  else:
1728 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1729 a8083063 Iustin Pop
1730 7ead9575 Guido Trotter
  status, api_versions = _OSOndiskAPIVersion(name, os_dir)
1731 255dcebd Iustin Pop
  if not status:
1732 255dcebd Iustin Pop
    # push the error up
1733 255dcebd Iustin Pop
    return status, api_versions
1734 a8083063 Iustin Pop
1735 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1736 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1737 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1738 a8083063 Iustin Pop
1739 41ba4061 Guido Trotter
  # OS Files dictionary, we will populate it with the absolute path names
1740 41ba4061 Guido Trotter
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1741 a8083063 Iustin Pop
1742 95075fba Guido Trotter
  if max(api_versions) >= constants.OS_API_V15:
1743 95075fba Guido Trotter
    os_files[constants.OS_VARIANTS_FILE] = ''
1744 95075fba Guido Trotter
1745 ea79fc15 Michael Hanselmann
  for filename in os_files:
1746 ea79fc15 Michael Hanselmann
    os_files[filename] = os.path.sep.join([os_dir, filename])
1747 a8083063 Iustin Pop
1748 a8083063 Iustin Pop
    try:
1749 ea79fc15 Michael Hanselmann
      st = os.stat(os_files[filename])
1750 a8083063 Iustin Pop
    except EnvironmentError, err:
1751 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is missing (%s)" %
1752 ea79fc15 Michael Hanselmann
                     (filename, os_dir, _ErrnoOrStr(err)))
1753 a8083063 Iustin Pop
1754 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1755 41ba4061 Guido Trotter
      return False, ("File '%s' under path '%s' is not a regular file" %
1756 ea79fc15 Michael Hanselmann
                     (filename, os_dir))
1757 255dcebd Iustin Pop
1758 ea79fc15 Michael Hanselmann
    if filename in constants.OS_SCRIPTS:
1759 0757c107 Guido Trotter
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1760 0757c107 Guido Trotter
        return False, ("File '%s' under path '%s' is not executable" %
1761 ea79fc15 Michael Hanselmann
                       (filename, os_dir))
1762 0757c107 Guido Trotter
1763 95075fba Guido Trotter
  variants = None
1764 95075fba Guido Trotter
  if constants.OS_VARIANTS_FILE in os_files:
1765 95075fba Guido Trotter
    variants_file = os_files[constants.OS_VARIANTS_FILE]
1766 95075fba Guido Trotter
    try:
1767 95075fba Guido Trotter
      variants = utils.ReadFile(variants_file).splitlines()
1768 95075fba Guido Trotter
    except EnvironmentError, err:
1769 95075fba Guido Trotter
      return False, ("Error while reading the OS variants file at %s: %s" %
1770 95075fba Guido Trotter
                     (variants_file, _ErrnoOrStr(err)))
1771 95075fba Guido Trotter
    if not variants:
1772 95075fba Guido Trotter
      return False, ("No supported os variant found")
1773 0757c107 Guido Trotter
1774 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
1775 41ba4061 Guido Trotter
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
1776 41ba4061 Guido Trotter
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
1777 41ba4061 Guido Trotter
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
1778 41ba4061 Guido Trotter
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
1779 95075fba Guido Trotter
                      supported_variants=variants,
1780 255dcebd Iustin Pop
                      api_versions=api_versions)
1781 255dcebd Iustin Pop
  return True, os_obj
1782 255dcebd Iustin Pop
1783 255dcebd Iustin Pop
1784 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
1785 255dcebd Iustin Pop
  """Create an OS instance from disk.
1786 255dcebd Iustin Pop

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

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

1794 255dcebd Iustin Pop
  @type base_dir: string
1795 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
1796 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1797 255dcebd Iustin Pop
  @rtype: L{objects.OS}
1798 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
1799 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
1800 255dcebd Iustin Pop

1801 255dcebd Iustin Pop
  """
1802 69b99987 Michael Hanselmann
  name_only = name.split("+", 1)[0]
1803 6ee7102a Guido Trotter
  status, payload = _TryOSFromDisk(name_only, base_dir)
1804 255dcebd Iustin Pop
1805 255dcebd Iustin Pop
  if not status:
1806 255dcebd Iustin Pop
    _Fail(payload)
1807 a8083063 Iustin Pop
1808 255dcebd Iustin Pop
  return payload
1809 a8083063 Iustin Pop
1810 a8083063 Iustin Pop
1811 099c52ad Iustin Pop
def OSEnvironment(instance, inst_os, debug=0):
1812 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1813 2266edb2 Guido Trotter

1814 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1815 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1816 099c52ad Iustin Pop
  @type inst_os: L{objects.OS}
1817 099c52ad Iustin Pop
  @param inst_os: operating system for which the environment is being built
1818 2266edb2 Guido Trotter
  @type debug: integer
1819 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1820 2266edb2 Guido Trotter
  @rtype: dict
1821 2266edb2 Guido Trotter
  @return: dict of environment variables
1822 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1823 10c2650b Iustin Pop
      cannot be found
1824 2266edb2 Guido Trotter

1825 2266edb2 Guido Trotter
  """
1826 2266edb2 Guido Trotter
  result = {}
1827 099c52ad Iustin Pop
  api_version = \
1828 099c52ad Iustin Pop
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
1829 d1a7d66f Guido Trotter
  result['OS_API_VERSION'] = '%d' % api_version
1830 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1831 15552312 Iustin Pop
  result['INSTANCE_OS'] = instance.os
1832 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1833 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1834 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1835 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1836 f11280b5 Guido Trotter
  if api_version >= constants.OS_API_V15:
1837 f11280b5 Guido Trotter
    try:
1838 f11280b5 Guido Trotter
      variant = instance.os.split('+', 1)[1]
1839 f11280b5 Guido Trotter
    except IndexError:
1840 099c52ad Iustin Pop
      variant = inst_os.supported_variants[0]
1841 f11280b5 Guido Trotter
    result['OS_VARIANT'] = variant
1842 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1843 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1844 2266edb2 Guido Trotter
    if real_disk is None:
1845 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1846 2266edb2 Guido Trotter
                                    str(disk))
1847 2266edb2 Guido Trotter
    real_disk.Open()
1848 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1849 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
1850 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1851 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1852 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1853 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1854 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1855 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1856 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1857 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1858 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1859 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1860 2266edb2 Guido Trotter
    if nic.ip:
1861 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1862 1ba9227f Guido Trotter
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1863 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1864 1ba9227f Guido Trotter
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1865 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
1866 1ba9227f Guido Trotter
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1867 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1868 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1869 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1870 2266edb2 Guido Trotter
1871 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1872 67fc3042 Iustin Pop
    for key, value in source.items():
1873 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1874 67fc3042 Iustin Pop
1875 2266edb2 Guido Trotter
  return result
1876 a8083063 Iustin Pop
1877 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
1878 594609c0 Iustin Pop
  """Grow a stack of block devices.
1879 594609c0 Iustin Pop

1880 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1881 10c2650b Iustin Pop
  first ones to resize.
1882 594609c0 Iustin Pop

1883 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1884 10c2650b Iustin Pop
  @param disk: the disk to be grown
1885 10c2650b Iustin Pop
  @rtype: (status, result)
1886 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1887 10c2650b Iustin Pop
      (True/False), and the errors message if status
1888 10c2650b Iustin Pop
      is False
1889 594609c0 Iustin Pop

1890 594609c0 Iustin Pop
  """
1891 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1892 594609c0 Iustin Pop
  if r_dev is None:
1893 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
1894 594609c0 Iustin Pop
1895 594609c0 Iustin Pop
  try:
1896 594609c0 Iustin Pop
    r_dev.Grow(amount)
1897 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1898 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
1899 594609c0 Iustin Pop
1900 594609c0 Iustin Pop
1901 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
1902 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1903 a8083063 Iustin Pop

1904 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1905 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1906 a8083063 Iustin Pop

1907 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1908 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1909 e9e9263d Guido Trotter
  @rtype: string
1910 e9e9263d Guido Trotter
  @return: snapshot disk path
1911 a8083063 Iustin Pop

1912 098c0958 Michael Hanselmann
  """
1913 a8083063 Iustin Pop
  if disk.children:
1914 a8083063 Iustin Pop
    if len(disk.children) == 1:
1915 a8083063 Iustin Pop
      # only one child, let's recurse on it
1916 821d1bd1 Iustin Pop
      return BlockdevSnapshot(disk.children[0])
1917 a8083063 Iustin Pop
    else:
1918 a8083063 Iustin Pop
      # more than one child, choose one that matches
1919 a8083063 Iustin Pop
      for child in disk.children:
1920 a8083063 Iustin Pop
        if child.size == disk.size:
1921 a8083063 Iustin Pop
          # return implies breaking the loop
1922 821d1bd1 Iustin Pop
          return BlockdevSnapshot(child)
1923 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1924 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1925 a8083063 Iustin Pop
    if r_dev is not None:
1926 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1927 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
1928 a8083063 Iustin Pop
    else:
1929 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
1930 a8083063 Iustin Pop
  else:
1931 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1932 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
1933 a8083063 Iustin Pop
1934 a8083063 Iustin Pop
1935 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1936 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1937 a8083063 Iustin Pop

1938 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1939 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1940 74c47259 Iustin Pop
  @type dest_node: str
1941 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1942 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1943 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1944 74c47259 Iustin Pop
  @type cluster_name: str
1945 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1946 74c47259 Iustin Pop
  @type idx: int
1947 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1948 74c47259 Iustin Pop
      used to export to the OS scripts environment
1949 c26a6bd2 Iustin Pop
  @rtype: None
1950 a8083063 Iustin Pop

1951 098c0958 Michael Hanselmann
  """
1952 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1953 d1a7d66f Guido Trotter
  export_env = OSEnvironment(instance, inst_os)
1954 d1a7d66f Guido Trotter
1955 a8083063 Iustin Pop
  export_script = inst_os.export_script
1956 a8083063 Iustin Pop
1957 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1958 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1959 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1960 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1961 0607699d Guido Trotter
  real_disk = _RecursiveFindBD(disk)
1962 0607699d Guido Trotter
  if real_disk is None:
1963 ba55d062 Iustin Pop
    _Fail("Block device '%s' is not set up", disk)
1964 ba55d062 Iustin Pop
1965 0607699d Guido Trotter
  real_disk.Open()
1966 0607699d Guido Trotter
1967 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1968 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
1969 a8083063 Iustin Pop
1970 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1971 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1972 a8083063 Iustin Pop
1973 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1974 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1975 a8083063 Iustin Pop
  # valid parameters
1976 a48b08bf Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
1977 a48b08bf Iustin Pop
                               inst_os.path, export_script, logfile)
1978 a8083063 Iustin Pop
1979 a8083063 Iustin Pop
  comprcmd = "gzip"
1980 a8083063 Iustin Pop
1981 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1982 00003458 Guido Trotter
                                destdir, destdir, destfile)
1983 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1984 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1985 62c9ec92 Iustin Pop
                                                   destcmd)
1986 a8083063 Iustin Pop
1987 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1988 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1989 a8083063 Iustin Pop
1990 a48b08bf Iustin Pop
  result = utils.RunCmd(["bash", "-c", command], env=export_env)
1991 a8083063 Iustin Pop
1992 a8083063 Iustin Pop
  if result.failed:
1993 ba55d062 Iustin Pop
    _Fail("OS snapshot export command '%s' returned error: %s"
1994 ba55d062 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1995 a8083063 Iustin Pop
1996 a8083063 Iustin Pop
1997 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1998 a8083063 Iustin Pop
  """Write out the export configuration information.
1999 a8083063 Iustin Pop

2000 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
2001 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
2002 10c2650b Iustin Pop
      saving configuration
2003 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
2004 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
2005 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
2006 a8083063 Iustin Pop

2007 c26a6bd2 Iustin Pop
  @rtype: None
2008 a8083063 Iustin Pop

2009 098c0958 Michael Hanselmann
  """
2010 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
2011 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
2012 a8083063 Iustin Pop
2013 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2014 a8083063 Iustin Pop
2015 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
2016 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
2017 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2018 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2019 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
2020 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
2021 a8083063 Iustin Pop
2022 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
2023 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
2024 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
2025 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
2026 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
2027 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
2028 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2029 66f93869 Manuel Franceschini
2030 95268cc3 Iustin Pop
  nic_total = 0
2031 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
2032 95268cc3 Iustin Pop
    nic_total += 1
2033 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2034 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
2035 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2036 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
2037 38206f3c Iustin Pop
               '%s' % nic.bridge)
2038 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
2039 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2040 a8083063 Iustin Pop
2041 726d7d68 Iustin Pop
  disk_total = 0
2042 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
2043 19d7f90a Guido Trotter
    if disk:
2044 726d7d68 Iustin Pop
      disk_total += 1
2045 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2046 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
2047 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2048 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
2049 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2050 19d7f90a Guido Trotter
                 ('%d' % disk.size))
2051 a8083063 Iustin Pop
2052 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2053 a8083063 Iustin Pop
2054 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
2055 726d7d68 Iustin Pop
                  data=config.Dumps())
2056 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
2057 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
2058 a8083063 Iustin Pop
2059 a8083063 Iustin Pop
2060 a8083063 Iustin Pop
def ExportInfo(dest):
2061 a8083063 Iustin Pop
  """Get export configuration information.
2062 a8083063 Iustin Pop

2063 10c2650b Iustin Pop
  @type dest: str
2064 10c2650b Iustin Pop
  @param dest: directory containing the export
2065 a8083063 Iustin Pop

2066 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
2067 10c2650b Iustin Pop
  @return: a serializable config file containing the
2068 10c2650b Iustin Pop
      export info
2069 a8083063 Iustin Pop

2070 a8083063 Iustin Pop
  """
2071 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
2072 a8083063 Iustin Pop
2073 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
2074 a8083063 Iustin Pop
  config.read(cff)
2075 a8083063 Iustin Pop
2076 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
2077 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
2078 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
2079 a8083063 Iustin Pop
2080 c26a6bd2 Iustin Pop
  return config.Dumps()
2081 a8083063 Iustin Pop
2082 a8083063 Iustin Pop
2083 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
2084 a8083063 Iustin Pop
  """Import an os image into an instance.
2085 a8083063 Iustin Pop

2086 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
2087 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
2088 6c0af70e Guido Trotter
  @type src_node: string
2089 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
2090 6c0af70e Guido Trotter
  @type src_images: list of string
2091 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
2092 6c0af70e Guido Trotter
  @rtype: list of boolean
2093 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
2094 a8083063 Iustin Pop

2095 a8083063 Iustin Pop
  """
2096 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
2097 d1a7d66f Guido Trotter
  import_env = OSEnvironment(instance, inst_os)
2098 a8083063 Iustin Pop
  import_script = inst_os.import_script
2099 a8083063 Iustin Pop
2100 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
2101 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
2102 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
2103 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
2104 a8083063 Iustin Pop
2105 a8083063 Iustin Pop
  comprcmd = "gunzip"
2106 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
2107 d868edb4 Iustin Pop
                               import_script, logfile)
2108 a8083063 Iustin Pop
2109 6c0af70e Guido Trotter
  final_result = []
2110 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
2111 6c0af70e Guido Trotter
    if image:
2112 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
2113 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
2114 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
2115 6c0af70e Guido Trotter
                                                       destcmd)
2116 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
2117 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
2118 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
2119 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
2120 6c0af70e Guido Trotter
      if result.failed:
2121 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
2122 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
2123 726d7d68 Iustin Pop
                      result.output)
2124 944bf548 Iustin Pop
        final_result.append("error importing disk %d: %s, %s" %
2125 944bf548 Iustin Pop
                            (idx, result.fail_reason, result.output[-100]))
2126 a8083063 Iustin Pop
2127 944bf548 Iustin Pop
  if final_result:
2128 afdc3985 Iustin Pop
    _Fail("; ".join(final_result), log=False)
2129 a8083063 Iustin Pop
2130 a8083063 Iustin Pop
2131 a8083063 Iustin Pop
def ListExports():
2132 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2133 098c0958 Michael Hanselmann

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2352 af5ebcb1 Michael Hanselmann
  """
2353 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2354 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2355 af5ebcb1 Michael Hanselmann
2356 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2357 af5ebcb1 Michael Hanselmann
2358 af5ebcb1 Michael Hanselmann
2359 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2360 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2361 5d672980 Iustin Pop

2362 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2363 5d672980 Iustin Pop

2364 10c2650b Iustin Pop
  @type drain_flag: boolean
2365 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2366 c8457ce7 Iustin Pop
  @rtype: truple
2367 c8457ce7 Iustin Pop
  @return: always True, None
2368 10c2650b Iustin Pop
  @warning: the function always returns True
2369 5d672980 Iustin Pop

2370 5d672980 Iustin Pop
  """
2371 5d672980 Iustin Pop
  if drain_flag:
2372 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2373 5d672980 Iustin Pop
  else:
2374 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2375 5d672980 Iustin Pop
2376 5d672980 Iustin Pop
2377 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2378 d61cbe76 Iustin Pop
  """Closes the given block devices.
2379 d61cbe76 Iustin Pop

2380 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2381 10c2650b Iustin Pop
  DRBD).
2382 10c2650b Iustin Pop

2383 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2384 b2e7666a Iustin Pop
      of this instance will be removed
2385 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2386 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2387 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2388 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2389 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2390 10c2650b Iustin Pop
      which will contain the error details in case we
2391 10c2650b Iustin Pop
      failed
2392 d61cbe76 Iustin Pop

2393 d61cbe76 Iustin Pop
  """
2394 d61cbe76 Iustin Pop
  bdevs = []
2395 d61cbe76 Iustin Pop
  for cf in disks:
2396 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2397 d61cbe76 Iustin Pop
    if rd is None:
2398 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2399 d61cbe76 Iustin Pop
    bdevs.append(rd)
2400 d61cbe76 Iustin Pop
2401 d61cbe76 Iustin Pop
  msg = []
2402 d61cbe76 Iustin Pop
  for rd in bdevs:
2403 d61cbe76 Iustin Pop
    try:
2404 d61cbe76 Iustin Pop
      rd.Close()
2405 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2406 d61cbe76 Iustin Pop
      msg.append(str(err))
2407 d61cbe76 Iustin Pop
  if msg:
2408 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2409 d61cbe76 Iustin Pop
  else:
2410 b2e7666a Iustin Pop
    if instance_name:
2411 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2412 d61cbe76 Iustin Pop
2413 d61cbe76 Iustin Pop
2414 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2415 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2416 6217e295 Iustin Pop

2417 6217e295 Iustin Pop
  @type hvname: string
2418 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2419 6217e295 Iustin Pop
  @type hvparams: dict
2420 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2421 c26a6bd2 Iustin Pop
  @rtype: None
2422 6217e295 Iustin Pop

2423 6217e295 Iustin Pop
  """
2424 6217e295 Iustin Pop
  try:
2425 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2426 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2427 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2428 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2429 6217e295 Iustin Pop
2430 6217e295 Iustin Pop
2431 56aa9fd5 Iustin Pop
def DemoteFromMC():
2432 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2433 56aa9fd5 Iustin Pop

2434 56aa9fd5 Iustin Pop
  """
2435 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2436 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2437 56aa9fd5 Iustin Pop
  if master == myself:
2438 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2439 f154a7a3 Michael Hanselmann
2440 f154a7a3 Michael Hanselmann
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2441 f154a7a3 Michael Hanselmann
  if not result.failed:
2442 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2443 f154a7a3 Michael Hanselmann
2444 56aa9fd5 Iustin Pop
  try:
2445 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2446 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2447 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2448 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2449 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2450 f154a7a3 Michael Hanselmann
2451 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2452 56aa9fd5 Iustin Pop
2453 56aa9fd5 Iustin Pop
2454 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2455 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2456 6b93ec9d Iustin Pop

2457 6b93ec9d Iustin Pop
  """
2458 6b93ec9d Iustin Pop
  # set the correct physical ID
2459 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2460 6b93ec9d Iustin Pop
  for cf in disks:
2461 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2462 6b93ec9d Iustin Pop
2463 6b93ec9d Iustin Pop
  bdevs = []
2464 6b93ec9d Iustin Pop
2465 6b93ec9d Iustin Pop
  for cf in disks:
2466 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2467 6b93ec9d Iustin Pop
    if rd is None:
2468 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
2469 6b93ec9d Iustin Pop
    bdevs.append(rd)
2470 5a533f8a Iustin Pop
  return bdevs
2471 6b93ec9d Iustin Pop
2472 6b93ec9d Iustin Pop
2473 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2474 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2475 6b93ec9d Iustin Pop

2476 6b93ec9d Iustin Pop
  """
2477 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2478 6b93ec9d Iustin Pop
2479 6b93ec9d Iustin Pop
  # disconnect disks
2480 6b93ec9d Iustin Pop
  for rd in bdevs:
2481 6b93ec9d Iustin Pop
    try:
2482 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2483 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2484 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
2485 2cc6781a Iustin Pop
            err, exc=True)
2486 6b93ec9d Iustin Pop
2487 6b93ec9d Iustin Pop
2488 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2489 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2490 6b93ec9d Iustin Pop

2491 6b93ec9d Iustin Pop
  """
2492 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2493 6b93ec9d Iustin Pop
2494 6b93ec9d Iustin Pop
  if multimaster:
2495 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2496 6b93ec9d Iustin Pop
      try:
2497 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2498 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2499 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
2500 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2501 6b93ec9d Iustin Pop
  # needed primary mode
2502 6b93ec9d Iustin Pop
  for rd in bdevs:
2503 6b93ec9d Iustin Pop
    try:
2504 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2505 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2506 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
2507 3c0cdc83 Michael Hanselmann
2508 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2509 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2510 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2511 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2512 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2513 3c0cdc83 Michael Hanselmann
2514 3c0cdc83 Michael Hanselmann
  def _Attach():
2515 6b93ec9d Iustin Pop
    all_connected = True
2516 3c0cdc83 Michael Hanselmann
2517 6b93ec9d Iustin Pop
    for rd in bdevs:
2518 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2519 3c0cdc83 Michael Hanselmann
2520 3c0cdc83 Michael Hanselmann
      all_connected = (all_connected and
2521 3c0cdc83 Michael Hanselmann
                       (stats.is_connected or stats.is_in_resync))
2522 3c0cdc83 Michael Hanselmann
2523 6b93ec9d Iustin Pop
      if stats.is_standalone:
2524 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2525 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2526 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2527 6b93ec9d Iustin Pop
        try:
2528 c738375b Iustin Pop
          rd.AttachNet(multimaster)
2529 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2530 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
2531 3c0cdc83 Michael Hanselmann
2532 3c0cdc83 Michael Hanselmann
    if not all_connected:
2533 3c0cdc83 Michael Hanselmann
      raise utils.RetryAgain()
2534 3c0cdc83 Michael Hanselmann
2535 3c0cdc83 Michael Hanselmann
  try:
2536 3c0cdc83 Michael Hanselmann
    # Start with a delay of 100 miliseconds and go up to 5 seconds
2537 3c0cdc83 Michael Hanselmann
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
2538 3c0cdc83 Michael Hanselmann
  except utils.RetryTimeout:
2539 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
2540 3c0cdc83 Michael Hanselmann
2541 6b93ec9d Iustin Pop
  if multimaster:
2542 6b93ec9d Iustin Pop
    # change to primary mode
2543 6b93ec9d Iustin Pop
    for rd in bdevs:
2544 d3da87b8 Iustin Pop
      try:
2545 d3da87b8 Iustin Pop
        rd.Open()
2546 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
2547 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
2548 6b93ec9d Iustin Pop
2549 6b93ec9d Iustin Pop
2550 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2551 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2552 6b93ec9d Iustin Pop

2553 6b93ec9d Iustin Pop
  """
2554 db8667b7 Iustin Pop
  def _helper(rd):
2555 db8667b7 Iustin Pop
    stats = rd.GetProcStatus()
2556 db8667b7 Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2557 db8667b7 Iustin Pop
      raise utils.RetryAgain()
2558 db8667b7 Iustin Pop
    return stats
2559 db8667b7 Iustin Pop
2560 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2561 6b93ec9d Iustin Pop
2562 6b93ec9d Iustin Pop
  min_resync = 100
2563 6b93ec9d Iustin Pop
  alldone = True
2564 6b93ec9d Iustin Pop
  for rd in bdevs:
2565 db8667b7 Iustin Pop
    try:
2566 db8667b7 Iustin Pop
      # poll each second for 15 seconds
2567 db8667b7 Iustin Pop
      stats = utils.Retry(_helper, 1, 15, args=[rd])
2568 db8667b7 Iustin Pop
    except utils.RetryTimeout:
2569 db8667b7 Iustin Pop
      stats = rd.GetProcStatus()
2570 db8667b7 Iustin Pop
      # last check
2571 db8667b7 Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2572 db8667b7 Iustin Pop
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2573 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2574 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2575 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2576 afdc3985 Iustin Pop
2577 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
2578 6b93ec9d Iustin Pop
2579 6b93ec9d Iustin Pop
2580 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
2581 f5118ade Iustin Pop
  """Hard-powercycle the node.
2582 f5118ade Iustin Pop

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

2586 f5118ade Iustin Pop
  """
2587 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2588 f5118ade Iustin Pop
  try:
2589 f5118ade Iustin Pop
    pid = os.fork()
2590 29921401 Iustin Pop
  except OSError:
2591 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
2592 f5118ade Iustin Pop
    pid = 0
2593 f5118ade Iustin Pop
  if pid > 0:
2594 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
2595 f5118ade Iustin Pop
  time.sleep(5)
2596 f5118ade Iustin Pop
  hyper.PowercycleNode()
2597 f5118ade Iustin Pop
2598 f5118ade Iustin Pop
2599 a8083063 Iustin Pop
class HooksRunner(object):
2600 a8083063 Iustin Pop
  """Hook runner.
2601 a8083063 Iustin Pop

2602 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2603 10c2650b Iustin Pop
  on the master side.
2604 a8083063 Iustin Pop

2605 a8083063 Iustin Pop
  """
2606 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2607 a8083063 Iustin Pop
2608 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2609 a8083063 Iustin Pop
    """Constructor for hooks runner.
2610 a8083063 Iustin Pop

2611 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2612 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2613 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2614 a8083063 Iustin Pop

2615 a8083063 Iustin Pop
    """
2616 a8083063 Iustin Pop
    if hooks_base_dir is None:
2617 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2618 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2619 a8083063 Iustin Pop
2620 a8083063 Iustin Pop
  @staticmethod
2621 a8083063 Iustin Pop
  def ExecHook(script, env):
2622 a8083063 Iustin Pop
    """Exec one hook script.
2623 a8083063 Iustin Pop

2624 10c2650b Iustin Pop
    @type script: str
2625 10c2650b Iustin Pop
    @param script: the full path to the script
2626 10c2650b Iustin Pop
    @type env: dict
2627 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2628 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2629 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2630 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2631 10c2650b Iustin Pop
        which will contain the error details in case we
2632 10c2650b Iustin Pop
        failed
2633 a8083063 Iustin Pop

2634 a8083063 Iustin Pop
    """
2635 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2636 a8083063 Iustin Pop
    fdstdin = None
2637 a8083063 Iustin Pop
    try:
2638 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2639 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2640 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2641 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2642 a8083063 Iustin Pop
      output = ""
2643 a8083063 Iustin Pop
      try:
2644 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2645 a8083063 Iustin Pop
        child.stdout.close()
2646 a8083063 Iustin Pop
      except EnvironmentError, err:
2647 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2648 a8083063 Iustin Pop
2649 a8083063 Iustin Pop
      while True:
2650 a8083063 Iustin Pop
        try:
2651 a8083063 Iustin Pop
          result = child.wait()
2652 a8083063 Iustin Pop
          break
2653 a8083063 Iustin Pop
        except EnvironmentError, err:
2654 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2655 a8083063 Iustin Pop
            continue
2656 a8083063 Iustin Pop
          raise
2657 a8083063 Iustin Pop
    finally:
2658 a8083063 Iustin Pop
      # try not to leak fds
2659 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2660 a8083063 Iustin Pop
        if fd is not None:
2661 a8083063 Iustin Pop
          try:
2662 a8083063 Iustin Pop
            fd.close()
2663 a8083063 Iustin Pop
          except EnvironmentError, err:
2664 a8083063 Iustin Pop
            # just log the error
2665 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2666 a8083063 Iustin Pop
            pass
2667 a8083063 Iustin Pop
2668 26f15862 Iustin Pop
    return result == 0, utils.SafeEncode(output.strip())
2669 a8083063 Iustin Pop
2670 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2671 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2672 a8083063 Iustin Pop

2673 10c2650b Iustin Pop
    @type hpath: str
2674 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2675 10c2650b Iustin Pop
        holds the scripts
2676 10c2650b Iustin Pop
    @type phase: str
2677 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2678 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2679 10c2650b Iustin Pop
    @type env: dict
2680 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2681 10c2650b Iustin Pop
    @rtype: list
2682 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2683 10c2650b Iustin Pop
      - script path
2684 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2685 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2686 10c2650b Iustin Pop
      - output of the script
2687 10c2650b Iustin Pop

2688 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2689 10c2650b Iustin Pop
        parameters
2690 a8083063 Iustin Pop

2691 a8083063 Iustin Pop
    """
2692 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2693 a8083063 Iustin Pop
      suffix = "pre"
2694 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2695 a8083063 Iustin Pop
      suffix = "post"
2696 a8083063 Iustin Pop
    else:
2697 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
2698 3fb4f740 Iustin Pop
2699 a8083063 Iustin Pop
    rr = []
2700 a8083063 Iustin Pop
2701 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2702 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2703 a8083063 Iustin Pop
    try:
2704 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2705 29921401 Iustin Pop
    except OSError:
2706 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2707 c26a6bd2 Iustin Pop
      return rr
2708 a8083063 Iustin Pop
2709 a8083063 Iustin Pop
    # we use the standard python sort order,
2710 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2711 a8083063 Iustin Pop
    dir_contents.sort()
2712 a8083063 Iustin Pop
    for relname in dir_contents:
2713 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2714 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2715 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2716 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2717 a8083063 Iustin Pop
        output = ""
2718 a8083063 Iustin Pop
      else:
2719 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2720 a8083063 Iustin Pop
        if not result:
2721 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2722 a8083063 Iustin Pop
        else:
2723 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2724 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2725 a8083063 Iustin Pop
2726 c26a6bd2 Iustin Pop
    return rr
2727 3f78eef2 Iustin Pop
2728 3f78eef2 Iustin Pop
2729 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2730 8d528b7c Iustin Pop
  """IAllocator runner.
2731 8d528b7c Iustin Pop

2732 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2733 8d528b7c Iustin Pop
  the master side.
2734 8d528b7c Iustin Pop

2735 8d528b7c Iustin Pop
  """
2736 8d528b7c Iustin Pop
  def Run(self, name, idata):
2737 8d528b7c Iustin Pop
    """Run an iallocator script.
2738 8d528b7c Iustin Pop

2739 10c2650b Iustin Pop
    @type name: str
2740 10c2650b Iustin Pop
    @param name: the iallocator script name
2741 10c2650b Iustin Pop
    @type idata: str
2742 10c2650b Iustin Pop
    @param idata: the allocator input data
2743 10c2650b Iustin Pop

2744 10c2650b Iustin Pop
    @rtype: tuple
2745 87f5c298 Iustin Pop
    @return: two element tuple of:
2746 87f5c298 Iustin Pop
       - status
2747 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
2748 8d528b7c Iustin Pop

2749 8d528b7c Iustin Pop
    """
2750 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2751 8d528b7c Iustin Pop
                                  os.path.isfile)
2752 8d528b7c Iustin Pop
    if alloc_script is None:
2753 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
2754 8d528b7c Iustin Pop
2755 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2756 8d528b7c Iustin Pop
    try:
2757 8d528b7c Iustin Pop
      os.write(fd, idata)
2758 8d528b7c Iustin Pop
      os.close(fd)
2759 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2760 8d528b7c Iustin Pop
      if result.failed:
2761 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2762 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
2763 8d528b7c Iustin Pop
    finally:
2764 8d528b7c Iustin Pop
      os.unlink(fin_name)
2765 8d528b7c Iustin Pop
2766 c26a6bd2 Iustin Pop
    return result.stdout
2767 8d528b7c Iustin Pop
2768 8d528b7c Iustin Pop
2769 3f78eef2 Iustin Pop
class DevCacheManager(object):
2770 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2771 3f78eef2 Iustin Pop

2772 3f78eef2 Iustin Pop
  """
2773 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2774 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2775 3f78eef2 Iustin Pop
2776 3f78eef2 Iustin Pop
  @classmethod
2777 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2778 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2779 3f78eef2 Iustin Pop

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

2783 10c2650b Iustin Pop
    @type dev_path: str
2784 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2785 10c2650b Iustin Pop
    @rtype: str
2786 10c2650b Iustin Pop
    @return: the converted path name
2787 3f78eef2 Iustin Pop

2788 3f78eef2 Iustin Pop
    """
2789 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2790 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2791 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2792 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2793 3f78eef2 Iustin Pop
    return fpath
2794 3f78eef2 Iustin Pop
2795 3f78eef2 Iustin Pop
  @classmethod
2796 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2797 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2798 3f78eef2 Iustin Pop

2799 10c2650b Iustin Pop
    @type dev_path: str
2800 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2801 10c2650b Iustin Pop
    @type owner: str
2802 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2803 10c2650b Iustin Pop
    @type on_primary: bool
2804 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2805 10c2650b Iustin Pop
        node nor not
2806 10c2650b Iustin Pop
    @type iv_name: str
2807 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2808 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2809 10c2650b Iustin Pop

2810 10c2650b Iustin Pop
    @rtype: None
2811 10c2650b Iustin Pop

2812 3f78eef2 Iustin Pop
    """
2813 cf5a8306 Iustin Pop
    if dev_path is None:
2814 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2815 cf5a8306 Iustin Pop
      return
2816 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2817 3f78eef2 Iustin Pop
    if on_primary:
2818 3f78eef2 Iustin Pop
      state = "primary"
2819 3f78eef2 Iustin Pop
    else:
2820 3f78eef2 Iustin Pop
      state = "secondary"
2821 3f78eef2 Iustin Pop
    if iv_name is None:
2822 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2823 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2824 3f78eef2 Iustin Pop
    try:
2825 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2826 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2827 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2828 3f78eef2 Iustin Pop
2829 3f78eef2 Iustin Pop
  @classmethod
2830 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2831 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2832 3f78eef2 Iustin Pop

2833 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2834 10c2650b Iustin Pop
    path name and logging.
2835 10c2650b Iustin Pop

2836 10c2650b Iustin Pop
    @type dev_path: str
2837 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2838 10c2650b Iustin Pop

2839 10c2650b Iustin Pop
    @rtype: None
2840 10c2650b Iustin Pop

2841 3f78eef2 Iustin Pop
    """
2842 cf5a8306 Iustin Pop
    if dev_path is None:
2843 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2844 cf5a8306 Iustin Pop
      return
2845 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2846 3f78eef2 Iustin Pop
    try:
2847 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2848 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2849 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)