Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 4a34c5cf

History | View | Annotate | Download (80.6 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 2cc6781a Iustin Pop
class RPCFail(Exception):
55 2cc6781a Iustin Pop
  """Class denoting RPC failure.
56 2cc6781a Iustin Pop

57 2cc6781a Iustin Pop
  Its argument is the error message.
58 2cc6781a Iustin Pop

59 2cc6781a Iustin Pop
  """
60 2cc6781a Iustin Pop
61 2cc6781a Iustin Pop
def _Fail(msg, *args, **kwargs):
62 2cc6781a Iustin Pop
  """Log an error and the raise an RPCFail exception.
63 2cc6781a Iustin Pop

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

69 2cc6781a Iustin Pop
  @type msg: string
70 2cc6781a Iustin Pop
  @param msg: the text of the exception
71 2cc6781a Iustin Pop
  @raise RPCFail
72 2cc6781a Iustin Pop

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

87 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
88 93384844 Iustin Pop
  @return: a SimpleStore instance
89 10c2650b Iustin Pop

90 10c2650b Iustin Pop
  """
91 93384844 Iustin Pop
  return ssconf.SimpleStore()
92 c657dcc9 Michael Hanselmann
93 c657dcc9 Michael Hanselmann
94 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
95 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
96 10c2650b Iustin Pop

97 10c2650b Iustin Pop
  @type cluster_name: str
98 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
99 10c2650b Iustin Pop
      by the SshRunner constructor
100 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
101 10c2650b Iustin Pop
  @return: an SshRunner instance
102 10c2650b Iustin Pop

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

110 12bce260 Michael Hanselmann
  @type data: list or tuple
111 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
112 12bce260 Michael Hanselmann
  @rtype: str
113 12bce260 Michael Hanselmann
  @return: Decompressed data
114 12bce260 Michael Hanselmann

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

130 10c2650b Iustin Pop
  @type path: str
131 10c2650b Iustin Pop
  @param path: the directory to clean
132 76ab5558 Michael Hanselmann
  @type exclude: list
133 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
134 10c2650b Iustin Pop
      to the empty list
135 76ab5558 Michael Hanselmann

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

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

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

182 c8457ce7 Iustin Pop
  @rtype: tuple
183 c8457ce7 Iustin Pop
  @return: True, None
184 24fc781f Michael Hanselmann

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

193 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
194 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
195 bd1e4562 Iustin Pop

196 bd1e4562 Iustin Pop
  @rtype: tuple
197 c26a6bd2 Iustin Pop
  @return: master_netdev, master_ip, master_name
198 2a52a064 Iustin Pop
  @raise RPCFail: in case of errors
199 b1b6ea87 Iustin Pop

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

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

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

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

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

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

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

308 7900ed01 Iustin Pop
  This does the following:
309 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
310 7900ed01 Iustin Pop
      - adds the ssh private key to the user
311 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
312 a8083063 Iustin Pop

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

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

353 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
354 10c2650b Iustin Pop
  from the cluster.
355 10c2650b Iustin Pop

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

360 a8083063 Iustin Pop
  """
361 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
362 1bc59f76 Michael Hanselmann
  JobQueuePurge()
363 f78346f5 Michael Hanselmann
364 70d9e3d8 Iustin Pop
  try:
365 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
366 7900ed01 Iustin Pop
367 0623d351 Iustin Pop
    f = open(pub_key, 'r')
368 0623d351 Iustin Pop
    try:
369 0623d351 Iustin Pop
      utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
370 0623d351 Iustin Pop
    finally:
371 0623d351 Iustin Pop
      f.close()
372 a8083063 Iustin Pop
373 0623d351 Iustin Pop
    utils.RemoveFile(priv_key)
374 0623d351 Iustin Pop
    utils.RemoveFile(pub_key)
375 0623d351 Iustin Pop
  except errors.OpExecError:
376 0623d351 Iustin Pop
    logging.exception("Error while processing ssh files")
377 a8083063 Iustin Pop
378 0623d351 Iustin Pop
  # Raise a custom exception (handled in ganeti-noded)
379 0623d351 Iustin Pop
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
380 6d8b6238 Guido Trotter
381 a8083063 Iustin Pop
382 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
383 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
384 a8083063 Iustin Pop

385 e69d05fd Iustin Pop
  @type vgname: C{string}
386 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
387 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
388 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
389 e69d05fd Iustin Pop
      memory information
390 e69d05fd Iustin Pop
  @rtype: C{dict}
391 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
392 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
393 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
394 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
395 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
396 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
397 a8083063 Iustin Pop

398 098c0958 Michael Hanselmann
  """
399 a8083063 Iustin Pop
  outputarray = {}
400 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
401 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
402 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
403 a8083063 Iustin Pop
404 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
405 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
406 a8083063 Iustin Pop
  if hyp_info is not None:
407 a8083063 Iustin Pop
    outputarray.update(hyp_info)
408 a8083063 Iustin Pop
409 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
410 3ef10550 Michael Hanselmann
  try:
411 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
412 3ef10550 Michael Hanselmann
  finally:
413 3ef10550 Michael Hanselmann
    f.close()
414 3ef10550 Michael Hanselmann
415 c26a6bd2 Iustin Pop
  return outputarray
416 a8083063 Iustin Pop
417 a8083063 Iustin Pop
418 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
419 a8083063 Iustin Pop
  """Verify the status of the local node.
420 a8083063 Iustin Pop

421 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
422 e69d05fd Iustin Pop
  local node.
423 e69d05fd Iustin Pop

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

427 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
428 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
429 e69d05fd Iustin Pop
  report).
430 a8083063 Iustin Pop

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

435 e69d05fd Iustin Pop
  @type what: C{dict}
436 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
437 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
438 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
439 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
440 e69d05fd Iustin Pop
        connectivity with
441 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
442 10c2650b Iustin Pop
  @rtype: dict
443 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
444 10c2650b Iustin Pop
      values representing the result of the checks
445 a8083063 Iustin Pop

446 a8083063 Iustin Pop
  """
447 a8083063 Iustin Pop
  result = {}
448 a8083063 Iustin Pop
449 25361b9a Iustin Pop
  if constants.NV_HYPERVISOR in what:
450 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
451 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
452 25361b9a Iustin Pop
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
453 25361b9a Iustin Pop
454 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
455 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
456 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
457 25361b9a Iustin Pop
458 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
459 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
460 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
461 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
462 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
463 a8083063 Iustin Pop
      if not success:
464 25361b9a Iustin Pop
        tmp[node] = message
465 25361b9a Iustin Pop
466 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
467 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
468 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
469 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
470 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
471 9d4bfc96 Iustin Pop
      if name == my_name:
472 9d4bfc96 Iustin Pop
        my_pip = pip
473 9d4bfc96 Iustin Pop
        my_sip = sip
474 9d4bfc96 Iustin Pop
        break
475 9d4bfc96 Iustin Pop
    if not my_pip:
476 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
477 25361b9a Iustin Pop
                      " in the node list")
478 9d4bfc96 Iustin Pop
    else:
479 c657dcc9 Michael Hanselmann
      port = utils.GetNodeDaemonPort()
480 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
481 9d4bfc96 Iustin Pop
        fail = []
482 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
483 9d4bfc96 Iustin Pop
          fail.append("primary")
484 9d4bfc96 Iustin Pop
        if sip != pip:
485 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
486 9d4bfc96 Iustin Pop
            fail.append("secondary")
487 9d4bfc96 Iustin Pop
        if fail:
488 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
489 25361b9a Iustin Pop
                       " and ".join(fail))
490 25361b9a Iustin Pop
491 25361b9a Iustin Pop
  if constants.NV_LVLIST in what:
492 25361b9a Iustin Pop
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
493 25361b9a Iustin Pop
494 25361b9a Iustin Pop
  if constants.NV_INSTANCELIST in what:
495 25361b9a Iustin Pop
    result[constants.NV_INSTANCELIST] = GetInstanceList(
496 25361b9a Iustin Pop
      what[constants.NV_INSTANCELIST])
497 25361b9a Iustin Pop
498 25361b9a Iustin Pop
  if constants.NV_VGLIST in what:
499 e480923b Iustin Pop
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
500 25361b9a Iustin Pop
501 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
502 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
503 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
504 25361b9a Iustin Pop
505 25361b9a Iustin Pop
  if constants.NV_HVINFO in what:
506 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
507 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
508 9d4bfc96 Iustin Pop
509 6d2e83d5 Iustin Pop
  if constants.NV_DRBDLIST in what:
510 6d2e83d5 Iustin Pop
    try:
511 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
512 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
513 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
514 f6eaed12 Iustin Pop
      used_minors = str(err)
515 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
516 6d2e83d5 Iustin Pop
517 c26a6bd2 Iustin Pop
  return result
518 a8083063 Iustin Pop
519 a8083063 Iustin Pop
520 a8083063 Iustin Pop
def GetVolumeList(vg_name):
521 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
522 a8083063 Iustin Pop

523 10c2650b Iustin Pop
  @type vg_name: str
524 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
525 10c2650b Iustin Pop
  @rtype: dict
526 10c2650b Iustin Pop
  @return:
527 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
528 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
529 10c2650b Iustin Pop

530 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
531 10c2650b Iustin Pop

532 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
533 10c2650b Iustin Pop
      details.
534 a8083063 Iustin Pop

535 a8083063 Iustin Pop
  """
536 cb2037a2 Iustin Pop
  lvs = {}
537 cb2037a2 Iustin Pop
  sep = '|'
538 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
539 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
540 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
541 a8083063 Iustin Pop
  if result.failed:
542 29d376ec Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
543 cb2037a2 Iustin Pop
544 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
545 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
546 df4c2628 Iustin Pop
    line = line.strip()
547 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
548 df4c2628 Iustin Pop
    if not match:
549 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
550 df4c2628 Iustin Pop
      continue
551 df4c2628 Iustin Pop
    name, size, attr = match.groups()
552 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
553 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
554 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
555 cb2037a2 Iustin Pop
556 cb2037a2 Iustin Pop
  return lvs
557 a8083063 Iustin Pop
558 a8083063 Iustin Pop
559 a8083063 Iustin Pop
def ListVolumeGroups():
560 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
561 a8083063 Iustin Pop

562 10c2650b Iustin Pop
  @rtype: dict
563 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
564 10c2650b Iustin Pop
      size of the volume
565 a8083063 Iustin Pop

566 a8083063 Iustin Pop
  """
567 c26a6bd2 Iustin Pop
  return utils.ListVolumeGroups()
568 a8083063 Iustin Pop
569 a8083063 Iustin Pop
570 dcb93971 Michael Hanselmann
def NodeVolumes():
571 dcb93971 Michael Hanselmann
  """List all volumes on this node.
572 dcb93971 Michael Hanselmann

573 10c2650b Iustin Pop
  @rtype: list
574 10c2650b Iustin Pop
  @return:
575 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
576 10c2650b Iustin Pop
      - name: the logical volume name,
577 10c2650b Iustin Pop
      - size: the size of the logical volume
578 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
579 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
580 10c2650b Iustin Pop

581 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
582 10c2650b Iustin Pop
    error.
583 10c2650b Iustin Pop

584 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
585 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
586 10c2650b Iustin Pop
    multiple times.
587 10c2650b Iustin Pop

588 dcb93971 Michael Hanselmann
  """
589 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
590 dcb93971 Michael Hanselmann
                         "--separator=|",
591 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
592 dcb93971 Michael Hanselmann
  if result.failed:
593 10bfe6cb Iustin Pop
    _Fail("Failed to list logical volumes, lvs output: %s",
594 10bfe6cb Iustin Pop
          result.output)
595 dcb93971 Michael Hanselmann
596 dcb93971 Michael Hanselmann
  def parse_dev(dev):
597 dcb93971 Michael Hanselmann
    if '(' in dev:
598 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
599 dcb93971 Michael Hanselmann
    else:
600 dcb93971 Michael Hanselmann
      return dev
601 dcb93971 Michael Hanselmann
602 dcb93971 Michael Hanselmann
  def map_line(line):
