Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 2503680f

History | View | Annotate | Download (81.2 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Functions used by the node daemon"""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
25 a8083063 Iustin Pop
import os
26 a8083063 Iustin Pop
import os.path
27 a8083063 Iustin Pop
import shutil
28 a8083063 Iustin Pop
import time
29 a8083063 Iustin Pop
import stat
30 a8083063 Iustin Pop
import errno
31 a8083063 Iustin Pop
import re
32 a8083063 Iustin Pop
import subprocess
33 b544cfe0 Iustin Pop
import random
34 18682bca Iustin Pop
import logging
35 3b9e6a30 Iustin Pop
import tempfile
36 12bce260 Michael Hanselmann
import zlib
37 12bce260 Michael Hanselmann
import base64
38 a8083063 Iustin Pop
39 a8083063 Iustin Pop
from ganeti import errors
40 a8083063 Iustin Pop
from ganeti import utils
41 a8083063 Iustin Pop
from ganeti import ssh
42 a8083063 Iustin Pop
from ganeti import hypervisor
43 a8083063 Iustin Pop
from ganeti import constants
44 a8083063 Iustin Pop
from ganeti import bdev
45 a8083063 Iustin Pop
from ganeti import objects
46 880478f8 Iustin Pop
from ganeti import ssconf
47 a8083063 Iustin Pop
48 a8083063 Iustin Pop
49 c657dcc9 Michael Hanselmann
def _GetConfig():
50 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
51 10c2650b Iustin Pop

52 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
53 93384844 Iustin Pop
  @return: a SimpleStore instance
54 10c2650b Iustin Pop

55 10c2650b Iustin Pop
  """
56 93384844 Iustin Pop
  return ssconf.SimpleStore()
57 c657dcc9 Michael Hanselmann
58 c657dcc9 Michael Hanselmann
59 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
60 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
61 10c2650b Iustin Pop

62 10c2650b Iustin Pop
  @type cluster_name: str
63 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
64 10c2650b Iustin Pop
      by the SshRunner constructor
65 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
66 10c2650b Iustin Pop
  @return: an SshRunner instance
67 10c2650b Iustin Pop

68 10c2650b Iustin Pop
  """
69 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
70 c92b310a Michael Hanselmann
71 c92b310a Michael Hanselmann
72 12bce260 Michael Hanselmann
def _Decompress(data):
73 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
74 12bce260 Michael Hanselmann

75 12bce260 Michael Hanselmann
  @type data: list or tuple
76 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
77 12bce260 Michael Hanselmann
  @rtype: str
78 12bce260 Michael Hanselmann
  @return: Decompressed data
79 12bce260 Michael Hanselmann

80 12bce260 Michael Hanselmann
  """
81 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
82 12bce260 Michael Hanselmann
  assert len(data) == 2
83 12bce260 Michael Hanselmann
  (encoding, content) = data
84 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
85 12bce260 Michael Hanselmann
    return content
86 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
87 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
88 12bce260 Michael Hanselmann
  else:
89 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
90 12bce260 Michael Hanselmann
91 12bce260 Michael Hanselmann
92 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
93 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
94 76ab5558 Michael Hanselmann

95 10c2650b Iustin Pop
  @type path: str
96 10c2650b Iustin Pop
  @param path: the directory to clean
97 76ab5558 Michael Hanselmann
  @type exclude: list
98 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
99 10c2650b Iustin Pop
      to the empty list
100 76ab5558 Michael Hanselmann

101 76ab5558 Michael Hanselmann
  """
102 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
103 3956cee1 Michael Hanselmann
    return
104 3bc6be5c Iustin Pop
  if exclude is None:
105 3bc6be5c Iustin Pop
    exclude = []
106 3bc6be5c Iustin Pop
  else:
107 3bc6be5c Iustin Pop
    # Normalize excluded paths
108 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
109 76ab5558 Michael Hanselmann
110 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
111 76ab5558 Michael Hanselmann
    full_name = os.path.normpath(os.path.join(path, rel_name))
112 76ab5558 Michael Hanselmann
    if full_name in exclude:
113 76ab5558 Michael Hanselmann
      continue
114 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
115 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
116 3956cee1 Michael Hanselmann
117 3956cee1 Michael Hanselmann
118 1bc59f76 Michael Hanselmann
def JobQueuePurge():
119 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
120 10c2650b Iustin Pop

121 10c2650b Iustin Pop
  @rtype: None
122 24fc781f Michael Hanselmann

123 24fc781f Michael Hanselmann
  """
124 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
125 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
126 24fc781f Michael Hanselmann
127 24fc781f Michael Hanselmann
128 bd1e4562 Iustin Pop
def GetMasterInfo():
129 bd1e4562 Iustin Pop
  """Returns master information.
130 bd1e4562 Iustin Pop

131 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
132 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
133 bd1e4562 Iustin Pop

134 bd1e4562 Iustin Pop
  @rtype: tuple
135 10c2650b Iustin Pop
  @return: (master_netdev, master_ip, master_name) if we have a good
136 10c2650b Iustin Pop
      configuration, otherwise (None, None, None)
137 b1b6ea87 Iustin Pop

138 b1b6ea87 Iustin Pop
  """
139 b1b6ea87 Iustin Pop
  try:
140 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
141 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
142 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
143 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
144 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
145 b1b6ea87 Iustin Pop
    logging.exception("Cluster configuration incomplete")
146 0a70a72a Iustin Pop
    return (None, None, None)
147 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
148 b1b6ea87 Iustin Pop
149 b1b6ea87 Iustin Pop
150 2503680f Guido Trotter
def StartMaster(start_daemons, no_voting):
151 a8083063 Iustin Pop
  """Activate local node as master node.
152 a8083063 Iustin Pop

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

157 10c2650b Iustin Pop
  @type start_daemons: boolean
158 10c2650b Iustin Pop
  @param start_daemons: whther to also start the master
159 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
160 2503680f Guido Trotter
  @type no_voting: boolean
161 2503680f Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
162 2503680f Guido Trotter
      (if start_daemons is True), but still non-interactively
163 10c2650b Iustin Pop
  @rtype: None
164 a8083063 Iustin Pop

165 a8083063 Iustin Pop
  """
166 b1b6ea87 Iustin Pop
  ok = True
167 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
168 b1b6ea87 Iustin Pop
  if not master_netdev:
169 a8083063 Iustin Pop
    return False
170 a8083063 Iustin Pop
171 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
172 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
173 b1b6ea87 Iustin Pop
      # we already have the ip:
174 b1b6ea87 Iustin Pop
      logging.debug("Already started")
175 b1b6ea87 Iustin Pop
    else:
176 b1b6ea87 Iustin Pop
      logging.error("Someone else has the master ip, not activating")
177 b1b6ea87 Iustin Pop
      ok = False
178 b1b6ea87 Iustin Pop
  else:
179 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
180 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
181 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
182 b1b6ea87 Iustin Pop
    if result.failed:
183 b1b6ea87 Iustin Pop
      logging.error("Can't activate master IP: %s", result.output)
184 b1b6ea87 Iustin Pop
      ok = False
185 b1b6ea87 Iustin Pop
186 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
187 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
188 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
189 b1b6ea87 Iustin Pop
190 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
191 b1b6ea87 Iustin Pop
  if start_daemons:
192 2503680f Guido Trotter
    daemons_params = {
193 2503680f Guido Trotter
        'ganeti-masterd': [],
194 2503680f Guido Trotter
        'ganeti-rapi': [],
195 2503680f Guido Trotter
        }
196 2503680f Guido Trotter
    if no_voting:
197 2503680f Guido Trotter
      daemons_params['ganeti-masterd'].append('--no-voting')
198 2503680f Guido Trotter
      daemons_params['ganeti-masterd'].append('--yes-do-it')
199 2503680f Guido Trotter
    for daemon in daemons_params:
200 2503680f Guido Trotter
      cmd = [daemon]
201 2503680f Guido Trotter
      cmd.extend(daemons_params[daemon])
202 2503680f Guido Trotter
      result = utils.RunCmd(cmd)
203 b1b6ea87 Iustin Pop
      if result.failed:
204 b1b6ea87 Iustin Pop
        logging.error("Can't start daemon %s: %s", daemon, result.output)
205 b1b6ea87 Iustin Pop
        ok = False
206 b1b6ea87 Iustin Pop
  return ok
207 a8083063 Iustin Pop
208 a8083063 Iustin Pop
209 1c65840b Iustin Pop
def StopMaster(stop_daemons):
210 a8083063 Iustin Pop
  """Deactivate this node as master.
211 a8083063 Iustin Pop

212 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
213 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
214 10c2650b Iustin Pop
  stop_daemons parameter.
215 10c2650b Iustin Pop

216 10c2650b Iustin Pop
  @type stop_daemons: boolean
217 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
218 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
219 10c2650b Iustin Pop
  @rtype: None
220 a8083063 Iustin Pop

221 a8083063 Iustin Pop
  """
222 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
223 b1b6ea87 Iustin Pop
  if not master_netdev:
224 b1b6ea87 Iustin Pop
    return False
225 a8083063 Iustin Pop
226 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
227 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
228 a8083063 Iustin Pop
  if result.failed:
229 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
230 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
231 b1b6ea87 Iustin Pop
232 b1b6ea87 Iustin Pop
  if stop_daemons:
233 b1b6ea87 Iustin Pop
    # stop/kill the rapi and the master daemon
234 b1b6ea87 Iustin Pop
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
235 b1b6ea87 Iustin Pop
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
236 a8083063 Iustin Pop
237 a8083063 Iustin Pop
  return True
238 a8083063 Iustin Pop
239 a8083063 Iustin Pop
240 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
241 7900ed01 Iustin Pop
  """Joins this node to the cluster.
242 a8083063 Iustin Pop

243 7900ed01 Iustin Pop
  This does the following:
244 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
245 7900ed01 Iustin Pop
      - adds the ssh private key to the user
246 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
247 a8083063 Iustin Pop

248 10c2650b Iustin Pop
  @type dsa: str
249 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
250 10c2650b Iustin Pop
  @type dsapub: str
251 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
252 10c2650b Iustin Pop
  @type rsa: str
253 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
254 10c2650b Iustin Pop
  @type rsapub: str
255 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
256 10c2650b Iustin Pop
  @type sshkey: str
257 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
258 10c2650b Iustin Pop
  @type sshpub: str
259 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
260 10c2650b Iustin Pop
  @rtype: boolean
261 10c2650b Iustin Pop
  @return: the success of the operation
262 10c2650b Iustin Pop

263 7900ed01 Iustin Pop
  """
264 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
265 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
266 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
267 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
268 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
269 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
270 a8083063 Iustin Pop
271 70d9e3d8 Iustin Pop
  try:
272 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
273 70d9e3d8 Iustin Pop
                                                    mkdir=True)
274 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
275 a1b805fb Iustin Pop
    msg = "Error while processing user ssh files"
276 a1b805fb Iustin Pop
    logging.exception(msg)
277 a1b805fb Iustin Pop
    return (False, "%s: %s" % (msg, err))