603 dcb93971 Michael Hanselmann
    return {
604 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
605 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
606 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
607 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
608 dcb93971 Michael Hanselmann
    }
609 dcb93971 Michael Hanselmann
610 c26a6bd2 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
611 c26a6bd2 Iustin Pop
          if line.count('|') >= 3]
612 dcb93971 Michael Hanselmann
613 dcb93971 Michael Hanselmann
614 a8083063 Iustin Pop
def BridgesExist(bridges_list):
615 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
616 a8083063 Iustin Pop

617 b1206984 Iustin Pop
  @rtype: boolean
618 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
619 a8083063 Iustin Pop

620 a8083063 Iustin Pop
  """
621 35c0c8da Iustin Pop
  missing = []
622 a8083063 Iustin Pop
  for bridge in bridges_list:
623 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
624 35c0c8da Iustin Pop
      missing.append(bridge)
625 a8083063 Iustin Pop
626 35c0c8da Iustin Pop
  if missing:
627 afdc3985 Iustin Pop
    _Fail("Missing bridges %s", ", ".join(missing))
628 35c0c8da Iustin Pop
629 a8083063 Iustin Pop
630 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
631 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
632 a8083063 Iustin Pop

633 e69d05fd Iustin Pop
  @type hypervisor_list: list
634 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
635 e69d05fd Iustin Pop

636 e69d05fd Iustin Pop
  @rtype: list
637 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
638 10c2650b Iustin Pop
    - instance1.example.com
639 10c2650b Iustin Pop
    - instance2.example.com
640 a8083063 Iustin Pop

641 098c0958 Michael Hanselmann
  """
642 e69d05fd Iustin Pop
  results = []
643 e69d05fd Iustin Pop
  for hname in hypervisor_list:
644 e69d05fd Iustin Pop
    try:
645 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
646 e69d05fd Iustin Pop
      results.extend(names)
647 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
648 aca13712 Iustin Pop
      _Fail("Error enumerating instances (hypervisor %s): %s",
649 aca13712 Iustin Pop
            hname, err, exc=True)
650 a8083063 Iustin Pop
651 e69d05fd Iustin Pop
  return results
652 a8083063 Iustin Pop
653 a8083063 Iustin Pop
654 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
655 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
656 a8083063 Iustin Pop

657 e69d05fd Iustin Pop
  @type instance: string
658 e69d05fd Iustin Pop
  @param instance: the instance name
659 e69d05fd Iustin Pop
  @type hname: string
660 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
661 a8083063 Iustin Pop

662 e69d05fd Iustin Pop
  @rtype: dict
663 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
664 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
665 e69d05fd Iustin Pop
      - state: xen state of instance (string)
666 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
667 a8083063 Iustin Pop

668 098c0958 Michael Hanselmann
  """
669 a8083063 Iustin Pop
  output = {}
670 a8083063 Iustin Pop
671 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
672 a8083063 Iustin Pop
  if iinfo is not None:
673 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
674 a8083063 Iustin Pop
    output['state'] = iinfo[4]
675 a8083063 Iustin Pop
    output['time'] = iinfo[5]
676 a8083063 Iustin Pop
677 c26a6bd2 Iustin Pop
  return output
678 a8083063 Iustin Pop
679 a8083063 Iustin Pop
680 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
681 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
682 56e7640c Iustin Pop

683 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
684 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
685 56e7640c Iustin Pop

686 56e7640c Iustin Pop
  @rtype: tuple
687 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
688 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
689 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
690 56e7640c Iustin Pop

691 56e7640c Iustin Pop
  """
692 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
693 afdc3985 Iustin Pop
  iname = instance.name
694 afdc3985 Iustin Pop
  if iname not in hyper.ListInstances():
695 afdc3985 Iustin Pop
    _Fail("Instance %s is not running", iname)
696 56e7640c Iustin Pop
697 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
698 afdc3985 Iustin Pop
    link_name = _GetBlockDevSymlinkPath(iname, idx)
699 56e7640c Iustin Pop
    if not os.path.islink(link_name):
700 afdc3985 Iustin Pop
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
701 56e7640c Iustin Pop
702 56e7640c Iustin Pop
703 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
704 a8083063 Iustin Pop
  """Gather data about all instances.
705 a8083063 Iustin Pop

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

710 e69d05fd Iustin Pop
  @type hypervisor_list: list
711 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
712 e69d05fd Iustin Pop

713 955db481 Guido Trotter
  @rtype: dict
714 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
715 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
716 e69d05fd Iustin Pop
      - state: xen state of instance (string)
717 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
718 10c2650b Iustin Pop
      - vcpus: the number of vcpus
719 a8083063 Iustin Pop

720 098c0958 Michael Hanselmann
  """
721 a8083063 Iustin Pop
  output = {}
722 a8083063 Iustin Pop
723 e69d05fd Iustin Pop
  for hname in hypervisor_list:
724 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
725 e69d05fd Iustin Pop
    if iinfo:
726 29921401 Iustin Pop
      for name, _, memory, vcpus, state, times in iinfo:
727 f23b5ae8 Iustin Pop
        value = {
728 e69d05fd Iustin Pop
          'memory': memory,
729 e69d05fd Iustin Pop
          'vcpus': vcpus,
730 e69d05fd Iustin Pop
          'state': state,
731 e69d05fd Iustin Pop
          'time': times,
732 e69d05fd Iustin Pop
          }
733 b33b6f55 Iustin Pop
        if name in output:
734 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
735 b33b6f55 Iustin Pop
          # and not state and time which can change between the
736 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
737 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
738 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
739 2fa74ef4 Iustin Pop
              _Fail("Instance %s is running twice"
740 2fa74ef4 Iustin Pop
                    " with different parameters", name)
741 f23b5ae8 Iustin Pop
        output[name] = value
742 a8083063 Iustin Pop
743 c26a6bd2 Iustin Pop
  return output
744 a8083063 Iustin Pop
745 a8083063 Iustin Pop
746 e557bae9 Guido Trotter
def InstanceOsAdd(instance, reinstall):
747 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
748 a8083063 Iustin Pop

749 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
750 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
751 e557bae9 Guido Trotter
  @type reinstall: boolean
752 e557bae9 Guido Trotter
  @param reinstall: whether this is an instance reinstall
753 c26a6bd2 Iustin Pop
  @rtype: None
754 a8083063 Iustin Pop

755 a8083063 Iustin Pop
  """
756 255dcebd Iustin Pop
  inst_os = OSFromDisk(instance.os)
757 255dcebd Iustin Pop
758 d1a7d66f Guido Trotter
  create_env = OSEnvironment(instance, inst_os)
759 e557bae9 Guido Trotter
  if reinstall:
760 e557bae9 Guido Trotter
    create_env['INSTANCE_REINSTALL'] = "1"
761 a8083063 Iustin Pop
762 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
763 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
764 decd5f45 Iustin Pop
765 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
766 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
767 decd5f45 Iustin Pop
  if result.failed:
768 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
769 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
770 18682bca Iustin Pop
                  result.output)
771 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
772 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
773 afdc3985 Iustin Pop
    _Fail("OS create script failed (%s), last lines in the"
774 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
775 decd5f45 Iustin Pop
776 decd5f45 Iustin Pop
777 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
778 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
779 decd5f45 Iustin Pop

780 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
781 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
782 d15a9ad3 Guido Trotter
  @type old_name: string
783 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
784 10c2650b Iustin Pop
  @rtype: boolean
785 10c2650b Iustin Pop
  @return: the success of the operation
786 decd5f45 Iustin Pop

787 decd5f45 Iustin Pop
  """
788 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
789 decd5f45 Iustin Pop
790 d1a7d66f Guido Trotter
  rename_env = OSEnvironment(instance, inst_os)
791 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
792 decd5f45 Iustin Pop
793 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
794 decd5f45 Iustin Pop
                                           old_name,
795 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
796 a8083063 Iustin Pop
797 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
798 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
799 a8083063 Iustin Pop
800 a8083063 Iustin Pop
  if result.failed:
801 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
802 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
803 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
804 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
805 afdc3985 Iustin Pop
    _Fail("OS rename script failed (%s), last lines in the"
806 afdc3985 Iustin Pop
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
807 a8083063 Iustin Pop
808 a8083063 Iustin Pop
809 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
810 5bbd3f7f Michael Hanselmann
  """Get information about the volume group.
811 a8083063 Iustin Pop

812 10c2650b Iustin Pop
  @type vg_name: str
813 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
814 10c2650b Iustin Pop
  @rtype: dict
815 10c2650b Iustin Pop
  @return:
816 10c2650b Iustin Pop
    A dictionary with the following keys:
817 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
818 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
819 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
820 a8083063 Iustin Pop

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

824 a8083063 Iustin Pop
  """
825 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
826 f4d377e7 Iustin Pop
827 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
828 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
829 a8083063 Iustin Pop
830 a8083063 Iustin Pop
  if retval.failed:
831 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
832 f4d377e7 Iustin Pop
    return retdic
833 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
834 f4d377e7 Iustin Pop
  if len(valarr) == 3:
835 f4d377e7 Iustin Pop
    try:
836 f4d377e7 Iustin Pop
      retdic = {
837 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
838 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
839 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
840 f4d377e7 Iustin Pop
        }
841 f4d377e7 Iustin Pop
    except ValueError, err:
842 29921401 Iustin Pop
      logging.exception("Fail to parse vgs output: %s", err)
843 f4d377e7 Iustin Pop
  else:
844 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
845 18682bca Iustin Pop
                  " three): %s", str(valarr))
846 a8083063 Iustin Pop
  return retdic
847 a8083063 Iustin Pop
848 a8083063 Iustin Pop
849 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
850 5282084b Iustin Pop
  return os.path.join(constants.DISK_LINKS_DIR,
851 5282084b Iustin Pop
                      "%s:%d" % (instance_name, idx))
852 5282084b Iustin Pop
853 5282084b Iustin Pop
854 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
855 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
856 9332fd8a Iustin Pop

857 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
858 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
859 9332fd8a Iustin Pop

860 9332fd8a Iustin Pop

861 5282084b Iustin Pop
  @param instance_name: the name of the target instance
862 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
863 5282084b Iustin Pop
  @param idx: the disk index
864 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
865 9332fd8a Iustin Pop

866 9332fd8a Iustin Pop
  """
867 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
868 9332fd8a Iustin Pop
  try:
869 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
870 5282084b Iustin Pop
  except OSError, err:
871 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
872 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
873 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
874 9332fd8a Iustin Pop
        os.remove(link_name)
875 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
876 9332fd8a Iustin Pop
    else:
877 9332fd8a Iustin Pop
      raise
878 9332fd8a Iustin Pop
879 9332fd8a Iustin Pop
  return link_name
880 9332fd8a Iustin Pop
881 9332fd8a Iustin Pop
882 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
883 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
884 3c9c571d Iustin Pop

885 3c9c571d Iustin Pop
  """
886 29921401 Iustin Pop
  for idx, _ in enumerate(disks):
887 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
888 5282084b Iustin Pop
    if os.path.islink(link_name):
889 3c9c571d Iustin Pop
      try:
890 03dfa658 Iustin Pop
        os.remove(link_name)
891 03dfa658 Iustin Pop
      except OSError:
892 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
893 3c9c571d Iustin Pop
894 3c9c571d Iustin Pop
895 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
896 a8083063 Iustin Pop
  """Set up an instance's block device(s).
897 a8083063 Iustin Pop

898 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
899 a8083063 Iustin Pop
  devices must be already assembled.
900 a8083063 Iustin Pop

901 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
902 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
903 069cfbf1 Iustin Pop
  @rtype: list
904 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
905 10c2650b Iustin Pop

906 a8083063 Iustin Pop
  """
907 a8083063 Iustin Pop
  block_devices = []
908 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
909 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
910 a8083063 Iustin Pop
    if device is None:
911 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
912 a8083063 Iustin Pop
                                    str(disk))
913 a8083063 Iustin Pop
    device.Open()
914 9332fd8a Iustin Pop
    try:
915 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
916 9332fd8a Iustin Pop
    except OSError, e:
917 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
918 9332fd8a Iustin Pop
                                    e.strerror)
919 9332fd8a Iustin Pop
920 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
921 9332fd8a Iustin Pop
922 a8083063 Iustin Pop
  return block_devices
923 a8083063 Iustin Pop
924 a8083063 Iustin Pop
925 07813a9e Iustin Pop
def StartInstance(instance):
926 a8083063 Iustin Pop
  """Start an instance.
927 a8083063 Iustin Pop

928 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
929 e69d05fd Iustin Pop
  @param instance: the instance object
930 c26a6bd2 Iustin Pop
  @rtype: None
931 a8083063 Iustin Pop

932 098c0958 Michael Hanselmann
  """
933 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
934 a8083063 Iustin Pop
935 a8083063 Iustin Pop
  if instance.name in running_instances:
936 c26a6bd2 Iustin Pop
    logging.info("Instance %s already running, not starting", instance.name)
937 c26a6bd2 Iustin Pop
    return
938 a8083063 Iustin Pop
939 a8083063 Iustin Pop
  try:
940 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
941 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
942 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
943 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
944 2cc6781a Iustin Pop
    _Fail("Block device error: %s", err, exc=True)
945 a8083063 Iustin Pop
  except errors.HypervisorError, err:
946 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
947 2cc6781a Iustin Pop
    _Fail("Hypervisor error: %s", err, exc=True)
948 a8083063 Iustin Pop
949 a8083063 Iustin Pop
950 1fae010f Iustin Pop
def InstanceShutdown(instance):
951 a8083063 Iustin Pop
  """Shut an instance down.
952 a8083063 Iustin Pop

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

955 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
956 e69d05fd Iustin Pop
  @param instance: the instance object
957 c26a6bd2 Iustin Pop
  @rtype: None
958 a8083063 Iustin Pop

959 098c0958 Michael Hanselmann
  """
960 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
961 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
962 c26a6bd2 Iustin Pop
  iname = instance.name
963 a8083063 Iustin Pop
964 c26a6bd2 Iustin Pop
  if iname not in running_instances:
965 c26a6bd2 Iustin Pop
    logging.info("Instance %s not running, doing nothing", iname)
966 c26a6bd2 Iustin Pop
    return
967 a8083063 Iustin Pop
968 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
969 a8083063 Iustin Pop
  try:
970 a8083063 Iustin Pop
    hyper.StopInstance(instance)
971 a8083063 Iustin Pop
  except errors.HypervisorError, err:
972 c26a6bd2 Iustin Pop
    _Fail("Failed to stop instance %s: %s", iname, err)
973 a8083063 Iustin Pop
974 a8083063 Iustin Pop
  # test every 10secs for 2min
975 a8083063 Iustin Pop
976 a8083063 Iustin Pop
  time.sleep(1)
977 7c4d6c7b Michael Hanselmann
  for _ in range(11):
978 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
979 a8083063 Iustin Pop
      break
980 a8083063 Iustin Pop
    time.sleep(10)
981 a8083063 Iustin Pop
  else:
982 a8083063 Iustin Pop
    # the shutdown did not succeed
983 c26a6bd2 Iustin Pop
    logging.error("Shutdown of '%s' unsuccessful, using destroy", iname)
984 a8083063 Iustin Pop
985 a8083063 Iustin Pop
    try:
986 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
987 a8083063 Iustin Pop
    except errors.HypervisorError, err:
988 c26a6bd2 Iustin Pop
      _Fail("Failed to force stop instance %s: %s", iname, err)
989 a8083063 Iustin Pop
990 a8083063 Iustin Pop
    time.sleep(1)
991 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
992 c26a6bd2 Iustin Pop
      _Fail("Could not shutdown instance %s even by destroy", iname)
993 3c9c571d Iustin Pop
994 c26a6bd2 Iustin Pop
  _RemoveBlockDevLinks(iname, instance.disks)
995 a8083063 Iustin Pop
996 a8083063 Iustin Pop
997 07813a9e Iustin Pop
def InstanceReboot(instance, reboot_type):
998 007a2f3e Alexander Schreiber
  """Reboot an instance.
999 007a2f3e Alexander Schreiber

1000 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1001 10c2650b Iustin Pop
  @param instance: the instance object to reboot
1002 10c2650b Iustin Pop
  @type reboot_type: str
1003 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
1004 10c2650b Iustin Pop
    constants:
1005 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1006 10c2650b Iustin Pop
        instance OS, do not recreate the VM
1007 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1008 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
1009 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1010 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
1011 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
1012 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
1013 c26a6bd2 Iustin Pop
  @rtype: None
1014 007a2f3e Alexander Schreiber

1015 007a2f3e Alexander Schreiber
  """
1016 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1017 007a2f3e Alexander Schreiber
1018 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1019 2cc6781a Iustin Pop
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1020 007a2f3e Alexander Schreiber
1021 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1022 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1023 007a2f3e Alexander Schreiber
    try:
1024 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1025 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1026 2cc6781a Iustin Pop
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1027 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1028 007a2f3e Alexander Schreiber
    try:
1029 c26a6bd2 Iustin Pop
      InstanceShutdown(instance)
1030 07813a9e Iustin Pop
      return StartInstance(instance)
1031 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1032 2cc6781a Iustin Pop
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1033 007a2f3e Alexander Schreiber
  else:
1034 2cc6781a Iustin Pop
    _Fail("Invalid reboot_type received: %s", reboot_type)
1035 007a2f3e Alexander Schreiber
1036 007a2f3e Alexander Schreiber
1037 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1038 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1039 6906a9d8 Guido Trotter

1040 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1041 6906a9d8 Guido Trotter
  @param instance: the instance definition
1042 6906a9d8 Guido Trotter

1043 6906a9d8 Guido Trotter
  """
1044 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1045 cd42d0ad Guido Trotter
  try:
1046 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1047 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1048 2cc6781a Iustin Pop
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1049 c26a6bd2 Iustin Pop
  return info
1050 6906a9d8 Guido Trotter
1051 6906a9d8 Guido Trotter
1052 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1053 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1054 6906a9d8 Guido Trotter

1055 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1056 6906a9d8 Guido Trotter
  @param instance: the instance definition
1057 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1058 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1059 6906a9d8 Guido Trotter
  @type target: string
1060 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1061 6906a9d8 Guido Trotter

1062 6906a9d8 Guido Trotter
  """
1063 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1064 cd42d0ad Guido Trotter
  try:
1065 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1066 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1067 2cc6781a Iustin Pop
    _Fail("Failed to accept instance: %s", err, exc=True)
1068 6906a9d8 Guido Trotter
1069 6906a9d8 Guido Trotter
1070 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1071 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1072 6906a9d8 Guido Trotter

1073 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1074 6906a9d8 Guido Trotter
  @param instance: the instance definition
1075 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1076 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1077 6906a9d8 Guido Trotter
  @type success: boolean
1078 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1079 6906a9d8 Guido Trotter

1080 6906a9d8 Guido Trotter
  """
1081 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1082 cd42d0ad Guido Trotter
  try:
1083 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1084 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1085 2cc6781a Iustin Pop
    _Fail("Failed to finalize migration: %s", err, exc=True)
1086 6906a9d8 Guido Trotter
1087 6906a9d8 Guido Trotter
1088 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1089 2a10865c Iustin Pop
  """Migrates an instance to another node.
1090 2a10865c Iustin Pop

1091 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1092 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1093 9f0e6b37 Iustin Pop
  @type target: string
1094 9f0e6b37 Iustin Pop
  @param target: the target node name
1095 9f0e6b37 Iustin Pop
  @type live: boolean
1096 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1097 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1098 9f0e6b37 Iustin Pop
  @rtype: tuple
1099 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1100 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1101 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1102 9f0e6b37 Iustin Pop

1103 2a10865c Iustin Pop
  """
1104 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1105 2a10865c Iustin Pop
1106 2a10865c Iustin Pop
  try:
1107 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
1108 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1109 2cc6781a Iustin Pop
    _Fail("Failed to migrate instance: %s", err, exc=True)
1110 2a10865c Iustin Pop
1111 2a10865c Iustin Pop
1112 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1113 a8083063 Iustin Pop
  """Creates a block device for an instance.
1114 a8083063 Iustin Pop

1115 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1116 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1117 b1206984 Iustin Pop
  @type size: int
1118 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1119 b1206984 Iustin Pop
  @type owner: str
1120 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1121 b1206984 Iustin Pop
      used for device cache data
1122 b1206984 Iustin Pop
  @type on_primary: boolean
1123 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1124 b1206984 Iustin Pop
  @type info: string
1125 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1126 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1127 b1206984 Iustin Pop

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

1132 a8083063 Iustin Pop
  """
1133 a8083063 Iustin Pop
  clist = []
1134 a8083063 Iustin Pop
  if disk.children:
1135 a8083063 Iustin Pop
    for child in disk.children:
1136 1063abd1 Iustin Pop
      try:
1137 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1138 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1139 2cc6781a Iustin Pop
        _Fail("Can't assemble device %s: %s", child, err)
1140 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1141 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1142 a8083063 Iustin Pop
        # be assembled
1143 1063abd1 Iustin Pop
        try:
1144 1063abd1 Iustin Pop
          crdev.Open()
1145 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1146 2cc6781a Iustin Pop
          _Fail("Can't make child '%s' read-write: %s", child, err)
1147 a8083063 Iustin Pop
      clist.append(crdev)
1148 a8083063 Iustin Pop
1149 dab69e97 Iustin Pop
  try:
1150 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1151 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1152 2cc6781a Iustin Pop
    _Fail("Can't create block device: %s", err)
1153 6c626518 Iustin Pop
1154 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1155 1063abd1 Iustin Pop
    try:
1156 1063abd1 Iustin Pop
      device.Assemble()
1157 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1158 2cc6781a Iustin Pop
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1159 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1160 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1161 1063abd1 Iustin Pop
      try:
1162 1063abd1 Iustin Pop
        device.Open(force=True)
1163 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1164 2cc6781a Iustin Pop
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1165 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1166 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1167 a0c3fea1 Michael Hanselmann
1168 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1169 a0c3fea1 Michael Hanselmann
1170 c26a6bd2 Iustin Pop
  return device.unique_id
1171 a8083063 Iustin Pop
1172 a8083063 Iustin Pop
1173 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1174 a8083063 Iustin Pop
  """Remove a block device.
1175 a8083063 Iustin Pop

1176 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1177 10c2650b Iustin Pop

1178 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1179 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1180 10c2650b Iustin Pop
  @rtype: boolean
1181 10c2650b Iustin Pop
  @return: the success of the operation
1182 a8083063 Iustin Pop

1183 a8083063 Iustin Pop
  """
1184 e1bc0878 Iustin Pop
  msgs = []
1185 a8083063 Iustin Pop
  try:
1186 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1187 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1188 a8083063 Iustin Pop
    # probably can't attach
1189 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1190 a8083063 Iustin Pop
    rdev = None
1191 a8083063 Iustin Pop
  if rdev is not None:
1192 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1193 e1bc0878 Iustin Pop
    try:
1194 0c6c04ec Iustin Pop
      rdev.Remove()
1195 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1196 e1bc0878 Iustin Pop
      msgs.append(str(err))
1197 c26a6bd2 Iustin Pop
    if not msgs:
1198 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1199 e1bc0878 Iustin Pop
1200 a8083063 Iustin Pop
  if disk.children:
1201 a8083063 Iustin Pop
    for child in disk.children:
1202 c26a6bd2 Iustin Pop
      try:
1203 c26a6bd2 Iustin Pop
        BlockdevRemove(child)
1204 c26a6bd2 Iustin Pop
      except RPCFail, err:
1205 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1206 e1bc0878 Iustin Pop
1207 c26a6bd2 Iustin Pop
  if msgs:
1208 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1209 afdc3985 Iustin Pop
1210 a8083063 Iustin Pop
1211 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1212 a8083063 Iustin Pop
  """Activate a block device for an instance.
1213 a8083063 Iustin Pop

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

1216 10c2650b Iustin Pop
  @note: this function is called recursively.
1217 a8083063 Iustin Pop

1218 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1219 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1220 10c2650b Iustin Pop
  @type owner: str