278 a8083063 Iustin Pop
279 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
280 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
281 a8083063 Iustin Pop
282 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
283 a8083063 Iustin Pop
284 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
285 a8083063 Iustin Pop
286 a1b805fb Iustin Pop
  return (True, "Node added successfully")
287 a8083063 Iustin Pop
288 a8083063 Iustin Pop
289 a8083063 Iustin Pop
def LeaveCluster():
290 10c2650b Iustin Pop
  """Cleans up and remove the current node.
291 10c2650b Iustin Pop

292 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
293 10c2650b Iustin Pop
  from the cluster.
294 10c2650b Iustin Pop

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

299 a8083063 Iustin Pop
  """
300 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
301 1bc59f76 Michael Hanselmann
  JobQueuePurge()
302 f78346f5 Michael Hanselmann
303 70d9e3d8 Iustin Pop
  try:
304 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
305 18682bca Iustin Pop
  except errors.OpExecError:
306 18682bca Iustin Pop
    logging.exception("Error while processing ssh files")
307 7900ed01 Iustin Pop
    return
308 7900ed01 Iustin Pop
309 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
310 a8083063 Iustin Pop
  try:
311 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
312 a8083063 Iustin Pop
  finally:
313 a8083063 Iustin Pop
    f.close()
314 a8083063 Iustin Pop
315 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
316 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
317 a8083063 Iustin Pop
318 6d8b6238 Guido Trotter
  # Return a reassuring string to the caller, and quit
319 6d8b6238 Guido Trotter
  raise errors.QuitGanetiException(False, 'Shutdown scheduled')
320 6d8b6238 Guido Trotter
321 a8083063 Iustin Pop
322 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
323 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
324 a8083063 Iustin Pop

325 e69d05fd Iustin Pop
  @type vgname: C{string}
326 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
327 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
328 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
329 e69d05fd Iustin Pop
      memory information
330 e69d05fd Iustin Pop
  @rtype: C{dict}
331 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
332 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
333 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
334 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
335 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
336 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
337 a8083063 Iustin Pop

338 098c0958 Michael Hanselmann
  """
339 a8083063 Iustin Pop
  outputarray = {}
340 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
341 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
342 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
343 a8083063 Iustin Pop
344 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
345 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
346 a8083063 Iustin Pop
  if hyp_info is not None:
347 a8083063 Iustin Pop
    outputarray.update(hyp_info)
348 a8083063 Iustin Pop
349 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
350 3ef10550 Michael Hanselmann
  try:
351 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
352 3ef10550 Michael Hanselmann
  finally:
353 3ef10550 Michael Hanselmann
    f.close()
354 3ef10550 Michael Hanselmann
355 a8083063 Iustin Pop
  return outputarray
356 a8083063 Iustin Pop
357 a8083063 Iustin Pop
358 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
359 a8083063 Iustin Pop
  """Verify the status of the local node.
360 a8083063 Iustin Pop

361 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
362 e69d05fd Iustin Pop
  local node.
363 e69d05fd Iustin Pop

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

367 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
368 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
369 e69d05fd Iustin Pop
  report).
370 a8083063 Iustin Pop

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

375 e69d05fd Iustin Pop
  @type what: C{dict}
376 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
377 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
378 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
379 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
380 e69d05fd Iustin Pop
        connectivity with
381 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
382 10c2650b Iustin Pop
  @rtype: dict
383 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
384 10c2650b Iustin Pop
      values representing the result of the checks
385 a8083063 Iustin Pop

386 a8083063 Iustin Pop
  """
387 a8083063 Iustin Pop
  result = {}
388 a8083063 Iustin Pop
389 25361b9a Iustin Pop
  if constants.NV_HYPERVISOR in what:
390 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
391 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
392 25361b9a Iustin Pop
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
393 25361b9a Iustin Pop
394 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
395 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
396 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
397 25361b9a Iustin Pop
398 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
399 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
400 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
401 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
402 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
403 a8083063 Iustin Pop
      if not success:
404 25361b9a Iustin Pop
        tmp[node] = message
405 25361b9a Iustin Pop
406 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
407 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
408 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
409 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
410 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
411 9d4bfc96 Iustin Pop
      if name == my_name:
412 9d4bfc96 Iustin Pop
        my_pip = pip
413 9d4bfc96 Iustin Pop
        my_sip = sip
414 9d4bfc96 Iustin Pop
        break
415 9d4bfc96 Iustin Pop
    if not my_pip:
416 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
417 25361b9a Iustin Pop
                      " in the node list")
418 9d4bfc96 Iustin Pop
    else:
419 c657dcc9 Michael Hanselmann
      port = utils.GetNodeDaemonPort()
420 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
421 9d4bfc96 Iustin Pop
        fail = []
422 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
423 9d4bfc96 Iustin Pop
          fail.append("primary")
424 9d4bfc96 Iustin Pop
        if sip != pip:
425 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
426 9d4bfc96 Iustin Pop
            fail.append("secondary")
427 9d4bfc96 Iustin Pop
        if fail:
428 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
429 25361b9a Iustin Pop
                       " and ".join(fail))
430 25361b9a Iustin Pop
431 25361b9a Iustin Pop
  if constants.NV_LVLIST in what:
432 25361b9a Iustin Pop
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
433 25361b9a Iustin Pop
434 25361b9a Iustin Pop
  if constants.NV_INSTANCELIST in what:
435 25361b9a Iustin Pop
    result[constants.NV_INSTANCELIST] = GetInstanceList(
436 25361b9a Iustin Pop
      what[constants.NV_INSTANCELIST])
437 25361b9a Iustin Pop
438 25361b9a Iustin Pop
  if constants.NV_VGLIST in what:
439 25361b9a Iustin Pop
    result[constants.NV_VGLIST] = ListVolumeGroups()
440 25361b9a Iustin Pop
441 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
442 e9ce0a64 Iustin Pop
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
443 e9ce0a64 Iustin Pop
                                    constants.RELEASE_VERSION)
444 25361b9a Iustin Pop
445 25361b9a Iustin Pop
  if constants.NV_HVINFO in what:
446 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
447 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
448 9d4bfc96 Iustin Pop
449 6d2e83d5 Iustin Pop
  if constants.NV_DRBDLIST in what:
450 6d2e83d5 Iustin Pop
    try:
451 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
452 f6eaed12 Iustin Pop
    except errors.BlockDeviceError, err:
453 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
454 f6eaed12 Iustin Pop
      used_minors = str(err)
455 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
456 6d2e83d5 Iustin Pop
457 a8083063 Iustin Pop
  return result
458 a8083063 Iustin Pop
459 a8083063 Iustin Pop
460 a8083063 Iustin Pop
def GetVolumeList(vg_name):
461 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
462 a8083063 Iustin Pop

463 10c2650b Iustin Pop
  @type vg_name: str
464 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
465 10c2650b Iustin Pop
  @rtype: dict
466 10c2650b Iustin Pop
  @return:
467 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
468 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
469 10c2650b Iustin Pop

470 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
471 10c2650b Iustin Pop

472 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
473 10c2650b Iustin Pop
      details.
474 a8083063 Iustin Pop

475 a8083063 Iustin Pop
  """
476 cb2037a2 Iustin Pop
  lvs = {}
477 cb2037a2 Iustin Pop
  sep = '|'
478 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
479 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
480 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
481 a8083063 Iustin Pop
  if result.failed:
482 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
483 18682bca Iustin Pop
                  result.output)
484 b63ed789 Iustin Pop
    return result.output
485 cb2037a2 Iustin Pop
486 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
487 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
488 df4c2628 Iustin Pop
    line = line.strip()
489 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
490 df4c2628 Iustin Pop
    if not match:
491 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
492 df4c2628 Iustin Pop
      continue
493 df4c2628 Iustin Pop
    name, size, attr = match.groups()
494 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
495 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
496 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
497 cb2037a2 Iustin Pop
498 cb2037a2 Iustin Pop
  return lvs
499 a8083063 Iustin Pop
500 a8083063 Iustin Pop
501 a8083063 Iustin Pop
def ListVolumeGroups():
502 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
503 a8083063 Iustin Pop

504 10c2650b Iustin Pop
  @rtype: dict
505 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
506 10c2650b Iustin Pop
      size of the volume
507 a8083063 Iustin Pop

508 a8083063 Iustin Pop
  """
509 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
510 a8083063 Iustin Pop
511 a8083063 Iustin Pop
512 dcb93971 Michael Hanselmann
def NodeVolumes():
513 dcb93971 Michael Hanselmann
  """List all volumes on this node.
514 dcb93971 Michael Hanselmann

515 10c2650b Iustin Pop
  @rtype: list
516 10c2650b Iustin Pop
  @return:
517 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
518 10c2650b Iustin Pop
      - name: the logical volume name,
519 10c2650b Iustin Pop
      - size: the size of the logical volume
520 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
521 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
522 10c2650b Iustin Pop

523 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
524 10c2650b Iustin Pop
    error.
525 10c2650b Iustin Pop

526 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
527 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
528 10c2650b Iustin Pop
    multiple times.
529 10c2650b Iustin Pop

530 dcb93971 Michael Hanselmann
  """
531 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
532 dcb93971 Michael Hanselmann
                         "--separator=|",
533 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
534 dcb93971 Michael Hanselmann
  if result.failed:
535 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
536 18682bca Iustin Pop
                  result.output)
537 3f5bd234 Iustin Pop
    return []
538 dcb93971 Michael Hanselmann
539 dcb93971 Michael Hanselmann
  def parse_dev(dev):
540 dcb93971 Michael Hanselmann
    if '(' in dev:
541 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
542 dcb93971 Michael Hanselmann
    else:
543 dcb93971 Michael Hanselmann
      return dev
544 dcb93971 Michael Hanselmann
545 dcb93971 Michael Hanselmann
  def map_line(line):
546 dcb93971 Michael Hanselmann
    return {
547 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
548 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
549 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
550 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
551 dcb93971 Michael Hanselmann
    }
552 dcb93971 Michael Hanselmann
553 a17a7623 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
554 a17a7623 Iustin Pop
          if line.count('|') >= 3]
555 dcb93971 Michael Hanselmann
556 dcb93971 Michael Hanselmann
557 a8083063 Iustin Pop
def BridgesExist(bridges_list):
558 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
559 a8083063 Iustin Pop

560 b1206984 Iustin Pop
  @rtype: boolean
561 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
562 a8083063 Iustin Pop

563 a8083063 Iustin Pop
  """
564 a8083063 Iustin Pop
  for bridge in bridges_list:
565 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
566 a8083063 Iustin Pop
      return False
567 a8083063 Iustin Pop
568 a8083063 Iustin Pop
  return True
569 a8083063 Iustin Pop
570 a8083063 Iustin Pop
571 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
572 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
573 a8083063 Iustin Pop

574 e69d05fd Iustin Pop
  @type hypervisor_list: list
575 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
576 e69d05fd Iustin Pop

577 e69d05fd Iustin Pop
  @rtype: list
578 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
579 10c2650b Iustin Pop
    - instance1.example.com
580 10c2650b Iustin Pop
    - instance2.example.com
581 a8083063 Iustin Pop

582 098c0958 Michael Hanselmann
  """
583 e69d05fd Iustin Pop
  results = []
584 e69d05fd Iustin Pop
  for hname in hypervisor_list:
585 e69d05fd Iustin Pop
    try:
586 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
587 e69d05fd Iustin Pop
      results.extend(names)
588 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
589 e69d05fd Iustin Pop
      logging.exception("Error enumerating instances for hypevisor %s", hname)
590 e69d05fd Iustin Pop
      raise
591 a8083063 Iustin Pop
592 e69d05fd Iustin Pop
  return results
593 a8083063 Iustin Pop
594 a8083063 Iustin Pop
595 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
596 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
597 a8083063 Iustin Pop

598 e69d05fd Iustin Pop
  @type instance: string
599 e69d05fd Iustin Pop
  @param instance: the instance name
600 e69d05fd Iustin Pop
  @type hname: string
601 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
602 a8083063 Iustin Pop

603 e69d05fd Iustin Pop
  @rtype: dict
604 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
605 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
606 e69d05fd Iustin Pop
      - state: xen state of instance (string)
607 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
608 a8083063 Iustin Pop

609 098c0958 Michael Hanselmann
  """
610 a8083063 Iustin Pop
  output = {}
611 a8083063 Iustin Pop
612 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
613 a8083063 Iustin Pop
  if iinfo is not None:
614 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
615 a8083063 Iustin Pop
    output['state'] = iinfo[4]
616 a8083063 Iustin Pop
    output['time'] = iinfo[5]
617 a8083063 Iustin Pop
618 a8083063 Iustin Pop
  return output
619 a8083063 Iustin Pop
620 a8083063 Iustin Pop
621 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
622 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
623 56e7640c Iustin Pop

624 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
625 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
626 56e7640c Iustin Pop

627 56e7640c Iustin Pop
  @rtype: tuple
628 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
629 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
630 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
631 56e7640c Iustin Pop

632 56e7640c Iustin Pop
  """
633 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
634 56e7640c Iustin Pop
  if instance.name not in hyper.ListInstances():
635 56e7640c Iustin Pop
    return (False, 'not running')
636 56e7640c Iustin Pop
637 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
638 56e7640c Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance.name, idx)
639 56e7640c Iustin Pop
    if not os.path.islink(link_name):
640 56e7640c Iustin Pop
      return (False, 'not restarted since ganeti 1.2.5')
641 56e7640c Iustin Pop
642 56e7640c Iustin Pop
  return (True, '')
643 56e7640c Iustin Pop
644 56e7640c Iustin Pop
645 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
646 a8083063 Iustin Pop
  """Gather data about all instances.
647 a8083063 Iustin Pop

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

652 e69d05fd Iustin Pop
  @type hypervisor_list: list
653 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
654 e69d05fd Iustin Pop

655 955db481 Guido Trotter
  @rtype: dict
656 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
657 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
658 e69d05fd Iustin Pop
      - state: xen state of instance (string)
659 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
660 10c2650b Iustin Pop
      - vcpus: the number of vcpus
661 a8083063 Iustin Pop

662 098c0958 Michael Hanselmann
  """
663 a8083063 Iustin Pop
  output = {}
664 a8083063 Iustin Pop
665 e69d05fd Iustin Pop
  for hname in hypervisor_list:
666 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
667 e69d05fd Iustin Pop
    if iinfo:
668 e69d05fd Iustin Pop
      for name, inst_id, memory, vcpus, state, times in iinfo:
669 f23b5ae8 Iustin Pop
        value = {
670 e69d05fd Iustin Pop
          'memory': memory,
671 e69d05fd Iustin Pop
          'vcpus': vcpus,
672 e69d05fd Iustin Pop
          'state': state,
673 e69d05fd Iustin Pop
          'time': times,
674 e69d05fd Iustin Pop
          }
675 b33b6f55 Iustin Pop
        if name in output:
676 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
677 b33b6f55 Iustin Pop
          # and not state and time which can change between the
678 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
679 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
680 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
681 b33b6f55 Iustin Pop
              raise errors.HypervisorError("Instance %s is running twice"
682 b33b6f55 Iustin Pop
                                           " with different parameters" % name)
683 f23b5ae8 Iustin Pop
        output[name] = value
684 a8083063 Iustin Pop
685 a8083063 Iustin Pop
  return output
686 a8083063 Iustin Pop
687 a8083063 Iustin Pop
688 1268d6fd Iustin Pop
def InstanceOsAdd(instance):
689 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
690 a8083063 Iustin Pop

691 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
692 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
693 10c2650b Iustin Pop
  @rtype: boolean
694 10c2650b Iustin Pop
  @return: the success of the operation
695 a8083063 Iustin Pop

696 a8083063 Iustin Pop
  """
697 1268d6fd Iustin Pop
  try:
698 1268d6fd Iustin Pop
    inst_os = OSFromDisk(instance.os)
699 1268d6fd Iustin Pop
  except errors.InvalidOS, err:
700 1268d6fd Iustin Pop
    os_name, os_dir, os_err = err.args
701 1268d6fd Iustin Pop
    if os_dir is None:
702 1268d6fd Iustin Pop
      return (False, "Can't find OS '%s': %s" % (os_name, os_err))
703 1268d6fd Iustin Pop
    else:
704 1268d6fd Iustin Pop
      return (False, "Error parsing OS '%s' in directory %s: %s" %
705 1268d6fd Iustin Pop
              (os_name, os_dir, os_err))
706 a8083063 Iustin Pop
707 58f6e5ca Guido Trotter
  create_env = OSEnvironment(instance)
708 a8083063 Iustin Pop
709 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
710 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
711 decd5f45 Iustin Pop
712 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
713 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
714 decd5f45 Iustin Pop
  if result.failed:
715 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
716 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
717 18682bca Iustin Pop
                  result.output)