1221 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1222 10c2650b Iustin Pop
  @type as_primary: boolean
1223 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1224 10c2650b Iustin Pop
      read/write
1225 a8083063 Iustin Pop

1226 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1227 10c2650b Iustin Pop
      was assembled)
1228 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1229 10c2650b Iustin Pop
      during the activation of the children or the device
1230 10c2650b Iustin Pop
      itself
1231 a8083063 Iustin Pop

1232 a8083063 Iustin Pop
  """
1233 a8083063 Iustin Pop
  children = []
1234 a8083063 Iustin Pop
  if disk.children:
1235 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1236 fc1dc9d7 Iustin Pop
    if mcn == -1:
1237 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1238 fc1dc9d7 Iustin Pop
    else:
1239 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1240 a8083063 Iustin Pop
    for chld_disk in disk.children:
1241 fc1dc9d7 Iustin Pop
      try:
1242 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1243 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1244 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1245 fc1dc9d7 Iustin Pop
          raise
1246 fc1dc9d7 Iustin Pop
        cdev = None
1247 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1248 1063abd1 Iustin Pop
                      str(err))
1249 fc1dc9d7 Iustin Pop
      children.append(cdev)
1250 a8083063 Iustin Pop
1251 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1252 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1253 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1254 a8083063 Iustin Pop
    result = r_dev
1255 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1256 a8083063 Iustin Pop
      r_dev.Open()
1257 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1258 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1259 3f78eef2 Iustin Pop
1260 a8083063 Iustin Pop
  else:
1261 a8083063 Iustin Pop
    result = True
1262 a8083063 Iustin Pop
  return result
1263 a8083063 Iustin Pop
1264 a8083063 Iustin Pop
1265 821d1bd1 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary):
1266 a8083063 Iustin Pop
  """Activate a block device for an instance.
1267 a8083063 Iustin Pop

1268 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1269 a8083063 Iustin Pop

1270 b1206984 Iustin Pop
  @rtype: str or boolean
1271 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1272 b1206984 Iustin Pop
      C{True} for secondary nodes
1273 a8083063 Iustin Pop

1274 a8083063 Iustin Pop
  """
1275 53c14ef1 Iustin Pop
  try:
1276 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1277 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1278 53c14ef1 Iustin Pop
      result = result.dev_path
1279 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1280 afdc3985 Iustin Pop
    _Fail("Error while assembling disk: %s", err, exc=True)
1281 afdc3985 Iustin Pop
1282 c26a6bd2 Iustin Pop
  return result
1283 a8083063 Iustin Pop
1284 a8083063 Iustin Pop
1285 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1286 a8083063 Iustin Pop
  """Shut down a block device.
1287 a8083063 Iustin Pop

1288 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1289 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1290 c41eea6e Iustin Pop
  shutdown.
1291 a8083063 Iustin Pop

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

1296 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1297 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1298 10c2650b Iustin Pop
      shutdown
1299 c26a6bd2 Iustin Pop
  @rtype: None
1300 10c2650b Iustin Pop

1301 a8083063 Iustin Pop
  """
1302 cacfd1fd Iustin Pop
  msgs = []
1303 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1304 a8083063 Iustin Pop
  if r_dev is not None:
1305 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1306 cacfd1fd Iustin Pop
    try:
1307 746f7476 Iustin Pop
      r_dev.Shutdown()
1308 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1309 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1310 cacfd1fd Iustin Pop
      msgs.append(str(err))
1311 746f7476 Iustin Pop
1312 a8083063 Iustin Pop
  if disk.children:
1313 a8083063 Iustin Pop
    for child in disk.children:
1314 c26a6bd2 Iustin Pop
      try:
1315 c26a6bd2 Iustin Pop
        BlockdevShutdown(child)
1316 c26a6bd2 Iustin Pop
      except RPCFail, err:
1317 c26a6bd2 Iustin Pop
        msgs.append(str(err))
1318 746f7476 Iustin Pop
1319 c26a6bd2 Iustin Pop
  if msgs:
1320 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
1321 a8083063 Iustin Pop
1322 a8083063 Iustin Pop
1323 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1324 153d9724 Iustin Pop
  """Extend a mirrored block device.
1325 a8083063 Iustin Pop

1326 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1327 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1328 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1329 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1330 c26a6bd2 Iustin Pop
  @rtype: None
1331 10c2650b Iustin Pop

1332 a8083063 Iustin Pop
  """
1333 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1334 153d9724 Iustin Pop
  if parent_bdev is None:
1335 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1336 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1337 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1338 2cc6781a Iustin Pop
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1339 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1340 a8083063 Iustin Pop
1341 a8083063 Iustin Pop
1342 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1343 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1344 a8083063 Iustin Pop

1345 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1346 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1347 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1348 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1349 c26a6bd2 Iustin Pop
  @rtype: None
1350 10c2650b Iustin Pop

1351 a8083063 Iustin Pop
  """
1352 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1353 153d9724 Iustin Pop
  if parent_bdev is None:
1354 2cc6781a Iustin Pop
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1355 e739bd57 Iustin Pop
  devs = []
1356 e739bd57 Iustin Pop
  for disk in new_cdevs:
1357 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1358 e739bd57 Iustin Pop
    if rpath is None:
1359 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1360 e739bd57 Iustin Pop
      if bd is None:
1361 2cc6781a Iustin Pop
        _Fail("Can't find device %s while removing children", disk)
1362 e739bd57 Iustin Pop
      else:
1363 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1364 e739bd57 Iustin Pop
    else:
1365 e739bd57 Iustin Pop
      devs.append(rpath)
1366 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1367 a8083063 Iustin Pop
1368 a8083063 Iustin Pop
1369 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1370 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1371 a8083063 Iustin Pop

1372 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1373 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1374 10c2650b Iustin Pop
  @rtype: disk
1375 10c2650b Iustin Pop
  @return:
1376 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1377 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1378 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1379 10c2650b Iustin Pop
      found
1380 a8083063 Iustin Pop

1381 a8083063 Iustin Pop
  """
1382 a8083063 Iustin Pop
  stats = []
1383 a8083063 Iustin Pop
  for dsk in disks:
1384 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1385 a8083063 Iustin Pop
    if rbd is None:
1386 3efa9051 Iustin Pop
      _Fail("Can't find device %s", dsk)
1387 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1388 c26a6bd2 Iustin Pop
  return stats
1389 a8083063 Iustin Pop
1390 a8083063 Iustin Pop
1391 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1392 a8083063 Iustin Pop
  """Check if a device is activated.
1393 a8083063 Iustin Pop

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

1396 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1397 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1398 a8083063 Iustin Pop

1399 10c2650b Iustin Pop
  @return: None if the device can't be found,
1400 10c2650b Iustin Pop
      otherwise the device instance
1401 a8083063 Iustin Pop

1402 a8083063 Iustin Pop
  """
1403 a8083063 Iustin Pop
  children = []
1404 a8083063 Iustin Pop
  if disk.children:
1405 a8083063 Iustin Pop
    for chdisk in disk.children:
1406 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1407 a8083063 Iustin Pop
1408 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1409 a8083063 Iustin Pop
1410 a8083063 Iustin Pop
1411 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1412 a8083063 Iustin Pop
  """Check if a device is activated.
1413 a8083063 Iustin Pop

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

1416 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1417 10c2650b Iustin Pop
  @param disk: the disk to find
1418 10c2650b Iustin Pop
  @rtype: None or tuple
1419 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1420 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1421 10c2650b Iustin Pop
      estimated_time, is_degraded)
1422 a8083063 Iustin Pop

1423 a8083063 Iustin Pop
  """
1424 23829f6f Iustin Pop
  try:
1425 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1426 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1427 2cc6781a Iustin Pop
    _Fail("Failed to find device: %s", err, exc=True)
1428 a8083063 Iustin Pop
  if rbd is None:
1429 c26a6bd2 Iustin Pop
    return None
1430 c26a6bd2 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1431 a8083063 Iustin Pop
1432 a8083063 Iustin Pop
1433 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1434 a8083063 Iustin Pop
  """Write a file to the filesystem.
1435 a8083063 Iustin Pop

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

1439 10c2650b Iustin Pop
  @type file_name: str
1440 10c2650b Iustin Pop
  @param file_name: the target file name
1441 10c2650b Iustin Pop
  @type data: str
1442 10c2650b Iustin Pop
  @param data: the new contents of the file
1443 10c2650b Iustin Pop
  @type mode: int
1444 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1445 10c2650b Iustin Pop
  @type uid: int
1446 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1447 10c2650b Iustin Pop
  @type gid: int
1448 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1449 10c2650b Iustin Pop
  @type atime: float
1450 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1451 10c2650b Iustin Pop
  @type mtime: float
1452 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1453 c26a6bd2 Iustin Pop
  @rtype: None
1454 10c2650b Iustin Pop

1455 a8083063 Iustin Pop
  """
1456 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1457 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1458 a8083063 Iustin Pop
1459 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
1460 2cc6781a Iustin Pop
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1461 2cc6781a Iustin Pop
          file_name)
1462 a8083063 Iustin Pop
1463 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1464 12bce260 Michael Hanselmann
1465 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1466 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1467 a8083063 Iustin Pop
1468 386b57af Iustin Pop
1469 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1470 89b14f05 Iustin Pop
  """Update all ssconf files.
1471 89b14f05 Iustin Pop

1472 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1473 89b14f05 Iustin Pop

1474 89b14f05 Iustin Pop
  """
1475 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1476 6ddc95ec Michael Hanselmann
1477 6ddc95ec Michael Hanselmann
1478 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1479 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1480 a8083063 Iustin Pop

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

1485 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1486 10c2650b Iustin Pop
  @param err: the exception to format
1487 a8083063 Iustin Pop

1488 a8083063 Iustin Pop
  """
1489 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1490 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1491 a8083063 Iustin Pop
  else:
1492 a8083063 Iustin Pop
    detail = str(err)
1493 a8083063 Iustin Pop
  return detail
1494 a8083063 Iustin Pop
1495 5d0fe286 Iustin Pop
1496 7ead9575 Guido Trotter
def _OSOndiskAPIVersion(name, os_dir):
1497 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1498 a8083063 Iustin Pop

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

1502 10c2650b Iustin Pop
  @type name: str
1503 10c2650b Iustin Pop
  @param name: the OS name we should look for
1504 10c2650b Iustin Pop
  @type os_dir: str
1505 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1506 8e70b181 Iustin Pop
  @rtype: tuple
1507 8e70b181 Iustin Pop
  @return: tuple (status, data) with status denoting the validity and
1508 8e70b181 Iustin Pop
      data holding either the vaid versions or an error message
1509 a8083063 Iustin Pop

1510 a8083063 Iustin Pop
  """
1511 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1512 a8083063 Iustin Pop
1513 a8083063 Iustin Pop
  try:
1514 a8083063 Iustin Pop
    st = os.stat(api_file)
1515 a8083063 Iustin Pop
  except EnvironmentError, err:
1516 255dcebd Iustin Pop
    return False, ("Required file 'ganeti_api_version' file not"
1517 255dcebd Iustin Pop
                   " found under path %s: %s" % (os_dir, _ErrnoOrStr(err)))
1518 a8083063 Iustin Pop
1519 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1520 255dcebd Iustin Pop
    return False, ("File 'ganeti_api_version' file at %s is not"
1521 255dcebd Iustin Pop
                   " a regular file" % os_dir)
1522 a8083063 Iustin Pop
1523 a8083063 Iustin Pop
  try:
1524 3374afa9 Guido Trotter
    api_versions = utils.ReadFile(api_file).splitlines()
1525 a8083063 Iustin Pop
  except EnvironmentError, err:
1526 255dcebd Iustin Pop
    return False, ("Error while reading the API version file at %s: %s" %
1527 255dcebd Iustin Pop
                   (api_file, _ErrnoOrStr(err)))
1528 a8083063 Iustin Pop
1529 a8083063 Iustin Pop
  try:
1530 63b9b186 Guido Trotter
    api_versions = [int(version.strip()) for version in api_versions]
1531 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1532 255dcebd Iustin Pop
    return False, ("API version(s) can't be converted to integer: %s" %
1533 255dcebd Iustin Pop
                   str(err))
1534 a8083063 Iustin Pop
1535 255dcebd Iustin Pop
  return True, api_versions
1536 a8083063 Iustin Pop
1537 386b57af Iustin Pop
1538 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1539 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1540 a8083063 Iustin Pop

1541 10c2650b Iustin Pop
  @type top_dirs: list
1542 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1543 10c2650b Iustin Pop
      search (if not given defaults to
1544 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1545 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1546 255dcebd Iustin Pop
  @return: a list of tuples (name, path, status, diagnose)
1547 255dcebd Iustin Pop
      for all (potential) OSes under all search paths, where:
1548 255dcebd Iustin Pop
          - name is the (potential) OS name
1549 255dcebd Iustin Pop
          - path is the full path to the OS
1550 255dcebd Iustin Pop
          - status True/False is the validity of the OS
1551 255dcebd Iustin Pop
          - diagnose is the error message for an invalid OS, otherwise empty
1552 a8083063 Iustin Pop

1553 a8083063 Iustin Pop
  """