718 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
719 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
720 20e01edd Iustin Pop
    return (False, "OS create script failed (%s), last lines in the"
721 20e01edd Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
722 decd5f45 Iustin Pop
723 20e01edd Iustin Pop
  return (True, "Successfully installed")
724 decd5f45 Iustin Pop
725 decd5f45 Iustin Pop
726 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
727 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
728 decd5f45 Iustin Pop

729 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
730 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
731 d15a9ad3 Guido Trotter
  @type old_name: string
732 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
733 10c2650b Iustin Pop
  @rtype: boolean
734 10c2650b Iustin Pop
  @return: the success of the operation
735 decd5f45 Iustin Pop

736 decd5f45 Iustin Pop
  """
737 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
738 decd5f45 Iustin Pop
739 ff38b6c0 Guido Trotter
  rename_env = OSEnvironment(instance)
740 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
741 decd5f45 Iustin Pop
742 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
743 decd5f45 Iustin Pop
                                           old_name,
744 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
745 a8083063 Iustin Pop
746 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
747 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
748 a8083063 Iustin Pop
749 a8083063 Iustin Pop
  if result.failed:
750 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
751 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
752 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
753 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
754 96841384 Iustin Pop
    return (False, "OS rename script failed (%s), last lines in the"
755 96841384 Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
756 a8083063 Iustin Pop
757 96841384 Iustin Pop
  return (True, "Rename successful")
758 a8083063 Iustin Pop
759 a8083063 Iustin Pop
760 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
761 a8083063 Iustin Pop
  """Get informations about the volume group.
762 a8083063 Iustin Pop

763 10c2650b Iustin Pop
  @type vg_name: str
764 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
765 10c2650b Iustin Pop
  @rtype: dict
766 10c2650b Iustin Pop
  @return:
767 10c2650b Iustin Pop
    A dictionary with the following keys:
768 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
769 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
770 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
771 a8083063 Iustin Pop

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

775 a8083063 Iustin Pop
  """
776 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
777 f4d377e7 Iustin Pop
778 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
779 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
780 a8083063 Iustin Pop
781 a8083063 Iustin Pop
  if retval.failed:
782 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
783 f4d377e7 Iustin Pop
    return retdic
784 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
785 f4d377e7 Iustin Pop
  if len(valarr) == 3:
786 f4d377e7 Iustin Pop
    try:
787 f4d377e7 Iustin Pop
      retdic = {
788 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
789 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
790 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
791 f4d377e7 Iustin Pop
        }
792 f4d377e7 Iustin Pop
    except ValueError, err:
793 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
794 f4d377e7 Iustin Pop
  else:
795 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
796 18682bca Iustin Pop
                  " three): %s", str(valarr))
797 a8083063 Iustin Pop
  return retdic
798 a8083063 Iustin Pop
799 a8083063 Iustin Pop
800 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
801 5282084b Iustin Pop
  return os.path.join(constants.DISK_LINKS_DIR,
802 5282084b Iustin Pop
                      "%s:%d" % (instance_name, idx))
803 5282084b Iustin Pop
804 5282084b Iustin Pop
805 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
806 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
807 9332fd8a Iustin Pop

808 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
809 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
810 9332fd8a Iustin Pop

811 9332fd8a Iustin Pop

812 5282084b Iustin Pop
  @param instance_name: the name of the target instance
813 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
814 5282084b Iustin Pop
  @param idx: the disk index
815 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
816 9332fd8a Iustin Pop

817 9332fd8a Iustin Pop
  """
818 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
819 9332fd8a Iustin Pop
  try:
820 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
821 5282084b Iustin Pop
  except OSError, err:
822 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
823 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
824 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
825 9332fd8a Iustin Pop
        os.remove(link_name)
826 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
827 9332fd8a Iustin Pop
    else:
828 9332fd8a Iustin Pop
      raise
829 9332fd8a Iustin Pop
830 9332fd8a Iustin Pop
  return link_name
831 9332fd8a Iustin Pop
832 9332fd8a Iustin Pop
833 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
834 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
835 3c9c571d Iustin Pop

836 3c9c571d Iustin Pop
  """
837 5282084b Iustin Pop
  for idx, disk in enumerate(disks):
838 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
839 5282084b Iustin Pop
    if os.path.islink(link_name):
840 3c9c571d Iustin Pop
      try:
841 03dfa658 Iustin Pop
        os.remove(link_name)
842 03dfa658 Iustin Pop
      except OSError:
843 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
844 3c9c571d Iustin Pop
845 3c9c571d Iustin Pop
846 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
847 a8083063 Iustin Pop
  """Set up an instance's block device(s).
848 a8083063 Iustin Pop

849 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
850 a8083063 Iustin Pop
  devices must be already assembled.
851 a8083063 Iustin Pop

852 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
853 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
854 069cfbf1 Iustin Pop
  @rtype: list
855 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
856 10c2650b Iustin Pop

857 a8083063 Iustin Pop
  """
858 a8083063 Iustin Pop
  block_devices = []
859 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
860 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
861 a8083063 Iustin Pop
    if device is None:
862 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
863 a8083063 Iustin Pop
                                    str(disk))
864 a8083063 Iustin Pop
    device.Open()
865 9332fd8a Iustin Pop
    try:
866 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
867 9332fd8a Iustin Pop
    except OSError, e:
868 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
869 9332fd8a Iustin Pop
                                    e.strerror)
870 9332fd8a Iustin Pop
871 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
872 9332fd8a Iustin Pop
873 a8083063 Iustin Pop
  return block_devices
874 a8083063 Iustin Pop
875 a8083063 Iustin Pop
876 07813a9e Iustin Pop
def StartInstance(instance):
877 a8083063 Iustin Pop
  """Start an instance.
878 a8083063 Iustin Pop

879 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
880 e69d05fd Iustin Pop
  @param instance: the instance object
881 e69d05fd Iustin Pop
  @rtype: boolean
882 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
883 a8083063 Iustin Pop

884 098c0958 Michael Hanselmann
  """
885 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
886 a8083063 Iustin Pop
887 a8083063 Iustin Pop
  if instance.name in running_instances:
888 dd279568 Iustin Pop
    return (True, "Already running")
889 a8083063 Iustin Pop
890 a8083063 Iustin Pop
  try:
891 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
892 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
893 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
894 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
895 ec596c24 Iustin Pop
    logging.exception("Failed to start instance")
896 dd279568 Iustin Pop
    return (False, "Block device error: %s" % str(err))
897 a8083063 Iustin Pop
  except errors.HypervisorError, err:
898 18682bca Iustin Pop
    logging.exception("Failed to start instance")
899 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
900 dd279568 Iustin Pop
    return (False, "Hypervisor error: %s" % str(err))
901 a8083063 Iustin Pop
902 dd279568 Iustin Pop
  return (True, "Instance started successfully")
903 a8083063 Iustin Pop
904 a8083063 Iustin Pop
905 1fae010f Iustin Pop
def InstanceShutdown(instance):
906 a8083063 Iustin Pop
  """Shut an instance down.
907 a8083063 Iustin Pop

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

910 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
911 e69d05fd Iustin Pop
  @param instance: the instance object
912 e69d05fd Iustin Pop
  @rtype: boolean
913 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
914 a8083063 Iustin Pop

915 098c0958 Michael Hanselmann
  """
916 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
917 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
918 a8083063 Iustin Pop
919 a8083063 Iustin Pop
  if instance.name not in running_instances:
920 1fae010f Iustin Pop
    return (True, "Instance already stopped")
921 a8083063 Iustin Pop
922 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
923 a8083063 Iustin Pop
  try:
924 a8083063 Iustin Pop
    hyper.StopInstance(instance)
925 a8083063 Iustin Pop
  except errors.HypervisorError, err:
926 1fae010f Iustin Pop
    msg = "Failed to stop instance %s: %s" % (instance.name, err)
927 1fae010f Iustin Pop
    logging.error(msg)
928 1fae010f Iustin Pop
    return (False, msg)
929 a8083063 Iustin Pop
930 a8083063 Iustin Pop
  # test every 10secs for 2min
931 a8083063 Iustin Pop
932 a8083063 Iustin Pop
  time.sleep(1)
933 a8083063 Iustin Pop
  for dummy in range(11):
934 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
935 a8083063 Iustin Pop
      break
936 a8083063 Iustin Pop
    time.sleep(10)
937 a8083063 Iustin Pop
  else:
938 a8083063 Iustin Pop
    # the shutdown did not succeed
939 ca77edbc Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, using destroy",
940 ca77edbc Guido Trotter
                  instance.name)
941 a8083063 Iustin Pop
942 a8083063 Iustin Pop
    try:
943 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
944 a8083063 Iustin Pop
    except errors.HypervisorError, err:
945 1fae010f Iustin Pop
      msg = "Failed to force stop instance %s: %s" % (instance.name, err)
946 1fae010f Iustin Pop
      logging.error(msg)
947 1fae010f Iustin Pop
      return (False, msg)
948 a8083063 Iustin Pop
949 a8083063 Iustin Pop
    time.sleep(1)
950 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
951 1fae010f Iustin Pop
      msg = ("Could not shutdown instance %s even by destroy" %
952 1fae010f Iustin Pop
             instance.name)
953 1fae010f Iustin Pop
      logging.error(msg)
954 1fae010f Iustin Pop
      return (False, msg)
955 a8083063 Iustin Pop
956 5282084b Iustin Pop
  _RemoveBlockDevLinks(instance.name, instance.disks)
957 3c9c571d Iustin Pop
958 1fae010f Iustin Pop
  return (True, "Instance has been shutdown successfully")
959 a8083063 Iustin Pop
960 a8083063 Iustin Pop
961 07813a9e Iustin Pop
def InstanceReboot(instance, reboot_type):
962 007a2f3e Alexander Schreiber
  """Reboot an instance.
963 007a2f3e Alexander Schreiber

964 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
965 10c2650b Iustin Pop
  @param instance: the instance object to reboot
966 10c2650b Iustin Pop
  @type reboot_type: str
967 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
968 10c2650b Iustin Pop
    constants:
969 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
970 10c2650b Iustin Pop
        instance OS, do not recreate the VM
971 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
972 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
973 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
974 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
975 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
976 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
977 10c2650b Iustin Pop
  @rtype: boolean
978 10c2650b Iustin Pop
  @return: the success of the operation
979 007a2f3e Alexander Schreiber

980 007a2f3e Alexander Schreiber
  """
981 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
982 007a2f3e Alexander Schreiber
983 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
984 489fcbe9 Iustin Pop
    msg = "Cannot reboot instance %s that is not running" % instance.name
985 489fcbe9 Iustin Pop
    logging.error(msg)
986 489fcbe9 Iustin Pop
    return (False, msg)
987 007a2f3e Alexander Schreiber
988 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
989 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
990 007a2f3e Alexander Schreiber
    try:
991 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
992 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
993 489fcbe9 Iustin Pop
      msg = "Failed to soft reboot instance %s: %s" % (instance.name, err)
994 489fcbe9 Iustin Pop
      logging.error(msg)
995 489fcbe9 Iustin Pop
      return (False, msg)
996 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
997 007a2f3e Alexander Schreiber
    try:
998 ae48ac32 Iustin Pop
      stop_result = InstanceShutdown(instance)
999 ae48ac32 Iustin Pop
      if not stop_result[0]:
1000 ae48ac32 Iustin Pop
        return stop_result
1001 07813a9e Iustin Pop
      return StartInstance(instance)
1002 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1003 489fcbe9 Iustin Pop
      msg = "Failed to hard reboot instance %s: %s" % (instance.name, err)
1004 489fcbe9 Iustin Pop
      logging.error(msg)
1005 489fcbe9 Iustin Pop
      return (False, msg)
1006 007a2f3e Alexander Schreiber
  else:
1007 489fcbe9 Iustin Pop
    return (False, "Invalid reboot_type received: %s" % (reboot_type,))
1008 007a2f3e Alexander Schreiber
1009 489fcbe9 Iustin Pop
  return (True, "Reboot successful")
1010 007a2f3e Alexander Schreiber
1011 007a2f3e Alexander Schreiber
1012 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1013 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1014 6906a9d8 Guido Trotter

1015 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1016 6906a9d8 Guido Trotter
  @param instance: the instance definition
1017 6906a9d8 Guido Trotter

1018 6906a9d8 Guido Trotter
  """
1019 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1020 cd42d0ad Guido Trotter
  try:
1021 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1022 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1023 cd42d0ad Guido Trotter
    msg = "Failed to fetch migration information"
1024 cd42d0ad Guido Trotter
    logging.exception(msg)
1025 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1026 cd42d0ad Guido Trotter
  return (True, info)
1027 6906a9d8 Guido Trotter
1028 6906a9d8 Guido Trotter
1029 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1030 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1031 6906a9d8 Guido Trotter

1032 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1033 6906a9d8 Guido Trotter
  @param instance: the instance definition
1034 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1035 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1036 6906a9d8 Guido Trotter
  @type target: string
1037 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1038 6906a9d8 Guido Trotter

1039 6906a9d8 Guido Trotter
  """
1040 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1041 cd42d0ad Guido Trotter
  try:
1042 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1043 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1044 cd42d0ad Guido Trotter
    msg = "Failed to accept instance"
1045 cd42d0ad Guido Trotter
    logging.exception(msg)
1046 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1047 6906a9d8 Guido Trotter
  return (True, "Accept successfull")
1048 6906a9d8 Guido Trotter
1049 6906a9d8 Guido Trotter
1050 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1051 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1052 6906a9d8 Guido Trotter

1053 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1054 6906a9d8 Guido Trotter
  @param instance: the instance definition
1055 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1056 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1057 6906a9d8 Guido Trotter
  @type success: boolean
1058 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1059 6906a9d8 Guido Trotter

1060 6906a9d8 Guido Trotter
  """
1061 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1062 cd42d0ad Guido Trotter
  try:
1063 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1064 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1065 cd42d0ad Guido Trotter
    msg = "Failed to finalize migration"
1066 cd42d0ad Guido Trotter
    logging.exception(msg)
1067 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1068 6906a9d8 Guido Trotter
  return (True, "Migration Finalized")
1069 6906a9d8 Guido Trotter
1070 6906a9d8 Guido Trotter
1071 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1072 2a10865c Iustin Pop
  """Migrates an instance to another node.
1073 2a10865c Iustin Pop

1074 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1075 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1076 9f0e6b37 Iustin Pop
  @type target: string
1077 9f0e6b37 Iustin Pop
  @param target: the target node name
1078 9f0e6b37 Iustin Pop
  @type live: boolean
1079 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1080 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1081 9f0e6b37 Iustin Pop
  @rtype: tuple
1082 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1083 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1084 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1085 9f0e6b37 Iustin Pop

1086 2a10865c Iustin Pop
  """
1087 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1088 2a10865c Iustin Pop
1089 2a10865c Iustin Pop
  try:
1090 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
1091 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1092 53c776b5 Iustin Pop
    msg = "Failed to migrate instance"
1093 53c776b5 Iustin Pop
    logging.exception(msg)
1094 53c776b5 Iustin Pop
    return (False, "%s: %s" % (msg, err))
1095 2a10865c Iustin Pop
  return (True, "Migration successfull")
1096 2a10865c Iustin Pop
1097 2a10865c Iustin Pop
1098 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1099 a8083063 Iustin Pop
  """Creates a block device for an instance.
1100 a8083063 Iustin Pop

1101 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1102 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1103 b1206984 Iustin Pop
  @type size: int
1104 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1105 b1206984 Iustin Pop
  @type owner: str
1106 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1107 b1206984 Iustin Pop
      used for device cache data
1108 b1206984 Iustin Pop
  @type on_primary: boolean
1109 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1110 b1206984 Iustin Pop
  @type info: string
1111 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1112 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1113 b1206984 Iustin Pop

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

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

1173 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1174 10c2650b Iustin Pop

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

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

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

1214 10c2650b Iustin Pop
  @note: this function is called recursively.
1215 a8083063 Iustin Pop

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

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

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

1266 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1267 a8083063 Iustin Pop

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

1272 a8083063 Iustin Pop
  """
1273 1063abd1 Iustin Pop
  status = True
1274 53c14ef1 Iustin Pop
  result = "no error information"
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 53c14ef1 Iustin Pop
    result = "Error while assembling disk: %s" % str(err)
1281 1063abd1 Iustin Pop
    status = False
1282 53c14ef1 Iustin Pop
  return (status, 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 c41eea6e Iustin Pop
  First, if the device is assembled (Attach() is successfull), 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 10c2650b Iustin Pop
  @rtype: boolean
1300 10c2650b Iustin Pop
  @return: the success of the operation
1301 10c2650b Iustin Pop

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

1328 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1329 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1330 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1331 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1332 10c2650b Iustin Pop
  @rtype: boolean
1333 10c2650b Iustin Pop
  @return: the success of the operation
1334 10c2650b Iustin Pop

1335 a8083063 Iustin Pop
  """
1336 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1337 153d9724 Iustin Pop
  if parent_bdev is None:
1338 18682bca Iustin Pop
    logging.error("Can't find parent device")
1339 a8083063 Iustin Pop
    return False
1340 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1341 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1342 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
1343 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
1344 a8083063 Iustin Pop
    return False
1345 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1346 a8083063 Iustin Pop
  return True
1347 a8083063 Iustin Pop
1348 a8083063 Iustin Pop
1349 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1350 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1351 a8083063 Iustin Pop

1352 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1353 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1354 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1355 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1356 10c2650b Iustin Pop
  @rtype: boolean
1357 10c2650b Iustin Pop
  @return: the success of the operation
1358 10c2650b Iustin Pop

1359 a8083063 Iustin Pop
  """
1360 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1361 153d9724 Iustin Pop
  if parent_bdev is None:
1362 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
1363 a8083063 Iustin Pop
    return False
1364 e739bd57 Iustin Pop
  devs = []
1365 e739bd57 Iustin Pop
  for disk in new_cdevs:
1366 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1367 e739bd57 Iustin Pop
    if rpath is None:
1368 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1369 e739bd57 Iustin Pop
      if bd is None:
1370 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
1371 18682bca Iustin Pop
                      disk)
1372 e739bd57 Iustin Pop
        return False
1373 e739bd57 Iustin Pop
      else:
1374 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1375 e739bd57 Iustin Pop
    else:
1376 e739bd57 Iustin Pop
      devs.append(rpath)
1377 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1378 a8083063 Iustin Pop
  return True
1379 a8083063 Iustin Pop
1380 a8083063 Iustin Pop
1381 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1382 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1383 a8083063 Iustin Pop

1384 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1385 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1386 10c2650b Iustin Pop
  @rtype: disk
1387 10c2650b Iustin Pop
  @return:
1388 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1389 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1390 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1391 10c2650b Iustin Pop
      found
1392 a8083063 Iustin Pop

1393 a8083063 Iustin Pop
  """
1394 a8083063 Iustin Pop
  stats = []
1395 a8083063 Iustin Pop
  for dsk in disks:
1396 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1397 a8083063 Iustin Pop
    if rbd is None:
1398 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
1399 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1400 a8083063 Iustin Pop
  return stats
1401 a8083063 Iustin Pop
1402 a8083063 Iustin Pop
1403 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1404 a8083063 Iustin Pop
  """Check if a device is activated.
1405 a8083063 Iustin Pop

1406 a8083063 Iustin Pop
  If so, return informations about the real device.
1407 a8083063 Iustin Pop

1408 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1409 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1410 a8083063 Iustin Pop

1411 10c2650b Iustin Pop
  @return: None if the device can't be found,
1412 10c2650b Iustin Pop
      otherwise the device instance
1413 a8083063 Iustin Pop

1414 a8083063 Iustin Pop
  """
1415 a8083063 Iustin Pop
  children = []
1416 a8083063 Iustin Pop
  if disk.children:
1417 a8083063 Iustin Pop
    for chdisk in disk.children:
1418 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1419 a8083063 Iustin Pop
1420 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1421 a8083063 Iustin Pop
1422 a8083063 Iustin Pop
1423 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1424 a8083063 Iustin Pop
  """Check if a device is activated.
1425 a8083063 Iustin Pop

1426 10c2650b Iustin Pop
  If it is, return informations about the real device.
1427 a8083063 Iustin Pop

1428 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1429 10c2650b Iustin Pop
  @param disk: the disk to find
1430 10c2650b Iustin Pop
  @rtype: None or tuple
1431 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1432 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1433 10c2650b Iustin Pop
      estimated_time, is_degraded)