1554 7c3d51d4 Guido Trotter
  if top_dirs is None:
1555 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1556 a8083063 Iustin Pop
1557 a8083063 Iustin Pop
  result = []
1558 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1559 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1560 7c3d51d4 Guido Trotter
      try:
1561 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1562 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1563 29921401 Iustin Pop
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1564 7c3d51d4 Guido Trotter
        break
1565 7c3d51d4 Guido Trotter
      for name in f_names:
1566 255dcebd Iustin Pop
        os_path = os.path.sep.join([dir_name, name])
1567 255dcebd Iustin Pop
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1568 255dcebd Iustin Pop
        if status:
1569 255dcebd Iustin Pop
          diagnose = ""
1570 255dcebd Iustin Pop
        else:
1571 255dcebd Iustin Pop
          diagnose = os_inst
1572 255dcebd Iustin Pop
        result.append((name, os_path, status, diagnose))
1573 a8083063 Iustin Pop
1574 c26a6bd2 Iustin Pop
  return result
1575 a8083063 Iustin Pop
1576 a8083063 Iustin Pop
1577 255dcebd Iustin Pop
def _TryOSFromDisk(name, base_dir=None):
1578 a8083063 Iustin Pop
  """Create an OS instance from disk.
1579 a8083063 Iustin Pop

1580 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1581 8e70b181 Iustin Pop
  valid OS name.
1582 a8083063 Iustin Pop

1583 8ee4dc80 Guido Trotter
  @type base_dir: string
1584 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1585 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1586 255dcebd Iustin Pop
  @rtype: tuple
1587 255dcebd Iustin Pop
  @return: success and either the OS instance if we find a valid one,
1588 255dcebd Iustin Pop
      or error message
1589 7c3d51d4 Guido Trotter

1590 a8083063 Iustin Pop
  """
1591 56bcd3f4 Guido Trotter
  if base_dir is None:
1592 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1593 c34c0cfd Iustin Pop
    if os_dir is None:
1594 255dcebd Iustin Pop
      return False, "Directory for OS %s not found in search path" % name
1595 c34c0cfd Iustin Pop
  else:
1596 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1597 a8083063 Iustin Pop
1598 7ead9575 Guido Trotter
  status, api_versions = _OSOndiskAPIVersion(name, os_dir)
1599 255dcebd Iustin Pop
  if not status:
1600 255dcebd Iustin Pop
    # push the error up
1601 255dcebd Iustin Pop
    return status, api_versions
1602 a8083063 Iustin Pop
1603 d1a7d66f Guido Trotter
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1604 255dcebd Iustin Pop
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1605 d1a7d66f Guido Trotter
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1606 a8083063 Iustin Pop
1607 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1608 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1609 a8083063 Iustin Pop
1610 a8083063 Iustin Pop
  for script in os_scripts:
1611 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1612 a8083063 Iustin Pop
1613 a8083063 Iustin Pop
    try:
1614 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1615 a8083063 Iustin Pop
    except EnvironmentError, err:
1616 255dcebd Iustin Pop
      return False, ("Script '%s' under path '%s' is missing (%s)" %
1617 255dcebd Iustin Pop
                     (script, os_dir, _ErrnoOrStr(err)))
1618 a8083063 Iustin Pop
1619 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1620 255dcebd Iustin Pop
      return False, ("Script '%s' under path '%s' is not executable" %
1621 255dcebd Iustin Pop
                     (script, os_dir))
1622 a8083063 Iustin Pop
1623 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1624 255dcebd Iustin Pop
      return False, ("Script '%s' under path '%s' is not a regular file" %
1625 255dcebd Iustin Pop
                     (script, os_dir))
1626 255dcebd Iustin Pop
1627 8e70b181 Iustin Pop
  os_obj = objects.OS(name=name, path=os_dir,
1628 255dcebd Iustin Pop
                      create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1629 255dcebd Iustin Pop
                      export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1630 255dcebd Iustin Pop
                      import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1631 255dcebd Iustin Pop
                      rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1632 255dcebd Iustin Pop
                      api_versions=api_versions)
1633 255dcebd Iustin Pop
  return True, os_obj
1634 255dcebd Iustin Pop
1635 255dcebd Iustin Pop
1636 255dcebd Iustin Pop
def OSFromDisk(name, base_dir=None):
1637 255dcebd Iustin Pop
  """Create an OS instance from disk.
1638 255dcebd Iustin Pop

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

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

1646 255dcebd Iustin Pop
  @type base_dir: string
1647 255dcebd Iustin Pop
  @keyword base_dir: Base directory containing OS installations.
1648 255dcebd Iustin Pop
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1649 255dcebd Iustin Pop
  @rtype: L{objects.OS}
1650 255dcebd Iustin Pop
  @return: the OS instance if we find a valid one
1651 255dcebd Iustin Pop
  @raise RPCFail: if we don't find a valid OS
1652 255dcebd Iustin Pop

1653 255dcebd Iustin Pop
  """
1654 255dcebd Iustin Pop
  status, payload = _TryOSFromDisk(name, base_dir)
1655 255dcebd Iustin Pop
1656 255dcebd Iustin Pop
  if not status:
1657 255dcebd Iustin Pop
    _Fail(payload)
1658 a8083063 Iustin Pop
1659 255dcebd Iustin Pop
  return payload
1660 a8083063 Iustin Pop
1661 a8083063 Iustin Pop
1662 d1a7d66f Guido Trotter
def OSEnvironment(instance, os, debug=0):
1663 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1664 2266edb2 Guido Trotter

1665 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1666 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1667 d1a7d66f Guido Trotter
  @type os: L{objects.OS}
1668 d1a7d66f Guido Trotter
  @param os: operating system for which the environment is being built
1669 2266edb2 Guido Trotter
  @type debug: integer
1670 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1671 2266edb2 Guido Trotter
  @rtype: dict
1672 2266edb2 Guido Trotter
  @return: dict of environment variables
1673 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1674 10c2650b Iustin Pop
      cannot be found
1675 2266edb2 Guido Trotter

1676 2266edb2 Guido Trotter
  """
1677 2266edb2 Guido Trotter
  result = {}
1678 d1a7d66f Guido Trotter
  api_version = max(constants.OS_API_VERSIONS.intersection(os.api_versions))
1679 d1a7d66f Guido Trotter
  result['OS_API_VERSION'] = '%d' % api_version
1680 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1681 15552312 Iustin Pop
  result['INSTANCE_OS'] = instance.os
1682 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1683 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1684 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1685 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1686 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1687 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1688 2266edb2 Guido Trotter
    if real_disk is None:
1689 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1690 2266edb2 Guido Trotter
                                    str(disk))
1691 2266edb2 Guido Trotter
    real_disk.Open()
1692 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1693 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
1694 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1695 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1696 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1697 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1698 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1699 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1700 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1701 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1702 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1703 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1704 2266edb2 Guido Trotter
    if nic.ip:
1705 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1706 1ba9227f Guido Trotter
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1707 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1708 1ba9227f Guido Trotter
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1709 1ba9227f Guido Trotter
    if nic.nicparams[constants.NIC_LINK]:
1710 1ba9227f Guido Trotter
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1711 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1712 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1713 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1714 2266edb2 Guido Trotter
1715 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1716 67fc3042 Iustin Pop
    for key, value in source.items():
1717 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1718 67fc3042 Iustin Pop
1719 2266edb2 Guido Trotter
  return result
1720 a8083063 Iustin Pop
1721 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
1722 594609c0 Iustin Pop
  """Grow a stack of block devices.
1723 594609c0 Iustin Pop

1724 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1725 10c2650b Iustin Pop
  first ones to resize.
1726 594609c0 Iustin Pop

1727 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1728 10c2650b Iustin Pop
  @param disk: the disk to be grown
1729 10c2650b Iustin Pop
  @rtype: (status, result)
1730 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1731 10c2650b Iustin Pop
      (True/False), and the errors message if status
1732 10c2650b Iustin Pop
      is False
1733 594609c0 Iustin Pop

1734 594609c0 Iustin Pop
  """
1735 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1736 594609c0 Iustin Pop
  if r_dev is None:
1737 afdc3985 Iustin Pop
    _Fail("Cannot find block device %s", disk)
1738 594609c0 Iustin Pop
1739 594609c0 Iustin Pop
  try:
1740 594609c0 Iustin Pop
    r_dev.Grow(amount)
1741 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1742 2cc6781a Iustin Pop
    _Fail("Failed to grow block device: %s", err, exc=True)
1743 594609c0 Iustin Pop
1744 594609c0 Iustin Pop
1745 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
1746 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1747 a8083063 Iustin Pop

1748 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1749 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1750 a8083063 Iustin Pop

1751 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1752 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1753 e9e9263d Guido Trotter
  @rtype: string
1754 e9e9263d Guido Trotter
  @return: snapshot disk path
1755 a8083063 Iustin Pop

1756 098c0958 Michael Hanselmann
  """
1757 a8083063 Iustin Pop
  if disk.children:
1758 a8083063 Iustin Pop
    if len(disk.children) == 1:
1759 a8083063 Iustin Pop
      # only one child, let's recurse on it
1760 821d1bd1 Iustin Pop
      return BlockdevSnapshot(disk.children[0])
1761 a8083063 Iustin Pop
    else:
1762 a8083063 Iustin Pop
      # more than one child, choose one that matches
1763 a8083063 Iustin Pop
      for child in disk.children:
1764 a8083063 Iustin Pop
        if child.size == disk.size:
1765 a8083063 Iustin Pop
          # return implies breaking the loop
1766 821d1bd1 Iustin Pop
          return BlockdevSnapshot(child)
1767 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1768 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1769 a8083063 Iustin Pop
    if r_dev is not None:
1770 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1771 c26a6bd2 Iustin Pop
      return r_dev.Snapshot(disk.size)
1772 a8083063 Iustin Pop
    else:
1773 87812fd3 Iustin Pop
      _Fail("Cannot find block device %s", disk)
1774 a8083063 Iustin Pop
  else:
1775 87812fd3 Iustin Pop
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1776 87812fd3 Iustin Pop
          disk.unique_id, disk.dev_type)
1777 a8083063 Iustin Pop
1778 a8083063 Iustin Pop
1779 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1780 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1781 a8083063 Iustin Pop

1782 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1783 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1784 74c47259 Iustin Pop
  @type dest_node: str
1785 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1786 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1787 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1788 74c47259 Iustin Pop
  @type cluster_name: str
1789 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1790 74c47259 Iustin Pop
  @type idx: int
1791 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1792 74c47259 Iustin Pop
      used to export to the OS scripts environment
1793 c26a6bd2 Iustin Pop
  @rtype: None
1794 a8083063 Iustin Pop

1795 098c0958 Michael Hanselmann
  """
1796 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1797 d1a7d66f Guido Trotter
  export_env = OSEnvironment(instance, inst_os)
1798 d1a7d66f Guido Trotter
1799 a8083063 Iustin Pop
  export_script = inst_os.export_script
1800 a8083063 Iustin Pop
1801 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1802 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1803 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1804 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1805 0607699d Guido Trotter
  real_disk = _RecursiveFindBD(disk)
1806 0607699d Guido Trotter
  if real_disk is None:
1807 ba55d062 Iustin Pop
    _Fail("Block device '%s' is not set up", disk)
1808 ba55d062 Iustin Pop
1809 0607699d Guido Trotter
  real_disk.Open()
1810 0607699d Guido Trotter
1811 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1812 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
1813 a8083063 Iustin Pop
1814 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1815 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1816 a8083063 Iustin Pop
1817 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1818 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1819 a8083063 Iustin Pop
  # valid parameters
1820 0607699d Guido Trotter
  expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1821 0607699d Guido Trotter
                               export_script, logfile)
1822 a8083063 Iustin Pop
1823 a8083063 Iustin Pop
  comprcmd = "gzip"
1824 a8083063 Iustin Pop
1825 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1826 00003458 Guido Trotter
                                destdir, destdir, destfile)
1827 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1828 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1829 62c9ec92 Iustin Pop
                                                   destcmd)
1830 a8083063 Iustin Pop
1831 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1832 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1833 a8083063 Iustin Pop
1834 0607699d Guido Trotter
  result = utils.RunCmd(command, env=export_env)
1835 a8083063 Iustin Pop
1836 a8083063 Iustin Pop
  if result.failed:
1837 ba55d062 Iustin Pop
    _Fail("OS snapshot export command '%s' returned error: %s"
1838 ba55d062 Iustin Pop
          " output: %s", command, result.fail_reason, result.output)
1839 a8083063 Iustin Pop
1840 a8083063 Iustin Pop
1841 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1842 a8083063 Iustin Pop
  """Write out the export configuration information.
1843 a8083063 Iustin Pop

1844 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1845 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
1846 10c2650b Iustin Pop
      saving configuration
1847 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
1848 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
1849 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
1850 a8083063 Iustin Pop

1851 c26a6bd2 Iustin Pop
  @rtype: None
1852 a8083063 Iustin Pop

1853 098c0958 Michael Hanselmann
  """
1854 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1855 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1856 a8083063 Iustin Pop
1857 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1858 a8083063 Iustin Pop
1859 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1860 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1861 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1862 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1863 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1864 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1865 a8083063 Iustin Pop
1866 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1867 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1868 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
1869 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
1870 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1871 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
1872 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1873 66f93869 Manuel Franceschini
1874 95268cc3 Iustin Pop
  nic_total = 0
1875 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1876 95268cc3 Iustin Pop
    nic_total += 1
1877 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1878 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1879 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1880 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1881 38206f3c Iustin Pop
               '%s' % nic.bridge)
1882 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1883 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1884 a8083063 Iustin Pop
1885 726d7d68 Iustin Pop
  disk_total = 0
1886 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1887 19d7f90a Guido Trotter
    if disk:
1888 726d7d68 Iustin Pop
      disk_total += 1
1889 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1890 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
1891 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1892 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
1893 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1894 19d7f90a Guido Trotter
                 ('%d' % disk.size))
1895 a8083063 Iustin Pop
1896 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1897 a8083063 Iustin Pop
1898 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1899 726d7d68 Iustin Pop
                  data=config.Dumps())
1900 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1901 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1902 a8083063 Iustin Pop
1903 a8083063 Iustin Pop
1904 a8083063 Iustin Pop
def ExportInfo(dest):
1905 a8083063 Iustin Pop
  """Get export configuration information.
1906 a8083063 Iustin Pop

1907 10c2650b Iustin Pop
  @type dest: str
1908 10c2650b Iustin Pop
  @param dest: directory containing the export
1909 a8083063 Iustin Pop

1910 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
1911 10c2650b Iustin Pop
  @return: a serializable config file containing the
1912 10c2650b Iustin Pop
      export info
1913 a8083063 Iustin Pop

1914 a8083063 Iustin Pop
  """
1915 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1916 a8083063 Iustin Pop
1917 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1918 a8083063 Iustin Pop
  config.read(cff)
1919 a8083063 Iustin Pop
1920 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1921 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1922 3eccac06 Iustin Pop
    _Fail("Export info file doesn't have the required fields")
1923 a8083063 Iustin Pop
1924 c26a6bd2 Iustin Pop
  return config.Dumps()
1925 a8083063 Iustin Pop
1926 a8083063 Iustin Pop
1927 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1928 a8083063 Iustin Pop
  """Import an os image into an instance.
1929 a8083063 Iustin Pop

1930 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1931 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
1932 6c0af70e Guido Trotter
  @type src_node: string
1933 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
1934 6c0af70e Guido Trotter
  @type src_images: list of string
1935 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
1936 6c0af70e Guido Trotter
  @rtype: list of boolean
1937 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
1938 a8083063 Iustin Pop

1939 a8083063 Iustin Pop
  """
1940 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1941 d1a7d66f Guido Trotter
  import_env = OSEnvironment(instance, inst_os)
1942 a8083063 Iustin Pop
  import_script = inst_os.import_script
1943 a8083063 Iustin Pop
1944 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1945 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1946 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1947 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1948 a8083063 Iustin Pop
1949 a8083063 Iustin Pop
  comprcmd = "gunzip"
1950 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1951 d868edb4 Iustin Pop
                               import_script, logfile)
1952 a8083063 Iustin Pop
1953 6c0af70e Guido Trotter
  final_result = []
1954 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
1955 6c0af70e Guido Trotter
    if image:
1956 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
1957 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1958 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
1959 6c0af70e Guido Trotter
                                                       destcmd)
1960 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1961 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1962 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
1963 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
1964 6c0af70e Guido Trotter
      if result.failed:
1965 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
1966 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
1967 726d7d68 Iustin Pop
                      result.output)
1968 944bf548 Iustin Pop
        final_result.append("error importing disk %d: %s, %s" %
1969 944bf548 Iustin Pop
                            (idx, result.fail_reason, result.output[-100]))
1970 a8083063 Iustin Pop
1971 944bf548 Iustin Pop
  if final_result:
1972 afdc3985 Iustin Pop
    _Fail("; ".join(final_result), log=False)
1973 a8083063 Iustin Pop
1974 a8083063 Iustin Pop
1975 a8083063 Iustin Pop
def ListExports():
1976 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1977 098c0958 Michael Hanselmann

1978 10c2650b Iustin Pop
  @rtype: list
1979 10c2650b Iustin Pop
  @return: list of the exports
1980 10c2650b Iustin Pop

1981 a8083063 Iustin Pop
  """
1982 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1983 c26a6bd2 Iustin Pop
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1984 a8083063 Iustin Pop
  else:
1985 afdc3985 Iustin Pop
    _Fail("No exports directory")
1986 a8083063 Iustin Pop
1987 a8083063 Iustin Pop
1988 a8083063 Iustin Pop
def RemoveExport(export):
1989 a8083063 Iustin Pop
  """Remove an existing export from the node.
1990 a8083063 Iustin Pop

1991 10c2650b Iustin Pop
  @type export: str
1992 10c2650b Iustin Pop
  @param export: the name of the export to remove
1993 c26a6bd2 Iustin Pop
  @rtype: None
1994 a8083063 Iustin Pop

1995 098c0958 Michael Hanselmann
  """
1996 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1997 a8083063 Iustin Pop
1998 35fbcd11 Iustin Pop
  try:
1999 35fbcd11 Iustin Pop
    shutil.rmtree(target)
2000 35fbcd11 Iustin Pop
  except EnvironmentError, err:
2001 35fbcd11 Iustin Pop
    _Fail("Error while removing the export: %s", err, exc=True)
2002 a8083063 Iustin Pop
2003 a8083063 Iustin Pop
2004 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2005 f3e513ad Iustin Pop
  """Rename a list of block devices.
2006 f3e513ad Iustin Pop

2007 10c2650b Iustin Pop
  @type devlist: list of tuples
2008 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2009 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2010 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2011 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2012 10c2650b Iustin Pop
      rename it to
2013 10c2650b Iustin Pop
  @rtype: boolean
2014 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2015 f3e513ad Iustin Pop

2016 f3e513ad Iustin Pop
  """
2017 6b5e3f70 Iustin Pop
  msgs = []
2018 f3e513ad Iustin Pop
  result = True
2019 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2020 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2021 f3e513ad Iustin Pop
    if dev is None:
2022 6b5e3f70 Iustin Pop
      msgs.append("Can't find device %s in rename" % str(disk))
2023 f3e513ad Iustin Pop
      result = False
2024 f3e513ad Iustin Pop
      continue
2025 f3e513ad Iustin Pop
    try:
2026 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2027 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2028 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2029 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2030 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2031 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2032 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2033 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2034 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2035 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2036 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2037 6b5e3f70 Iustin Pop
      msgs.append("Can't rename device '%s' to '%s': %s" %
2038 6b5e3f70 Iustin Pop
                  (dev, unique_id, err))
2039 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2040 f3e513ad Iustin Pop
      result = False
2041 afdc3985 Iustin Pop
  if not result:
2042 afdc3985 Iustin Pop
    _Fail("; ".join(msgs))
2043 f3e513ad Iustin Pop
2044 f3e513ad Iustin Pop
2045 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2046 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2047 778b75bb Manuel Franceschini

2048 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2049 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2050 778b75bb Manuel Franceschini
  directory are allowed.
2051 778b75bb Manuel Franceschini

2052 b1206984 Iustin Pop
  @type file_storage_dir: str
2053 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2054 d61cbe76 Iustin Pop

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

2057 778b75bb Manuel Franceschini
  """
2058 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2059 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2060 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2061 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2062 778b75bb Manuel Franceschini
      base_file_storage_dir):
2063 b2b8bcce Iustin Pop
    _Fail("File storage directory '%s' is not under base file"
2064 b2b8bcce Iustin Pop
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2065 778b75bb Manuel Franceschini
  return file_storage_dir
2066 778b75bb Manuel Franceschini
2067 778b75bb Manuel Franceschini
2068 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2069 778b75bb Manuel Franceschini
  """Create file storage directory.
2070 778b75bb Manuel Franceschini

2071 b1206984 Iustin Pop
  @type file_storage_dir: str
2072 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2073 778b75bb Manuel Franceschini

2074 b1206984 Iustin Pop
  @rtype: tuple
2075 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2076 b1206984 Iustin Pop
      creation was successful or not
2077 778b75bb Manuel Franceschini

2078 778b75bb Manuel Franceschini
  """
2079 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2080 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2081 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2082 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2083 b2b8bcce Iustin Pop
            file_storage_dir)
2084 778b75bb Manuel Franceschini
  else:
2085 b2b8bcce Iustin Pop
    try:
2086 b2b8bcce Iustin Pop
      os.makedirs(file_storage_dir, 0750)
2087 b2b8bcce Iustin Pop
    except OSError, err:
2088 b2b8bcce Iustin Pop
      _Fail("Cannot create file storage directory '%s': %s",
2089 b2b8bcce Iustin Pop
            file_storage_dir, err, exc=True)
2090 778b75bb Manuel Franceschini
2091 778b75bb Manuel Franceschini
2092 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2093 778b75bb Manuel Franceschini
  """Remove file storage directory.
2094 778b75bb Manuel Franceschini

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

2097 10c2650b Iustin Pop
  @type file_storage_dir: str
2098 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2099 10c2650b Iustin Pop
  @rtype: tuple (success,)
2100 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2101 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2102 778b75bb Manuel Franceschini

2103 778b75bb Manuel Franceschini
  """
2104 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2105 b2b8bcce Iustin Pop
  if os.path.exists(file_storage_dir):
2106 b2b8bcce Iustin Pop
    if not os.path.isdir(file_storage_dir):
2107 b2b8bcce Iustin Pop
      _Fail("Specified Storage directory '%s' is not a directory",
2108 b2b8bcce Iustin Pop
            file_storage_dir)
2109 afdc3985 Iustin Pop
    # deletes dir only if empty, otherwise we want to fail the rpc call
2110 b2b8bcce Iustin Pop
    try:
2111 b2b8bcce Iustin Pop
      os.rmdir(file_storage_dir)
2112 b2b8bcce Iustin Pop
    except OSError, err:
2113 b2b8bcce Iustin Pop
      _Fail("Cannot remove file storage directory '%s': %s",
2114 b2b8bcce Iustin Pop
            file_storage_dir, err)
2115 b2b8bcce Iustin Pop
2116 778b75bb Manuel Franceschini
2117 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2118 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2119 778b75bb Manuel Franceschini

2120 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2121 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2122 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2123 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2124 10c2650b Iustin Pop
  @rtype: tuple (success,)
2125 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2126 10c2650b Iustin Pop
      whether the operation was successful
2127 778b75bb Manuel Franceschini

2128 778b75bb Manuel Franceschini
  """