1434 a8083063 Iustin Pop

1435 a8083063 Iustin Pop
  """
1436 23829f6f Iustin Pop
  try:
1437 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1438 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1439 23829f6f Iustin Pop
    return (False, str(err))
1440 a8083063 Iustin Pop
  if rbd is None:
1441 23829f6f Iustin Pop
    return (True, None)
1442 23829f6f Iustin Pop
  return (True, (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus())
1443 a8083063 Iustin Pop
1444 a8083063 Iustin Pop
1445 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1446 a8083063 Iustin Pop
  """Write a file to the filesystem.
1447 a8083063 Iustin Pop

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

1451 10c2650b Iustin Pop
  @type file_name: str
1452 10c2650b Iustin Pop
  @param file_name: the target file name
1453 10c2650b Iustin Pop
  @type data: str
1454 10c2650b Iustin Pop
  @param data: the new contents of the file
1455 10c2650b Iustin Pop
  @type mode: int
1456 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1457 10c2650b Iustin Pop
  @type uid: int
1458 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1459 10c2650b Iustin Pop
  @type gid: int
1460 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1461 10c2650b Iustin Pop
  @type atime: float
1462 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1463 10c2650b Iustin Pop
  @type mtime: float
1464 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1465 10c2650b Iustin Pop
  @rtype: boolean
1466 10c2650b Iustin Pop
  @return: the success of the operation; errors are logged
1467 10c2650b Iustin Pop
      in the node daemon log
1468 10c2650b Iustin Pop

1469 a8083063 Iustin Pop
  """
1470 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1471 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
1472 18682bca Iustin Pop
                  file_name)
1473 a8083063 Iustin Pop
    return False
1474 a8083063 Iustin Pop
1475 97628462 Iustin Pop
  allowed_files = [
1476 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1477 97628462 Iustin Pop
    constants.ETC_HOSTS,
1478 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1479 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1480 97628462 Iustin Pop
    ]
1481 afee8008 Michael Hanselmann
1482 553f1c1d Michael Hanselmann
  if file_name not in allowed_files:
1483 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
1484 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
1485 a8083063 Iustin Pop
    return False
1486 a8083063 Iustin Pop
1487 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1488 12bce260 Michael Hanselmann
1489 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1490 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1491 a8083063 Iustin Pop
  return True
1492 a8083063 Iustin Pop
1493 386b57af Iustin Pop
1494 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1495 89b14f05 Iustin Pop
  """Update all ssconf files.
1496 89b14f05 Iustin Pop

1497 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1498 89b14f05 Iustin Pop

1499 89b14f05 Iustin Pop
  """
1500 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1501 6ddc95ec Michael Hanselmann
1502 6ddc95ec Michael Hanselmann
1503 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1504 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1505 a8083063 Iustin Pop

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

1510 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1511 10c2650b Iustin Pop
  @param err: the exception to format
1512 a8083063 Iustin Pop

1513 a8083063 Iustin Pop
  """
1514 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1515 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1516 a8083063 Iustin Pop
  else:
1517 a8083063 Iustin Pop
    detail = str(err)
1518 a8083063 Iustin Pop
  return detail
1519 a8083063 Iustin Pop
1520 5d0fe286 Iustin Pop
1521 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1522 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1523 a8083063 Iustin Pop

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

1527 10c2650b Iustin Pop
  @type name: str
1528 10c2650b Iustin Pop
  @param name: the OS name we should look for
1529 10c2650b Iustin Pop
  @type os_dir: str
1530 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1531 10c2650b Iustin Pop
  @rtype: int or None
1532 10c2650b Iustin Pop
  @return:
1533 10c2650b Iustin Pop
      Either an integer denoting the version or None in the
1534 10c2650b Iustin Pop
      case when this is not a valid OS name.
1535 10c2650b Iustin Pop
  @raise errors.InvalidOS: if the OS cannot be found
1536 a8083063 Iustin Pop

1537 a8083063 Iustin Pop
  """
1538 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1539 a8083063 Iustin Pop
1540 a8083063 Iustin Pop
  try:
1541 a8083063 Iustin Pop
    st = os.stat(api_file)
1542 a8083063 Iustin Pop
  except EnvironmentError, err:
1543 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1544 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1545 a8083063 Iustin Pop
1546 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1547 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1548 3ecf6786 Iustin Pop
                           " a regular file")
1549 a8083063 Iustin Pop
1550 a8083063 Iustin Pop
  try:
1551 a8083063 Iustin Pop
    f = open(api_file)
1552 a8083063 Iustin Pop
    try:
1553 082a7f91 Guido Trotter
      api_versions = f.readlines()
1554 a8083063 Iustin Pop
    finally:
1555 a8083063 Iustin Pop
      f.close()
1556 a8083063 Iustin Pop
  except EnvironmentError, err:
1557 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1558 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1559 a8083063 Iustin Pop
1560 082a7f91 Guido Trotter
  api_versions = [version.strip() for version in api_versions]
1561 a8083063 Iustin Pop
  try:
1562 082a7f91 Guido Trotter
    api_versions = [int(version) for version in api_versions]
1563 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1564 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1565 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1566 a8083063 Iustin Pop
1567 082a7f91 Guido Trotter
  return api_versions
1568 a8083063 Iustin Pop
1569 386b57af Iustin Pop
1570 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1571 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1572 a8083063 Iustin Pop

1573 10c2650b Iustin Pop
  @type top_dirs: list
1574 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1575 10c2650b Iustin Pop
      search (if not given defaults to
1576 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1577 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1578 10c2650b Iustin Pop
  @return: an OS object for each name in all the given
1579 10c2650b Iustin Pop
      directories
1580 a8083063 Iustin Pop

1581 a8083063 Iustin Pop
  """
1582 7c3d51d4 Guido Trotter
  if top_dirs is None:
1583 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1584 a8083063 Iustin Pop
1585 a8083063 Iustin Pop
  result = []
1586 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1587 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1588 7c3d51d4 Guido Trotter
      try:
1589 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1590 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1591 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1592 7c3d51d4 Guido Trotter
        break
1593 7c3d51d4 Guido Trotter
      for name in f_names:
1594 7c3d51d4 Guido Trotter
        try:
1595 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1596 7c3d51d4 Guido Trotter
          result.append(os_inst)
1597 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1598 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1599 a8083063 Iustin Pop
1600 a8083063 Iustin Pop
  return result
1601 a8083063 Iustin Pop
1602 a8083063 Iustin Pop
1603 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1604 a8083063 Iustin Pop
  """Create an OS instance from disk.
1605 a8083063 Iustin Pop

1606 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1607 a8083063 Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
1608 10c2650b Iustin Pop
  L{errors.InvalidOS} exception, detailing why this is not a valid OS.
1609 a8083063 Iustin Pop

1610 8ee4dc80 Guido Trotter
  @type base_dir: string
1611 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1612 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1613 10c2650b Iustin Pop
  @rtype: L{objects.OS}
1614 10c2650b Iustin Pop
  @return: the OS instance if we find a valid one
1615 10c2650b Iustin Pop
  @raise errors.InvalidOS: if we don't find a valid OS
1616 7c3d51d4 Guido Trotter

1617 a8083063 Iustin Pop
  """