2129 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2130 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2131 b2b8bcce Iustin Pop
  if not os.path.exists(new_file_storage_dir):
2132 b2b8bcce Iustin Pop
    if os.path.isdir(old_file_storage_dir):
2133 b2b8bcce Iustin Pop
      try:
2134 b2b8bcce Iustin Pop
        os.rename(old_file_storage_dir, new_file_storage_dir)
2135 b2b8bcce Iustin Pop
      except OSError, err:
2136 b2b8bcce Iustin Pop
        _Fail("Cannot rename '%s' to '%s': %s",
2137 b2b8bcce Iustin Pop
              old_file_storage_dir, new_file_storage_dir, err)
2138 778b75bb Manuel Franceschini
    else:
2139 b2b8bcce Iustin Pop
      _Fail("Specified storage dir '%s' is not a directory",
2140 b2b8bcce Iustin Pop
            old_file_storage_dir)
2141 b2b8bcce Iustin Pop
  else:
2142 b2b8bcce Iustin Pop
    if os.path.exists(old_file_storage_dir):
2143 b2b8bcce Iustin Pop
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2144 b2b8bcce Iustin Pop
            old_file_storage_dir, new_file_storage_dir)
2145 778b75bb Manuel Franceschini
2146 778b75bb Manuel Franceschini
2147 c8457ce7 Iustin Pop
def _EnsureJobQueueFile(file_name):
2148 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2149 ca52cdeb Michael Hanselmann

2150 10c2650b Iustin Pop
  @type file_name: str
2151 10c2650b Iustin Pop
  @param file_name: the file name we should check
2152 c8457ce7 Iustin Pop
  @rtype: None
2153 c8457ce7 Iustin Pop
  @raises RPCFail: if the file is not valid
2154 10c2650b Iustin Pop

2155 ca52cdeb Michael Hanselmann
  """
2156 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2157 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2158 dc31eae3 Michael Hanselmann
2159 dc31eae3 Michael Hanselmann
  if not result:
2160 c8457ce7 Iustin Pop
    _Fail("Passed job queue file '%s' does not belong to"
2161 c8457ce7 Iustin Pop
          " the queue directory '%s'", file_name, queue_dir)
2162 dc31eae3 Michael Hanselmann
2163 dc31eae3 Michael Hanselmann
2164 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2165 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2166 dc31eae3 Michael Hanselmann

2167 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2168 10c2650b Iustin Pop
  checking.
2169 10c2650b Iustin Pop

2170 10c2650b Iustin Pop
  @type file_name: str
2171 10c2650b Iustin Pop
  @param file_name: the job file name
2172 10c2650b Iustin Pop
  @type content: str
2173 10c2650b Iustin Pop
  @param content: the new job contents
2174 10c2650b Iustin Pop
  @rtype: boolean
2175 10c2650b Iustin Pop
  @return: the success of the operation
2176 10c2650b Iustin Pop

2177 dc31eae3 Michael Hanselmann
  """
2178 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(file_name)
2179 ca52cdeb Michael Hanselmann
2180 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2181 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2182 ca52cdeb Michael Hanselmann
2183 ca52cdeb Michael Hanselmann
2184 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2185 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2186 af5ebcb1 Michael Hanselmann

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

2189 10c2650b Iustin Pop
  @type old: str
2190 10c2650b Iustin Pop
  @param old: the old (actual) file name
2191 10c2650b Iustin Pop
  @type new: str
2192 10c2650b Iustin Pop
  @param new: the desired file name
2193 c8457ce7 Iustin Pop
  @rtype: tuple
2194 c8457ce7 Iustin Pop
  @return: the success of the operation and payload
2195 10c2650b Iustin Pop

2196 af5ebcb1 Michael Hanselmann
  """
2197 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(old)
2198 c8457ce7 Iustin Pop
  _EnsureJobQueueFile(new)
2199 af5ebcb1 Michael Hanselmann
2200 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2201 af5ebcb1 Michael Hanselmann
2202 af5ebcb1 Michael Hanselmann
2203 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2204 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2205 5d672980 Iustin Pop

2206 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2207 5d672980 Iustin Pop

2208 10c2650b Iustin Pop
  @type drain_flag: boolean
2209 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2210 c8457ce7 Iustin Pop
  @rtype: truple
2211 c8457ce7 Iustin Pop
  @return: always True, None
2212 10c2650b Iustin Pop
  @warning: the function always returns True
2213 5d672980 Iustin Pop

2214 5d672980 Iustin Pop
  """
2215 5d672980 Iustin Pop
  if drain_flag:
2216 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2217 5d672980 Iustin Pop
  else:
2218 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2219 5d672980 Iustin Pop
2220 5d672980 Iustin Pop
2221 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2222 d61cbe76 Iustin Pop
  """Closes the given block devices.
2223 d61cbe76 Iustin Pop

2224 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2225 10c2650b Iustin Pop
  DRBD).
2226 10c2650b Iustin Pop

2227 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2228 b2e7666a Iustin Pop
      of this instance will be removed
2229 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2230 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2231 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2232 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2233 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2234 10c2650b Iustin Pop
      which will contain the error details in case we
2235 10c2650b Iustin Pop
      failed
2236 d61cbe76 Iustin Pop

2237 d61cbe76 Iustin Pop
  """
2238 d61cbe76 Iustin Pop
  bdevs = []
2239 d61cbe76 Iustin Pop
  for cf in disks:
2240 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2241 d61cbe76 Iustin Pop
    if rd is None:
2242 2cc6781a Iustin Pop
      _Fail("Can't find device %s", cf)
2243 d61cbe76 Iustin Pop
    bdevs.append(rd)
2244 d61cbe76 Iustin Pop
2245 d61cbe76 Iustin Pop
  msg = []
2246 d61cbe76 Iustin Pop
  for rd in bdevs:
2247 d61cbe76 Iustin Pop
    try:
2248 d61cbe76 Iustin Pop
      rd.Close()
2249 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2250 d61cbe76 Iustin Pop
      msg.append(str(err))
2251 d61cbe76 Iustin Pop
  if msg:
2252 afdc3985 Iustin Pop
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2253 d61cbe76 Iustin Pop
  else:
2254 b2e7666a Iustin Pop
    if instance_name:
2255 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2256 d61cbe76 Iustin Pop
2257 d61cbe76 Iustin Pop
2258 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2259 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2260 6217e295 Iustin Pop

2261 6217e295 Iustin Pop
  @type hvname: string
2262 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2263 6217e295 Iustin Pop
  @type hvparams: dict
2264 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2265 c26a6bd2 Iustin Pop
  @rtype: None
2266 6217e295 Iustin Pop

2267 6217e295 Iustin Pop
  """
2268 6217e295 Iustin Pop
  try:
2269 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2270 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2271 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2272 afdc3985 Iustin Pop
    _Fail(str(err), log=False)
2273 6217e295 Iustin Pop
2274 6217e295 Iustin Pop
2275 56aa9fd5 Iustin Pop
def DemoteFromMC():
2276 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2277 56aa9fd5 Iustin Pop

2278 56aa9fd5 Iustin Pop
  """
2279 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2280 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2281 56aa9fd5 Iustin Pop
  if master == myself:
2282 afdc3985 Iustin Pop
    _Fail("ssconf status shows I'm the master node, will not demote")
2283 56aa9fd5 Iustin Pop
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2284 56aa9fd5 Iustin Pop
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2285 afdc3985 Iustin Pop
    _Fail("The master daemon is running, will not demote")
2286 56aa9fd5 Iustin Pop
  try:
2287 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2288 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2289 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2290 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2291 afdc3985 Iustin Pop
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2292 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2293 56aa9fd5 Iustin Pop
2294 56aa9fd5 Iustin Pop
2295 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2296 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2297 6b93ec9d Iustin Pop

2298 6b93ec9d Iustin Pop
  """
2299 6b93ec9d Iustin Pop
  # set the correct physical ID
2300 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2301 6b93ec9d Iustin Pop
  for cf in disks:
2302 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2303 6b93ec9d Iustin Pop
2304 6b93ec9d Iustin Pop
  bdevs = []
2305 6b93ec9d Iustin Pop
2306 6b93ec9d Iustin Pop
  for cf in disks:
2307 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2308 6b93ec9d Iustin Pop
    if rd is None:
2309 5a533f8a Iustin Pop
      _Fail("Can't find device %s", cf)
2310 6b93ec9d Iustin Pop
    bdevs.append(rd)
2311 5a533f8a Iustin Pop
  return bdevs
2312 6b93ec9d Iustin Pop
2313 6b93ec9d Iustin Pop
2314 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2315 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2316 6b93ec9d Iustin Pop

2317 6b93ec9d Iustin Pop
  """
2318 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2319 6b93ec9d Iustin Pop
2320 6b93ec9d Iustin Pop
  # disconnect disks
2321 6b93ec9d Iustin Pop
  for rd in bdevs:
2322 6b93ec9d Iustin Pop
    try:
2323 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2324 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2325 2cc6781a Iustin Pop
      _Fail("Can't change network configuration to standalone mode: %s",
2326 2cc6781a Iustin Pop
            err, exc=True)
2327 6b93ec9d Iustin Pop
2328 6b93ec9d Iustin Pop
2329 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2330 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2331 6b93ec9d Iustin Pop

2332 6b93ec9d Iustin Pop
  """
2333 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2334 6b93ec9d Iustin Pop
2335 6b93ec9d Iustin Pop
  if multimaster:
2336 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2337 6b93ec9d Iustin Pop
      try:
2338 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2339 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2340 2cc6781a Iustin Pop
        _Fail("Can't create symlink: %s", err)
2341 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2342 6b93ec9d Iustin Pop
  # needed primary mode
2343 6b93ec9d Iustin Pop
  for rd in bdevs:
2344 6b93ec9d Iustin Pop
    try:
2345 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2346 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2347 2cc6781a Iustin Pop
      _Fail("Can't change network configuration: %s", err)
2348 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2349 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2350 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2351 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2352 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2353 6b93ec9d Iustin Pop
  RECONNECT_TIMEOUT = 2 * 60
2354 6b93ec9d Iustin Pop
  sleep_time = 0.100 # start with 100 miliseconds
2355 6b93ec9d Iustin Pop
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2356 6b93ec9d Iustin Pop
  while time.time() < timeout_limit:
2357 6b93ec9d Iustin Pop
    all_connected = True
2358 6b93ec9d Iustin Pop
    for rd in bdevs:
2359 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2360 6b93ec9d Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2361 6b93ec9d Iustin Pop
        all_connected = False
2362 6b93ec9d Iustin Pop
      if stats.is_standalone:
2363 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2364 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2365 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2366 6b93ec9d Iustin Pop
        try:
2367 c738375b Iustin Pop
          rd.AttachNet(multimaster)
2368 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2369 2cc6781a Iustin Pop
          _Fail("Can't change network configuration: %s", err)
2370 6b93ec9d Iustin Pop
    if all_connected:
2371 6b93ec9d Iustin Pop
      break
2372 6b93ec9d Iustin Pop
    time.sleep(sleep_time)
2373 6b93ec9d Iustin Pop
    sleep_time = min(5, sleep_time * 1.5)
2374 6b93ec9d Iustin Pop
  if not all_connected:
2375 afdc3985 Iustin Pop
    _Fail("Timeout in disk reconnecting")
2376 6b93ec9d Iustin Pop
  if multimaster:
2377 6b93ec9d Iustin Pop
    # change to primary mode
2378 6b93ec9d Iustin Pop
    for rd in bdevs:
2379 d3da87b8 Iustin Pop
      try:
2380 d3da87b8 Iustin Pop
        rd.Open()
2381 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
2382 2cc6781a Iustin Pop
        _Fail("Can't change to primary mode: %s", err)
2383 6b93ec9d Iustin Pop
2384 6b93ec9d Iustin Pop
2385 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2386 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2387 6b93ec9d Iustin Pop

2388 6b93ec9d Iustin Pop
  """