1618 56bcd3f4 Guido Trotter
  if base_dir is None:
1619 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1620 c34c0cfd Iustin Pop
    if os_dir is None:
1621 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1622 c34c0cfd Iustin Pop
  else:
1623 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1624 a8083063 Iustin Pop
1625 082a7f91 Guido Trotter
  api_versions = _OSOndiskVersion(name, os_dir)
1626 a8083063 Iustin Pop
1627 082a7f91 Guido Trotter
  if constants.OS_API_VERSION not in api_versions:
1628 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1629 305a7297 Guido Trotter
                           " (found %s want %s)"
1630 082a7f91 Guido Trotter
                           % (api_versions, constants.OS_API_VERSION))
1631 a8083063 Iustin Pop
1632 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1633 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1634 a8083063 Iustin Pop
1635 a8083063 Iustin Pop
  for script in os_scripts:
1636 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1637 a8083063 Iustin Pop
1638 a8083063 Iustin Pop
    try:
1639 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1640 a8083063 Iustin Pop
    except EnvironmentError, err:
1641 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1642 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1643 a8083063 Iustin Pop
1644 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1645 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1646 305a7297 Guido Trotter
                             script)
1647 a8083063 Iustin Pop
1648 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1649 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1650 305a7297 Guido Trotter
                             script)
1651 a8083063 Iustin Pop
1652 a8083063 Iustin Pop
1653 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1654 62dbbe7e Guido Trotter
                    create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1655 62dbbe7e Guido Trotter
                    export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1656 62dbbe7e Guido Trotter
                    import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1657 62dbbe7e Guido Trotter
                    rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1658 082a7f91 Guido Trotter
                    api_versions=api_versions)
1659 a8083063 Iustin Pop
1660 2266edb2 Guido Trotter
def OSEnvironment(instance, debug=0):
1661 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1662 2266edb2 Guido Trotter

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

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

1715 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1716 10c2650b Iustin Pop
  first ones to resize.
1717 594609c0 Iustin Pop

1718 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1719 10c2650b Iustin Pop
  @param disk: the disk to be grown
1720 10c2650b Iustin Pop
  @rtype: (status, result)
1721 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1722 10c2650b Iustin Pop
      (True/False), and the errors message if status
1723 10c2650b Iustin Pop
      is False
1724 594609c0 Iustin Pop

1725 594609c0 Iustin Pop
  """
1726 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1727 594609c0 Iustin Pop
  if r_dev is None:
1728 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1729 594609c0 Iustin Pop
1730 594609c0 Iustin Pop
  try:
1731 594609c0 Iustin Pop
    r_dev.Grow(amount)
1732 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1733 594609c0 Iustin Pop
    return False, str(err)
1734 594609c0 Iustin Pop
1735 594609c0 Iustin Pop
  return True, None
1736 594609c0 Iustin Pop
1737 594609c0 Iustin Pop
1738 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
1739 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1740 a8083063 Iustin Pop

1741 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1742 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1743 a8083063 Iustin Pop

1744 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1745 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1746 e9e9263d Guido Trotter
  @rtype: string
1747 e9e9263d Guido Trotter
  @return: snapshot disk path
1748 a8083063 Iustin Pop

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

1776 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1777 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1778 74c47259 Iustin Pop
  @type dest_node: str
1779 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1780 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1781 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1782 74c47259 Iustin Pop
  @type cluster_name: str
1783 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1784 74c47259 Iustin Pop
  @type idx: int
1785 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1786 74c47259 Iustin Pop
      used to export to the OS scripts environment
1787 10c2650b Iustin Pop
  @rtype: boolean
1788 74c47259 Iustin Pop
  @return: the success of the operation
1789 a8083063 Iustin Pop

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

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

1849 10c2650b Iustin Pop
  @rtype: boolean
1850 10c2650b Iustin Pop
  @return: the success of the operation
1851 a8083063 Iustin Pop

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

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

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

1915 a8083063 Iustin Pop
  """
1916 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1917 a8083063 Iustin Pop
1918 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1919 a8083063 Iustin Pop
  config.read(cff)
1920 a8083063 Iustin Pop
1921 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1922 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1923 a8083063 Iustin Pop
    return None
1924 a8083063 Iustin Pop
1925 a8083063 Iustin Pop
  return config
1926 a8083063 Iustin Pop
1927 a8083063 Iustin Pop
1928 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1929 a8083063 Iustin Pop
  """Import an os image into an instance.
1930 a8083063 Iustin Pop

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

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

1981 10c2650b Iustin Pop
  @rtype: list
1982 10c2650b Iustin Pop
  @return: list of the exports
1983 10c2650b Iustin Pop

1984 a8083063 Iustin Pop
  """
1985 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1986 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1987 a8083063 Iustin Pop
  else:
1988 a8083063 Iustin Pop
    return []
1989 a8083063 Iustin Pop
1990 a8083063 Iustin Pop
1991 a8083063 Iustin Pop
def RemoveExport(export):
1992 a8083063 Iustin Pop
  """Remove an existing export from the node.
1993 a8083063 Iustin Pop

1994 10c2650b Iustin Pop
  @type export: str
1995 10c2650b Iustin Pop
  @param export: the name of the export to remove
1996 10c2650b Iustin Pop
  @rtype: boolean
1997 10c2650b Iustin Pop
  @return: the success of the operation
1998 a8083063 Iustin Pop

1999 098c0958 Michael Hanselmann
  """
2000 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
2001 a8083063 Iustin Pop
2002 a8083063 Iustin Pop
  shutil.rmtree(target)
2003 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
2004 a8083063 Iustin Pop
  # error message if rmtree fails.
2005 a8083063 Iustin Pop
2006 a8083063 Iustin Pop
  return True
2007 a8083063 Iustin Pop
2008 a8083063 Iustin Pop
2009 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2010 f3e513ad Iustin Pop
  """Rename a list of block devices.
2011 f3e513ad Iustin Pop

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

2021 f3e513ad Iustin Pop
  """
2022 f3e513ad Iustin Pop
  result = True
2023 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2024 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2025 f3e513ad Iustin Pop
    if dev is None:
2026 f3e513ad Iustin Pop
      result = False
2027 f3e513ad Iustin Pop
      continue
2028 f3e513ad Iustin Pop
    try:
2029 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2030 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2031 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2032 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2033 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2034 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2035 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2036 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2037 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2038 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2039 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
2040 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2041 f3e513ad Iustin Pop
      result = False
2042 f3e513ad Iustin Pop
  return result
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 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
2064 18682bca Iustin Pop
                  " storage directory '%s'",
2065 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
2066 778b75bb Manuel Franceschini
    return None
2067 778b75bb Manuel Franceschini
  return file_storage_dir
2068 778b75bb Manuel Franceschini
2069 778b75bb Manuel Franceschini
2070 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2071 778b75bb Manuel Franceschini
  """Create file storage directory.
2072 778b75bb Manuel Franceschini

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

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

2080 778b75bb Manuel Franceschini
  """
2081 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2082 778b75bb Manuel Franceschini
  result = True,
2083 778b75bb Manuel Franceschini
  if not file_storage_dir:
2084 778b75bb Manuel Franceschini
    result = False,
2085 778b75bb Manuel Franceschini
  else:
2086 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2087 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2088 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2089 778b75bb Manuel Franceschini
        result = False,
2090 778b75bb Manuel Franceschini
    else:
2091 778b75bb Manuel Franceschini
      try:
2092 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
2093 778b75bb Manuel Franceschini
      except OSError, err:
2094 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
2095 18682bca Iustin Pop
                      file_storage_dir, err)
2096 778b75bb Manuel Franceschini
        result = False,
2097 778b75bb Manuel Franceschini
  return result
2098 778b75bb Manuel Franceschini
2099 778b75bb Manuel Franceschini
2100 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2101 778b75bb Manuel Franceschini
  """Remove file storage directory.
2102 778b75bb Manuel Franceschini

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

2105 10c2650b Iustin Pop
  @type file_storage_dir: str
2106 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2107 10c2650b Iustin Pop
  @rtype: tuple (success,)
2108 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2109 10c2650b Iustin Pop
      whether the operation was successfull
2110 778b75bb Manuel Franceschini

2111 778b75bb Manuel Franceschini
  """
2112 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2113 778b75bb Manuel Franceschini
  result = True,
2114 778b75bb Manuel Franceschini
  if not file_storage_dir:
2115 778b75bb Manuel Franceschini
    result = False,
2116 778b75bb Manuel Franceschini
  else:
2117 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2118 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2119 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2120 778b75bb Manuel Franceschini
        result = False,
2121 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
2122 778b75bb Manuel Franceschini
      try:
2123 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
2124 778b75bb Manuel Franceschini
      except OSError, err:
2125 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
2126 18682bca Iustin Pop
                          file_storage_dir)
2127 778b75bb Manuel Franceschini
        result = False,
2128 778b75bb Manuel Franceschini
  return result
2129 778b75bb Manuel Franceschini
2130 778b75bb Manuel Franceschini
2131 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2132 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2133 778b75bb Manuel Franceschini

2134 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2135 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2136 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2137 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2138 10c2650b Iustin Pop
  @rtype: tuple (success,)
2139 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2140 10c2650b Iustin Pop
      whether the operation was successful
2141 778b75bb Manuel Franceschini

2142 778b75bb Manuel Franceschini
  """
2143 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2144 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2145 778b75bb Manuel Franceschini
  result = True,
2146 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
2147 778b75bb Manuel Franceschini
    result = False,
2148 778b75bb Manuel Franceschini
  else:
2149 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
2150 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
2151 778b75bb Manuel Franceschini
        try:
2152 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
2153 778b75bb Manuel Franceschini
        except OSError, err:
2154 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
2155 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
2156 778b75bb Manuel Franceschini
          result =  False,
2157 778b75bb Manuel Franceschini
      else:
2158 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
2159 778b75bb Manuel Franceschini
        result = False,
2160 778b75bb Manuel Franceschini
    else:
2161 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
2162 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
2163 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
2164 778b75bb Manuel Franceschini
        result = False,
2165 778b75bb Manuel Franceschini
  return result
2166 778b75bb Manuel Franceschini
2167 778b75bb Manuel Franceschini
2168 dc31eae3 Michael Hanselmann
def _IsJobQueueFile(file_name):
2169 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2170 ca52cdeb Michael Hanselmann

2171 10c2650b Iustin Pop
  @type file_name: str
2172 10c2650b Iustin Pop
  @param file_name: the file name we should check
2173 10c2650b Iustin Pop
  @rtype: boolean
2174 10c2650b Iustin Pop
  @return: whether the file is under the queue directory
2175 10c2650b Iustin Pop

2176 ca52cdeb Michael Hanselmann
  """
2177 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2178 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2179 dc31eae3 Michael Hanselmann
2180 dc31eae3 Michael Hanselmann
  if not result:
2181 ca52cdeb Michael Hanselmann
    logging.error("'%s' is not a file in the queue directory",
2182 ca52cdeb Michael Hanselmann
                  file_name)
2183 dc31eae3 Michael Hanselmann
2184 dc31eae3 Michael Hanselmann
  return result
2185 dc31eae3 Michael Hanselmann
2186 dc31eae3 Michael Hanselmann
2187 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2188 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2189 dc31eae3 Michael Hanselmann

2190 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2191 10c2650b Iustin Pop
  checking.
2192 10c2650b Iustin Pop

2193 10c2650b Iustin Pop
  @type file_name: str
2194 10c2650b Iustin Pop
  @param file_name: the job file name
2195 10c2650b Iustin Pop
  @type content: str
2196 10c2650b Iustin Pop
  @param content: the new job contents
2197 10c2650b Iustin Pop
  @rtype: boolean
2198 10c2650b Iustin Pop
  @return: the success of the operation
2199 10c2650b Iustin Pop

2200 dc31eae3 Michael Hanselmann
  """
2201 dc31eae3 Michael Hanselmann
  if not _IsJobQueueFile(file_name):
2202 ca52cdeb Michael Hanselmann
    return False
2203 ca52cdeb Michael Hanselmann
2204 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2205 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2206 ca52cdeb Michael Hanselmann
2207 ca52cdeb Michael Hanselmann
  return True
2208 ca52cdeb Michael Hanselmann
2209 ca52cdeb Michael Hanselmann
2210 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2211 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2212 af5ebcb1 Michael Hanselmann

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

2215 10c2650b Iustin Pop
  @type old: str
2216 10c2650b Iustin Pop
  @param old: the old (actual) file name
2217 10c2650b Iustin Pop
  @type new: str
2218 10c2650b Iustin Pop
  @param new: the desired file name
2219 10c2650b Iustin Pop
  @rtype: boolean
2220 10c2650b Iustin Pop
  @return: the success of the operation
2221 10c2650b Iustin Pop

2222 af5ebcb1 Michael Hanselmann
  """
2223 af5ebcb1 Michael Hanselmann
  if not (_IsJobQueueFile(old) and _IsJobQueueFile(new)):
2224 af5ebcb1 Michael Hanselmann
    return False
2225 af5ebcb1 Michael Hanselmann
2226 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2227 af5ebcb1 Michael Hanselmann
2228 af5ebcb1 Michael Hanselmann
  return True
2229 af5ebcb1 Michael Hanselmann
2230 af5ebcb1 Michael Hanselmann
2231 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2232 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2233 5d672980 Iustin Pop

2234 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2235 5d672980 Iustin Pop

2236 10c2650b Iustin Pop
  @type drain_flag: boolean
2237 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2238 10c2650b Iustin Pop
  @rtype: boolean
2239 10c2650b Iustin Pop
  @return: always True
2240 10c2650b Iustin Pop
  @warning: the function always returns True
2241 5d672980 Iustin Pop

2242 5d672980 Iustin Pop
  """
2243 5d672980 Iustin Pop
  if drain_flag:
2244 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2245 5d672980 Iustin Pop
  else:
2246 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2247 5d672980 Iustin Pop
2248 5d672980 Iustin Pop
  return True
2249 5d672980 Iustin Pop
2250 5d672980 Iustin Pop
2251 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2252 d61cbe76 Iustin Pop
  """Closes the given block devices.
2253 d61cbe76 Iustin Pop

2254 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2255 10c2650b Iustin Pop
  DRBD).
2256 10c2650b Iustin Pop

2257 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2258 b2e7666a Iustin Pop
      of this instance will be removed
2259 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2260 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2261 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2262 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2263 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2264 10c2650b Iustin Pop
      which will contain the error details in case we
2265 10c2650b Iustin Pop
      failed
2266 d61cbe76 Iustin Pop

2267 d61cbe76 Iustin Pop
  """
2268 d61cbe76 Iustin Pop
  bdevs = []
2269 d61cbe76 Iustin Pop
  for cf in disks:
2270 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2271 d61cbe76 Iustin Pop
    if rd is None:
2272 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
2273 d61cbe76 Iustin Pop
    bdevs.append(rd)
2274 d61cbe76 Iustin Pop
2275 d61cbe76 Iustin Pop
  msg = []
2276 d61cbe76 Iustin Pop
  for rd in bdevs:
2277 d61cbe76 Iustin Pop
    try:
2278 d61cbe76 Iustin Pop
      rd.Close()
2279 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2280 d61cbe76 Iustin Pop
      msg.append(str(err))
2281 d61cbe76 Iustin Pop
  if msg:
2282 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
2283 d61cbe76 Iustin Pop
  else:
2284 b2e7666a Iustin Pop
    if instance_name:
2285 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2286 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
2287 d61cbe76 Iustin Pop
2288 d61cbe76 Iustin Pop
2289 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2290 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2291 6217e295 Iustin Pop

2292 6217e295 Iustin Pop
  @type hvname: string
2293 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2294 6217e295 Iustin Pop
  @type hvparams: dict
2295 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2296 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2297 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2298 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2299 10c2650b Iustin Pop
      which will contain the error details in case we
2300 10c2650b Iustin Pop
      failed
2301 6217e295 Iustin Pop

2302 6217e295 Iustin Pop
  """
2303 6217e295 Iustin Pop
  try:
2304 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2305 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2306 6217e295 Iustin Pop
    return (True, "Validation passed")
2307 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2308 6217e295 Iustin Pop
    return (False, str(err))
2309 6217e295 Iustin Pop
2310 6217e295 Iustin Pop
2311 56aa9fd5 Iustin Pop
def DemoteFromMC():
2312 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2313 56aa9fd5 Iustin Pop

2314 56aa9fd5 Iustin Pop
  """
2315 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2316 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2317 56aa9fd5 Iustin Pop
  if master == myself:
2318 56aa9fd5 Iustin Pop
    return (False, "ssconf status shows I'm the master node, will not demote")
2319 56aa9fd5 Iustin Pop
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2320 56aa9fd5 Iustin Pop
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2321 56aa9fd5 Iustin Pop
    return (False, "The master daemon is running, will not demote")
2322 56aa9fd5 Iustin Pop
  try:
2323 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2324 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2325 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2326 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2327 56aa9fd5 Iustin Pop
      return (False, "Error while backing up cluster file: %s" % str(err))
2328 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2329 56aa9fd5 Iustin Pop
  return (True, "Done")
2330 56aa9fd5 Iustin Pop
2331 56aa9fd5 Iustin Pop
2332 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2333 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2334 6b93ec9d Iustin Pop

2335 6b93ec9d Iustin Pop
  """
2336 6b93ec9d Iustin Pop
  # set the correct physical ID
2337 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2338 6b93ec9d Iustin Pop
  for cf in disks:
2339 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2340 6b93ec9d Iustin Pop
2341 6b93ec9d Iustin Pop
  bdevs = []
2342 6b93ec9d Iustin Pop
2343 6b93ec9d Iustin Pop
  for cf in disks:
2344 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2345 6b93ec9d Iustin Pop
    if rd is None:
2346 6b93ec9d Iustin Pop
      return (False, "Can't find device %s" % cf)
2347 6b93ec9d Iustin Pop
    bdevs.append(rd)
2348 6b93ec9d Iustin Pop
  return (True, bdevs)
2349 6b93ec9d Iustin Pop
2350 6b93ec9d Iustin Pop
2351 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2352 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2353 6b93ec9d Iustin Pop

2354 6b93ec9d Iustin Pop
  """
2355 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2356 6b93ec9d Iustin Pop
  if not status:
2357 6b93ec9d Iustin Pop
    return status, bdevs
2358 6b93ec9d Iustin Pop
2359 6b93ec9d Iustin Pop
  # disconnect disks
2360 6b93ec9d Iustin Pop
  for rd in bdevs:
2361 6b93ec9d Iustin Pop
    try:
2362 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2363 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2364 6b93ec9d Iustin Pop
      logging.exception("Failed to go into standalone mode")
2365 6b93ec9d Iustin Pop
      return (False, "Can't change network configuration: %s" % str(err))
2366 6b93ec9d Iustin Pop
  return (True, "All disks are now disconnected")
2367 6b93ec9d Iustin Pop
2368 6b93ec9d Iustin Pop
2369 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2370 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2371 6b93ec9d Iustin Pop

2372 6b93ec9d Iustin Pop
  """
2373 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2374 6b93ec9d Iustin Pop
  if not status:
2375 6b93ec9d Iustin Pop
    return status, bdevs
2376 6b93ec9d Iustin Pop
2377 6b93ec9d Iustin Pop
  if multimaster:
2378 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2379 6b93ec9d Iustin Pop
      try:
2380 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2381 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2382 6b93ec9d Iustin Pop
        return (False, "Can't create symlink: %s" % str(err))
2383 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2384 6b93ec9d Iustin Pop
  # needed primary mode
2385 6b93ec9d Iustin Pop
  for rd in bdevs:
2386 6b93ec9d Iustin Pop
    try:
2387 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2388 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2389 6b93ec9d Iustin Pop
      return (False, "Can't change network configuration: %s" % str(err))
2390 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2391 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2392 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2393 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2394 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2395 6b93ec9d Iustin Pop
  RECONNECT_TIMEOUT = 2 * 60
2396 6b93ec9d Iustin Pop
  sleep_time = 0.100 # start with 100 miliseconds
2397 6b93ec9d Iustin Pop
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2398 6b93ec9d Iustin Pop
  while time.time() < timeout_limit:
2399 6b93ec9d Iustin Pop
    all_connected = True
2400 6b93ec9d Iustin Pop
    for rd in bdevs:
2401 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2402 6b93ec9d Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2403 6b93ec9d Iustin Pop
        all_connected = False
2404 6b93ec9d Iustin Pop
      if stats.is_standalone:
2405 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2406 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2407 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2408 6b93ec9d Iustin Pop
        try:
2409 c738375b Iustin Pop
          rd.AttachNet(multimaster)
2410 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2411 6b93ec9d Iustin Pop
          return (False, "Can't change network configuration: %s" % str(err))
2412 6b93ec9d Iustin Pop
    if all_connected:
2413 6b93ec9d Iustin Pop
      break
2414 6b93ec9d Iustin Pop
    time.sleep(sleep_time)
2415 6b93ec9d Iustin Pop
    sleep_time = min(5, sleep_time * 1.5)
2416 6b93ec9d Iustin Pop
  if not all_connected:
2417 6b93ec9d Iustin Pop
    return (False, "Timeout in disk reconnecting")
2418 6b93ec9d Iustin Pop
  if multimaster:
2419 6b93ec9d Iustin Pop
    # change to primary mode
2420 6b93ec9d Iustin Pop
    for rd in bdevs:
2421 d3da87b8 Iustin Pop
      try:
2422 d3da87b8 Iustin Pop
        rd.Open()
2423 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
2424 d3da87b8 Iustin Pop
        return (False, "Can't change to primary mode: %s" % str(err))
2425 6b93ec9d Iustin Pop
  if multimaster:
2426 6b93ec9d Iustin Pop
    msg = "multi-master and primary"
2427 6b93ec9d Iustin Pop
  else:
2428 6b93ec9d Iustin Pop
    msg = "single-master"
2429 6b93ec9d Iustin Pop
  return (True, "Disks are now configured as %s" % msg)
2430 6b93ec9d Iustin Pop
2431 6b93ec9d Iustin Pop
2432 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2433 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2434 6b93ec9d Iustin Pop

2435 6b93ec9d Iustin Pop
  """
2436 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2437 6b93ec9d Iustin Pop
  if not status:
2438 6b93ec9d Iustin Pop
    return status, bdevs
2439 6b93ec9d Iustin Pop
2440 6b93ec9d Iustin Pop
  min_resync = 100
2441 6b93ec9d Iustin Pop
  alldone = True
2442 6b93ec9d Iustin Pop
  failure = False
2443 6b93ec9d Iustin Pop
  for rd in bdevs:
2444 6b93ec9d Iustin Pop
    stats = rd.GetProcStatus()
2445 6b93ec9d Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2446 6b93ec9d Iustin Pop
      failure = True
2447 6b93ec9d Iustin Pop
      break
2448 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2449 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2450 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2451 6b93ec9d Iustin Pop
  return (not failure, (alldone, min_resync))
2452 6b93ec9d Iustin Pop
2453 6b93ec9d Iustin Pop
2454 a8083063 Iustin Pop
class HooksRunner(object):
2455 a8083063 Iustin Pop
  """Hook runner.
2456 a8083063 Iustin Pop

2457 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2458 10c2650b Iustin Pop
  on the master side.
2459 a8083063 Iustin Pop

2460 a8083063 Iustin Pop
  """
2461 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2462 a8083063 Iustin Pop
2463 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2464 a8083063 Iustin Pop
    """Constructor for hooks runner.
2465 a8083063 Iustin Pop

2466 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2467 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2468 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2469 a8083063 Iustin Pop

2470 a8083063 Iustin Pop
    """
2471 a8083063 Iustin Pop
    if hooks_base_dir is None:
2472 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2473 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2474 a8083063 Iustin Pop
2475 a8083063 Iustin Pop
  @staticmethod
2476 a8083063 Iustin Pop
  def ExecHook(script, env):
2477 a8083063 Iustin Pop
    """Exec one hook script.
2478 a8083063 Iustin Pop

2479 10c2650b Iustin Pop
    @type script: str
2480 10c2650b Iustin Pop
    @param script: the full path to the script
2481 10c2650b Iustin Pop
    @type env: dict
2482 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2483 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2484 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2485 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2486 10c2650b Iustin Pop
        which will contain the error details in case we
2487 10c2650b Iustin Pop
        failed
2488 a8083063 Iustin Pop

2489 a8083063 Iustin Pop
    """
2490 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2491 a8083063 Iustin Pop
    fdstdin = None
2492 a8083063 Iustin Pop
    try:
2493 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2494 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2495 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2496 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2497 a8083063 Iustin Pop
      output = ""
2498 a8083063 Iustin Pop
      try:
2499 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2500 a8083063 Iustin Pop
        child.stdout.close()
2501 a8083063 Iustin Pop
      except EnvironmentError, err:
2502 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2503 a8083063 Iustin Pop
2504 a8083063 Iustin Pop
      while True:
2505 a8083063 Iustin Pop
        try:
2506 a8083063 Iustin Pop
          result = child.wait()
2507 a8083063 Iustin Pop
          break
2508 a8083063 Iustin Pop
        except EnvironmentError, err:
2509 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2510 a8083063 Iustin Pop
            continue
2511 a8083063 Iustin Pop
          raise
2512 a8083063 Iustin Pop
    finally:
2513 a8083063 Iustin Pop
      # try not to leak fds
2514 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2515 a8083063 Iustin Pop
        if fd is not None:
2516 a8083063 Iustin Pop
          try:
2517 a8083063 Iustin Pop
            fd.close()
2518 a8083063 Iustin Pop
          except EnvironmentError, err:
2519 a8083063 Iustin Pop
            # just log the error
2520 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2521 a8083063 Iustin Pop
            pass
2522 a8083063 Iustin Pop
2523 26f15862 Iustin Pop
    return result == 0, utils.SafeEncode(output.strip())
2524 a8083063 Iustin Pop
2525 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2526 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2527 a8083063 Iustin Pop

2528 10c2650b Iustin Pop
    @type hpath: str
2529 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2530 10c2650b Iustin Pop
        holds the scripts
2531 10c2650b Iustin Pop
    @type phase: str
2532 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2533 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2534 10c2650b Iustin Pop
    @type env: dict
2535 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2536 10c2650b Iustin Pop
    @rtype: list
2537 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2538 10c2650b Iustin Pop
      - script path
2539 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2540 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2541 10c2650b Iustin Pop
      - output of the script
2542 10c2650b Iustin Pop

2543 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2544 10c2650b Iustin Pop
        parameters
2545 a8083063 Iustin Pop

2546 a8083063 Iustin Pop
    """
2547 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2548 a8083063 Iustin Pop
      suffix = "pre"
2549 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2550 a8083063 Iustin Pop
      suffix = "post"
2551 a8083063 Iustin Pop
    else:
2552 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
2553 a8083063 Iustin Pop
    rr = []
2554 a8083063 Iustin Pop
2555 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2556 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2557 a8083063 Iustin Pop
    try:
2558 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2559 a8083063 Iustin Pop
    except OSError, err:
2560 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2561 a8083063 Iustin Pop
      return rr
2562 a8083063 Iustin Pop
2563 a8083063 Iustin Pop
    # we use the standard python sort order,
2564 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2565 a8083063 Iustin Pop
    dir_contents.sort()
2566 a8083063 Iustin Pop
    for relname in dir_contents:
2567 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2568 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2569 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2570 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2571 a8083063 Iustin Pop
        output = ""
2572 a8083063 Iustin Pop
      else:
2573 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2574 a8083063 Iustin Pop
        if not result:
2575 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2576 a8083063 Iustin Pop
        else:
2577 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2578 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2579 a8083063 Iustin Pop
2580 a8083063 Iustin Pop
    return rr
2581 3f78eef2 Iustin Pop
2582 3f78eef2 Iustin Pop
2583 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2584 8d528b7c Iustin Pop
  """IAllocator runner.
2585 8d528b7c Iustin Pop

2586 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2587 8d528b7c Iustin Pop
  the master side.
2588 8d528b7c Iustin Pop

2589 8d528b7c Iustin Pop
  """
2590 8d528b7c Iustin Pop
  def Run(self, name, idata):
2591 8d528b7c Iustin Pop
    """Run an iallocator script.
2592 8d528b7c Iustin Pop

2593 10c2650b Iustin Pop
    @type name: str
2594 10c2650b Iustin Pop
    @param name: the iallocator script name
2595 10c2650b Iustin Pop
    @type idata: str
2596 10c2650b Iustin Pop
    @param idata: the allocator input data
2597 10c2650b Iustin Pop

2598 10c2650b Iustin Pop
    @rtype: tuple
2599 10c2650b Iustin Pop
    @return: four element tuple of:
2600 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
2601 8d528b7c Iustin Pop
       - stdout
2602 8d528b7c Iustin Pop
       - stderr
2603 10c2650b Iustin Pop
       - fail reason (as from L{utils.RunResult})
2604 8d528b7c Iustin Pop

2605 8d528b7c Iustin Pop
    """
2606 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2607 8d528b7c Iustin Pop
                                  os.path.isfile)
2608 8d528b7c Iustin Pop
    if alloc_script is None:
2609 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
2610 8d528b7c Iustin Pop
2611 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2612 8d528b7c Iustin Pop
    try:
2613 8d528b7c Iustin Pop
      os.write(fd, idata)
2614 8d528b7c Iustin Pop
      os.close(fd)
2615 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2616 8d528b7c Iustin Pop
      if result.failed:
2617 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
2618 8d528b7c Iustin Pop
                result.fail_reason)
2619 8d528b7c Iustin Pop
    finally:
2620 8d528b7c Iustin Pop
      os.unlink(fin_name)
2621 8d528b7c Iustin Pop
2622 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
2623 8d528b7c Iustin Pop
2624 8d528b7c Iustin Pop
2625 3f78eef2 Iustin Pop
class DevCacheManager(object):
2626 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2627 3f78eef2 Iustin Pop

2628 3f78eef2 Iustin Pop
  """
2629 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2630 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2631 3f78eef2 Iustin Pop
2632 3f78eef2 Iustin Pop
  @classmethod
2633 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2634 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2635 3f78eef2 Iustin Pop

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

2639 10c2650b Iustin Pop
    @type dev_path: str
2640 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2641 10c2650b Iustin Pop
    @rtype: str
2642 10c2650b Iustin Pop
    @return: the converted path name
2643 3f78eef2 Iustin Pop

2644 3f78eef2 Iustin Pop
    """
2645 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2646 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2647 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2648 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2649 3f78eef2 Iustin Pop
    return fpath
2650 3f78eef2 Iustin Pop
2651 3f78eef2 Iustin Pop
  @classmethod
2652 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2653 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2654 3f78eef2 Iustin Pop

2655 10c2650b Iustin Pop
    @type dev_path: str
2656 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2657 10c2650b Iustin Pop
    @type owner: str
2658 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2659 10c2650b Iustin Pop
    @type on_primary: bool
2660 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2661 10c2650b Iustin Pop
        node nor not
2662 10c2650b Iustin Pop
    @type iv_name: str
2663 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2664 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2665 10c2650b Iustin Pop

2666 10c2650b Iustin Pop
    @rtype: None
2667 10c2650b Iustin Pop

2668 3f78eef2 Iustin Pop
    """
2669 cf5a8306 Iustin Pop
    if dev_path is None:
2670 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2671 cf5a8306 Iustin Pop
      return
2672 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2673 3f78eef2 Iustin Pop
    if on_primary:
2674 3f78eef2 Iustin Pop
      state = "primary"
2675 3f78eef2 Iustin Pop
    else:
2676 3f78eef2 Iustin Pop
      state = "secondary"
2677 3f78eef2 Iustin Pop
    if iv_name is None:
2678 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2679 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2680 3f78eef2 Iustin Pop
    try:
2681 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2682 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2683 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
2684 3f78eef2 Iustin Pop
2685 3f78eef2 Iustin Pop
  @classmethod
2686 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2687 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2688 3f78eef2 Iustin Pop

2689 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2690 10c2650b Iustin Pop
    path name and logging.
2691 10c2650b Iustin Pop

2692 10c2650b Iustin Pop
    @type dev_path: str
2693 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2694 10c2650b Iustin Pop

2695 10c2650b Iustin Pop
    @rtype: None
2696 10c2650b Iustin Pop

2697 3f78eef2 Iustin Pop
    """
2698 cf5a8306 Iustin Pop
    if dev_path is None:
2699 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2700 cf5a8306 Iustin Pop
      return
2701 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2702 3f78eef2 Iustin Pop
    try:
2703 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2704 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2705 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)