2389 5a533f8a Iustin Pop
  bdevs = _FindDisks(nodes_ip, disks)
2390 6b93ec9d Iustin Pop
2391 6b93ec9d Iustin Pop
  min_resync = 100
2392 6b93ec9d Iustin Pop
  alldone = True
2393 6b93ec9d Iustin Pop
  for rd in bdevs:
2394 6b93ec9d Iustin Pop
    stats = rd.GetProcStatus()
2395 6b93ec9d Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2396 afdc3985 Iustin Pop
      _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2397 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2398 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2399 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2400 afdc3985 Iustin Pop
2401 c26a6bd2 Iustin Pop
  return (alldone, min_resync)
2402 6b93ec9d Iustin Pop
2403 6b93ec9d Iustin Pop
2404 f5118ade Iustin Pop
def PowercycleNode(hypervisor_type):
2405 f5118ade Iustin Pop
  """Hard-powercycle the node.
2406 f5118ade Iustin Pop

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

2410 f5118ade Iustin Pop
  """
2411 f5118ade Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2412 f5118ade Iustin Pop
  try:
2413 f5118ade Iustin Pop
    pid = os.fork()
2414 29921401 Iustin Pop
  except OSError:
2415 f5118ade Iustin Pop
    # if we can't fork, we'll pretend that we're in the child process
2416 f5118ade Iustin Pop
    pid = 0
2417 f5118ade Iustin Pop
  if pid > 0:
2418 c26a6bd2 Iustin Pop
    return "Reboot scheduled in 5 seconds"
2419 f5118ade Iustin Pop
  time.sleep(5)
2420 f5118ade Iustin Pop
  hyper.PowercycleNode()
2421 f5118ade Iustin Pop
2422 f5118ade Iustin Pop
2423 a8083063 Iustin Pop
class HooksRunner(object):
2424 a8083063 Iustin Pop
  """Hook runner.
2425 a8083063 Iustin Pop

2426 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2427 10c2650b Iustin Pop
  on the master side.
2428 a8083063 Iustin Pop

2429 a8083063 Iustin Pop
  """
2430 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2431 a8083063 Iustin Pop
2432 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2433 a8083063 Iustin Pop
    """Constructor for hooks runner.
2434 a8083063 Iustin Pop

2435 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2436 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2437 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2438 a8083063 Iustin Pop

2439 a8083063 Iustin Pop
    """
2440 a8083063 Iustin Pop
    if hooks_base_dir is None:
2441 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2442 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2443 a8083063 Iustin Pop
2444 a8083063 Iustin Pop
  @staticmethod
2445 a8083063 Iustin Pop
  def ExecHook(script, env):
2446 a8083063 Iustin Pop
    """Exec one hook script.
2447 a8083063 Iustin Pop

2448 10c2650b Iustin Pop
    @type script: str
2449 10c2650b Iustin Pop
    @param script: the full path to the script
2450 10c2650b Iustin Pop
    @type env: dict
2451 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2452 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2453 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2454 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2455 10c2650b Iustin Pop
        which will contain the error details in case we
2456 10c2650b Iustin Pop
        failed
2457 a8083063 Iustin Pop

2458 a8083063 Iustin Pop
    """
2459 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2460 a8083063 Iustin Pop
    fdstdin = None
2461 a8083063 Iustin Pop
    try:
2462 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2463 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2464 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2465 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2466 a8083063 Iustin Pop
      output = ""
2467 a8083063 Iustin Pop
      try:
2468 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2469 a8083063 Iustin Pop
        child.stdout.close()
2470 a8083063 Iustin Pop
      except EnvironmentError, err:
2471 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2472 a8083063 Iustin Pop
2473 a8083063 Iustin Pop
      while True:
2474 a8083063 Iustin Pop
        try:
2475 a8083063 Iustin Pop
          result = child.wait()
2476 a8083063 Iustin Pop
          break
2477 a8083063 Iustin Pop
        except EnvironmentError, err:
2478 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2479 a8083063 Iustin Pop
            continue
2480 a8083063 Iustin Pop
          raise
2481 a8083063 Iustin Pop
    finally:
2482 a8083063 Iustin Pop
      # try not to leak fds
2483 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2484 a8083063 Iustin Pop
        if fd is not None:
2485 a8083063 Iustin Pop
          try:
2486 a8083063 Iustin Pop
            fd.close()
2487 a8083063 Iustin Pop
          except EnvironmentError, err:
2488 a8083063 Iustin Pop
            # just log the error
2489 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2490 a8083063 Iustin Pop
            pass
2491 a8083063 Iustin Pop
2492 26f15862 Iustin Pop
    return result == 0, utils.SafeEncode(output.strip())
2493 a8083063 Iustin Pop
2494 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2495 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2496 a8083063 Iustin Pop

2497 10c2650b Iustin Pop
    @type hpath: str
2498 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2499 10c2650b Iustin Pop
        holds the scripts
2500 10c2650b Iustin Pop
    @type phase: str
2501 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2502 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2503 10c2650b Iustin Pop
    @type env: dict
2504 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2505 10c2650b Iustin Pop
    @rtype: list
2506 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2507 10c2650b Iustin Pop
      - script path
2508 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2509 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2510 10c2650b Iustin Pop
      - output of the script
2511 10c2650b Iustin Pop

2512 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2513 10c2650b Iustin Pop
        parameters
2514 a8083063 Iustin Pop

2515 a8083063 Iustin Pop
    """
2516 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2517 a8083063 Iustin Pop
      suffix = "pre"
2518 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2519 a8083063 Iustin Pop
      suffix = "post"
2520 a8083063 Iustin Pop
    else:
2521 3fb4f740 Iustin Pop
      _Fail("Unknown hooks phase '%s'", phase)
2522 3fb4f740 Iustin Pop
2523 a8083063 Iustin Pop
    rr = []
2524 a8083063 Iustin Pop
2525 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2526 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2527 a8083063 Iustin Pop
    try:
2528 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2529 29921401 Iustin Pop
    except OSError:
2530 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2531 c26a6bd2 Iustin Pop
      return rr
2532 a8083063 Iustin Pop
2533 a8083063 Iustin Pop
    # we use the standard python sort order,
2534 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2535 a8083063 Iustin Pop
    dir_contents.sort()
2536 a8083063 Iustin Pop
    for relname in dir_contents:
2537 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2538 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2539 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2540 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2541 a8083063 Iustin Pop
        output = ""
2542 a8083063 Iustin Pop
      else:
2543 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2544 a8083063 Iustin Pop
        if not result:
2545 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2546 a8083063 Iustin Pop
        else:
2547 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2548 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2549 a8083063 Iustin Pop
2550 c26a6bd2 Iustin Pop
    return rr
2551 3f78eef2 Iustin Pop
2552 3f78eef2 Iustin Pop
2553 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2554 8d528b7c Iustin Pop
  """IAllocator runner.
2555 8d528b7c Iustin Pop

2556 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2557 8d528b7c Iustin Pop
  the master side.
2558 8d528b7c Iustin Pop

2559 8d528b7c Iustin Pop
  """
2560 8d528b7c Iustin Pop
  def Run(self, name, idata):
2561 8d528b7c Iustin Pop
    """Run an iallocator script.
2562 8d528b7c Iustin Pop

2563 10c2650b Iustin Pop
    @type name: str
2564 10c2650b Iustin Pop
    @param name: the iallocator script name
2565 10c2650b Iustin Pop
    @type idata: str
2566 10c2650b Iustin Pop
    @param idata: the allocator input data
2567 10c2650b Iustin Pop

2568 10c2650b Iustin Pop
    @rtype: tuple
2569 87f5c298 Iustin Pop
    @return: two element tuple of:
2570 87f5c298 Iustin Pop
       - status
2571 87f5c298 Iustin Pop
       - either error message or stdout of allocator (for success)
2572 8d528b7c Iustin Pop

2573 8d528b7c Iustin Pop
    """
2574 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2575 8d528b7c Iustin Pop
                                  os.path.isfile)
2576 8d528b7c Iustin Pop
    if alloc_script is None:
2577 87f5c298 Iustin Pop
      _Fail("iallocator module '%s' not found in the search path", name)
2578 8d528b7c Iustin Pop
2579 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2580 8d528b7c Iustin Pop
    try:
2581 8d528b7c Iustin Pop
      os.write(fd, idata)
2582 8d528b7c Iustin Pop
      os.close(fd)
2583 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2584 8d528b7c Iustin Pop
      if result.failed:
2585 87f5c298 Iustin Pop
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2586 87f5c298 Iustin Pop
              name, result.fail_reason, result.output)
2587 8d528b7c Iustin Pop
    finally:
2588 8d528b7c Iustin Pop
      os.unlink(fin_name)
2589 8d528b7c Iustin Pop
2590 c26a6bd2 Iustin Pop
    return result.stdout
2591 8d528b7c Iustin Pop
2592 8d528b7c Iustin Pop
2593 3f78eef2 Iustin Pop
class DevCacheManager(object):
2594 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2595 3f78eef2 Iustin Pop

2596 3f78eef2 Iustin Pop
  """
2597 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2598 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2599 3f78eef2 Iustin Pop
2600 3f78eef2 Iustin Pop
  @classmethod
2601 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2602 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2603 3f78eef2 Iustin Pop

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

2607 10c2650b Iustin Pop
    @type dev_path: str
2608 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2609 10c2650b Iustin Pop
    @rtype: str
2610 10c2650b Iustin Pop
    @return: the converted path name
2611 3f78eef2 Iustin Pop

2612 3f78eef2 Iustin Pop
    """
2613 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2614 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2615 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2616 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2617 3f78eef2 Iustin Pop
    return fpath
2618 3f78eef2 Iustin Pop
2619 3f78eef2 Iustin Pop
  @classmethod
2620 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2621 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2622 3f78eef2 Iustin Pop

2623 10c2650b Iustin Pop
    @type dev_path: str
2624 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2625 10c2650b Iustin Pop
    @type owner: str
2626 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2627 10c2650b Iustin Pop
    @type on_primary: bool
2628 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2629 10c2650b Iustin Pop
        node nor not
2630 10c2650b Iustin Pop
    @type iv_name: str
2631 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2632 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2633 10c2650b Iustin Pop

2634 10c2650b Iustin Pop
    @rtype: None
2635 10c2650b Iustin Pop

2636 3f78eef2 Iustin Pop
    """
2637 cf5a8306 Iustin Pop
    if dev_path is None:
2638 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2639 cf5a8306 Iustin Pop
      return
2640 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2641 3f78eef2 Iustin Pop
    if on_primary:
2642 3f78eef2 Iustin Pop
      state = "primary"
2643 3f78eef2 Iustin Pop
    else:
2644 3f78eef2 Iustin Pop
      state = "secondary"
2645 3f78eef2 Iustin Pop
    if iv_name is None:
2646 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2647 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2648 3f78eef2 Iustin Pop
    try:
2649 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2650 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2651 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2652 3f78eef2 Iustin Pop
2653 3f78eef2 Iustin Pop
  @classmethod
2654 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2655 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2656 3f78eef2 Iustin Pop

2657 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2658 10c2650b Iustin Pop
    path name and logging.
2659 10c2650b Iustin Pop

2660 10c2650b Iustin Pop
    @type dev_path: str
2661 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2662 10c2650b Iustin Pop

2663 10c2650b Iustin Pop
    @rtype: None
2664 10c2650b Iustin Pop

2665 3f78eef2 Iustin Pop
    """
2666 cf5a8306 Iustin Pop
    if dev_path is None:
2667 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2668 cf5a8306 Iustin Pop
      return
2669 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2670 3f78eef2 Iustin Pop
    try:
2671 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2672 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2673 29921401 Iustin Pop
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)