Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ fe267188

History | View | Annotate | Download (82.2 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 360b0dc2 Iustin Pop
"""Functions used by the node daemon
23 360b0dc2 Iustin Pop

24 360b0dc2 Iustin Pop
@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
25 360b0dc2 Iustin Pop
     the L{UploadFile} function
26 360b0dc2 Iustin Pop

27 360b0dc2 Iustin Pop
"""
28 a8083063 Iustin Pop
29 a8083063 Iustin Pop
30 a8083063 Iustin Pop
import os
31 a8083063 Iustin Pop
import os.path
32 a8083063 Iustin Pop
import shutil
33 a8083063 Iustin Pop
import time
34 a8083063 Iustin Pop
import stat
35 a8083063 Iustin Pop
import errno
36 a8083063 Iustin Pop
import re
37 a8083063 Iustin Pop
import subprocess
38 b544cfe0 Iustin Pop
import random
39 18682bca Iustin Pop
import logging
40 3b9e6a30 Iustin Pop
import tempfile
41 12bce260 Michael Hanselmann
import zlib
42 12bce260 Michael Hanselmann
import base64
43 a8083063 Iustin Pop
44 a8083063 Iustin Pop
from ganeti import errors
45 a8083063 Iustin Pop
from ganeti import utils
46 a8083063 Iustin Pop
from ganeti import ssh
47 a8083063 Iustin Pop
from ganeti import hypervisor
48 a8083063 Iustin Pop
from ganeti import constants
49 a8083063 Iustin Pop
from ganeti import bdev
50 a8083063 Iustin Pop
from ganeti import objects
51 880478f8 Iustin Pop
from ganeti import ssconf
52 a8083063 Iustin Pop
53 a8083063 Iustin Pop
54 c657dcc9 Michael Hanselmann
def _GetConfig():
55 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
56 10c2650b Iustin Pop

57 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
58 93384844 Iustin Pop
  @return: a SimpleStore instance
59 10c2650b Iustin Pop

60 10c2650b Iustin Pop
  """
61 93384844 Iustin Pop
  return ssconf.SimpleStore()
62 c657dcc9 Michael Hanselmann
63 c657dcc9 Michael Hanselmann
64 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
65 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
66 10c2650b Iustin Pop

67 10c2650b Iustin Pop
  @type cluster_name: str
68 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
69 10c2650b Iustin Pop
      by the SshRunner constructor
70 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
71 10c2650b Iustin Pop
  @return: an SshRunner instance
72 10c2650b Iustin Pop

73 10c2650b Iustin Pop
  """
74 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
75 c92b310a Michael Hanselmann
76 c92b310a Michael Hanselmann
77 12bce260 Michael Hanselmann
def _Decompress(data):
78 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
79 12bce260 Michael Hanselmann

80 12bce260 Michael Hanselmann
  @type data: list or tuple
81 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
82 12bce260 Michael Hanselmann
  @rtype: str
83 12bce260 Michael Hanselmann
  @return: Decompressed data
84 12bce260 Michael Hanselmann

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

100 10c2650b Iustin Pop
  @type path: str
101 10c2650b Iustin Pop
  @param path: the directory to clean
102 76ab5558 Michael Hanselmann
  @type exclude: list
103 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
104 10c2650b Iustin Pop
      to the empty list
105 76ab5558 Michael Hanselmann

106 76ab5558 Michael Hanselmann
  """
107 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
108 3956cee1 Michael Hanselmann
    return
109 3bc6be5c Iustin Pop
  if exclude is None:
110 3bc6be5c Iustin Pop
    exclude = []
111 3bc6be5c Iustin Pop
  else:
112 3bc6be5c Iustin Pop
    # Normalize excluded paths
113 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
114 76ab5558 Michael Hanselmann
115 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
116 76ab5558 Michael Hanselmann
    full_name = os.path.normpath(os.path.join(path, rel_name))
117 76ab5558 Michael Hanselmann
    if full_name in exclude:
118 76ab5558 Michael Hanselmann
      continue
119 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
120 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
121 3956cee1 Michael Hanselmann
122 3956cee1 Michael Hanselmann
123 360b0dc2 Iustin Pop
def _BuildUploadFileList():
124 360b0dc2 Iustin Pop
  """Build the list of allowed upload files.
125 360b0dc2 Iustin Pop

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

128 360b0dc2 Iustin Pop
  """
129 360b0dc2 Iustin Pop
  return frozenset([
130 360b0dc2 Iustin Pop
      constants.CLUSTER_CONF_FILE,
131 360b0dc2 Iustin Pop
      constants.ETC_HOSTS,
132 360b0dc2 Iustin Pop
      constants.SSH_KNOWN_HOSTS_FILE,
133 360b0dc2 Iustin Pop
      constants.VNC_PASSWORD_FILE,
134 360b0dc2 Iustin Pop
      ])
135 360b0dc2 Iustin Pop
136 360b0dc2 Iustin Pop
137 360b0dc2 Iustin Pop
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
138 360b0dc2 Iustin Pop
139 360b0dc2 Iustin Pop
140 1bc59f76 Michael Hanselmann
def JobQueuePurge():
141 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
142 10c2650b Iustin Pop

143 10c2650b Iustin Pop
  @rtype: None
144 24fc781f Michael Hanselmann

145 24fc781f Michael Hanselmann
  """
146 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
147 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
148 24fc781f Michael Hanselmann
149 24fc781f Michael Hanselmann
150 bd1e4562 Iustin Pop
def GetMasterInfo():
151 bd1e4562 Iustin Pop
  """Returns master information.
152 bd1e4562 Iustin Pop

153 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
154 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
155 bd1e4562 Iustin Pop

156 bd1e4562 Iustin Pop
  @rtype: tuple
157 10c2650b Iustin Pop
  @return: (master_netdev, master_ip, master_name) if we have a good
158 10c2650b Iustin Pop
      configuration, otherwise (None, None, None)
159 b1b6ea87 Iustin Pop

160 b1b6ea87 Iustin Pop
  """
161 b1b6ea87 Iustin Pop
  try:
162 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
163 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
164 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
165 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
166 7c4d6c7b Michael Hanselmann
  except errors.ConfigurationError:
167 b1b6ea87 Iustin Pop
    logging.exception("Cluster configuration incomplete")
168 0a70a72a Iustin Pop
    return (None, None, None)
169 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
170 b1b6ea87 Iustin Pop
171 b1b6ea87 Iustin Pop
172 2503680f Guido Trotter
def StartMaster(start_daemons, no_voting):
173 a8083063 Iustin Pop
  """Activate local node as master node.
174 a8083063 Iustin Pop

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

179 10c2650b Iustin Pop
  @type start_daemons: boolean
180 10c2650b Iustin Pop
  @param start_daemons: whther to also start the master
181 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
182 2503680f Guido Trotter
  @type no_voting: boolean
183 2503680f Guido Trotter
  @param no_voting: whether to start ganeti-masterd without a node vote
184 2503680f Guido Trotter
      (if start_daemons is True), but still non-interactively
185 10c2650b Iustin Pop
  @rtype: None
186 a8083063 Iustin Pop

187 a8083063 Iustin Pop
  """
188 b1b6ea87 Iustin Pop
  ok = True
189 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
190 b1b6ea87 Iustin Pop
  if not master_netdev:
191 a8083063 Iustin Pop
    return False
192 a8083063 Iustin Pop
193 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
194 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
195 b1b6ea87 Iustin Pop
      # we already have the ip:
196 b1b6ea87 Iustin Pop
      logging.debug("Already started")
197 b1b6ea87 Iustin Pop
    else:
198 b1b6ea87 Iustin Pop
      logging.error("Someone else has the master ip, not activating")
199 b1b6ea87 Iustin Pop
      ok = False
200 b1b6ea87 Iustin Pop
  else:
201 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
202 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
203 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
204 b1b6ea87 Iustin Pop
    if result.failed:
205 b1b6ea87 Iustin Pop
      logging.error("Can't activate master IP: %s", result.output)
206 b1b6ea87 Iustin Pop
      ok = False
207 b1b6ea87 Iustin Pop
208 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
209 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
210 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
211 b1b6ea87 Iustin Pop
212 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
213 b1b6ea87 Iustin Pop
  if start_daemons:
214 2503680f Guido Trotter
    daemons_params = {
215 2503680f Guido Trotter
        'ganeti-masterd': [],
216 2503680f Guido Trotter
        'ganeti-rapi': [],
217 2503680f Guido Trotter
        }
218 2503680f Guido Trotter
    if no_voting:
219 2503680f Guido Trotter
      daemons_params['ganeti-masterd'].append('--no-voting')
220 2503680f Guido Trotter
      daemons_params['ganeti-masterd'].append('--yes-do-it')
221 2503680f Guido Trotter
    for daemon in daemons_params:
222 2503680f Guido Trotter
      cmd = [daemon]
223 2503680f Guido Trotter
      cmd.extend(daemons_params[daemon])
224 2503680f Guido Trotter
      result = utils.RunCmd(cmd)
225 b1b6ea87 Iustin Pop
      if result.failed:
226 b1b6ea87 Iustin Pop
        logging.error("Can't start daemon %s: %s", daemon, result.output)
227 b1b6ea87 Iustin Pop
        ok = False
228 b1b6ea87 Iustin Pop
  return ok
229 a8083063 Iustin Pop
230 a8083063 Iustin Pop
231 1c65840b Iustin Pop
def StopMaster(stop_daemons):
232 a8083063 Iustin Pop
  """Deactivate this node as master.
233 a8083063 Iustin Pop

234 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
235 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
236 10c2650b Iustin Pop
  stop_daemons parameter.
237 10c2650b Iustin Pop

238 10c2650b Iustin Pop
  @type stop_daemons: boolean
239 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
240 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
241 10c2650b Iustin Pop
  @rtype: None
242 a8083063 Iustin Pop

243 a8083063 Iustin Pop
  """
244 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
245 b1b6ea87 Iustin Pop
  if not master_netdev:
246 b1b6ea87 Iustin Pop
    return False
247 a8083063 Iustin Pop
248 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
249 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
250 a8083063 Iustin Pop
  if result.failed:
251 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
252 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
253 b1b6ea87 Iustin Pop
254 b1b6ea87 Iustin Pop
  if stop_daemons:
255 b1b6ea87 Iustin Pop
    # stop/kill the rapi and the master daemon
256 b1b6ea87 Iustin Pop
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
257 b1b6ea87 Iustin Pop
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
258 a8083063 Iustin Pop
259 a8083063 Iustin Pop
  return True
260 a8083063 Iustin Pop
261 a8083063 Iustin Pop
262 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
263 7900ed01 Iustin Pop
  """Joins this node to the cluster.
264 a8083063 Iustin Pop

265 7900ed01 Iustin Pop
  This does the following:
266 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
267 7900ed01 Iustin Pop
      - adds the ssh private key to the user
268 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
269 a8083063 Iustin Pop

270 10c2650b Iustin Pop
  @type dsa: str
271 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
272 10c2650b Iustin Pop
  @type dsapub: str
273 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
274 10c2650b Iustin Pop
  @type rsa: str
275 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
276 10c2650b Iustin Pop
  @type rsapub: str
277 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
278 10c2650b Iustin Pop
  @type sshkey: str
279 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
280 10c2650b Iustin Pop
  @type sshpub: str
281 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
282 10c2650b Iustin Pop
  @rtype: boolean
283 10c2650b Iustin Pop
  @return: the success of the operation
284 10c2650b Iustin Pop

285 7900ed01 Iustin Pop
  """
286 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
287 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
288 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
289 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
290 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
291 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
292 a8083063 Iustin Pop
293 70d9e3d8 Iustin Pop
  try:
294 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
295 70d9e3d8 Iustin Pop
                                                    mkdir=True)
296 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
297 a1b805fb Iustin Pop
    msg = "Error while processing user ssh files"
298 a1b805fb Iustin Pop
    logging.exception(msg)
299 a1b805fb Iustin Pop
    return (False, "%s: %s" % (msg, err))
300 a8083063 Iustin Pop
301 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
302 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
303 a8083063 Iustin Pop
304 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
305 a8083063 Iustin Pop
306 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
307 a8083063 Iustin Pop
308 a1b805fb Iustin Pop
  return (True, "Node added successfully")
309 a8083063 Iustin Pop
310 a8083063 Iustin Pop
311 a8083063 Iustin Pop
def LeaveCluster():
312 10c2650b Iustin Pop
  """Cleans up and remove the current node.
313 10c2650b Iustin Pop

314 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
315 10c2650b Iustin Pop
  from the cluster.
316 10c2650b Iustin Pop

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

321 a8083063 Iustin Pop
  """
322 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
323 1bc59f76 Michael Hanselmann
  JobQueuePurge()
324 f78346f5 Michael Hanselmann
325 70d9e3d8 Iustin Pop
  try:
326 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
327 18682bca Iustin Pop
  except errors.OpExecError:
328 18682bca Iustin Pop
    logging.exception("Error while processing ssh files")
329 7900ed01 Iustin Pop
    return
330 7900ed01 Iustin Pop
331 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
332 a8083063 Iustin Pop
  try:
333 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
334 a8083063 Iustin Pop
  finally:
335 a8083063 Iustin Pop
    f.close()
336 a8083063 Iustin Pop
337 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
338 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
339 a8083063 Iustin Pop
340 6d8b6238 Guido Trotter
  # Return a reassuring string to the caller, and quit
341 6d8b6238 Guido Trotter
  raise errors.QuitGanetiException(False, 'Shutdown scheduled')
342 6d8b6238 Guido Trotter
343 a8083063 Iustin Pop
344 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
345 5bbd3f7f Michael Hanselmann
  """Gives back a hash with different information about the node.
346 a8083063 Iustin Pop

347 e69d05fd Iustin Pop
  @type vgname: C{string}
348 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
349 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
350 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
351 e69d05fd Iustin Pop
      memory information
352 e69d05fd Iustin Pop
  @rtype: C{dict}
353 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
354 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
355 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
356 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
357 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
358 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
359 a8083063 Iustin Pop

360 098c0958 Michael Hanselmann
  """
361 a8083063 Iustin Pop
  outputarray = {}
362 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
363 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
364 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
365 a8083063 Iustin Pop
366 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
367 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
368 a8083063 Iustin Pop
  if hyp_info is not None:
369 a8083063 Iustin Pop
    outputarray.update(hyp_info)
370 a8083063 Iustin Pop
371 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
372 3ef10550 Michael Hanselmann
  try:
373 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
374 3ef10550 Michael Hanselmann
  finally:
375 3ef10550 Michael Hanselmann
    f.close()
376 3ef10550 Michael Hanselmann
377 a8083063 Iustin Pop
  return outputarray
378 a8083063 Iustin Pop
379 a8083063 Iustin Pop
380 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
381 a8083063 Iustin Pop
  """Verify the status of the local node.
382 a8083063 Iustin Pop

383 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
384 e69d05fd Iustin Pop
  local node.
385 e69d05fd Iustin Pop

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

389 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
390 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
391 e69d05fd Iustin Pop
  report).
392 a8083063 Iustin Pop

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

397 e69d05fd Iustin Pop
  @type what: C{dict}
398 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
399 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
400 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
401 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
402 e69d05fd Iustin Pop
        connectivity with
403 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
404 10c2650b Iustin Pop
  @rtype: dict
405 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
406 10c2650b Iustin Pop
      values representing the result of the checks
407 a8083063 Iustin Pop

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

485 10c2650b Iustin Pop
  @type vg_name: str
486 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
487 10c2650b Iustin Pop
  @rtype: dict
488 10c2650b Iustin Pop
  @return:
489 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
490 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
491 10c2650b Iustin Pop

492 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
493 10c2650b Iustin Pop

494 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
495 10c2650b Iustin Pop
      details.
496 a8083063 Iustin Pop

497 a8083063 Iustin Pop
  """
498 cb2037a2 Iustin Pop
  lvs = {}
499 cb2037a2 Iustin Pop
  sep = '|'
500 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
501 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
502 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
503 a8083063 Iustin Pop
  if result.failed:
504 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
505 18682bca Iustin Pop
                  result.output)
506 b63ed789 Iustin Pop
    return result.output
507 cb2037a2 Iustin Pop
508 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
509 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
510 df4c2628 Iustin Pop
    line = line.strip()
511 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
512 df4c2628 Iustin Pop
    if not match:
513 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
514 df4c2628 Iustin Pop
      continue
515 df4c2628 Iustin Pop
    name, size, attr = match.groups()
516 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
517 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
518 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
519 cb2037a2 Iustin Pop
520 cb2037a2 Iustin Pop
  return lvs
521 a8083063 Iustin Pop
522 a8083063 Iustin Pop
523 a8083063 Iustin Pop
def ListVolumeGroups():
524 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
525 a8083063 Iustin Pop

526 10c2650b Iustin Pop
  @rtype: dict
527 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
528 10c2650b Iustin Pop
      size of the volume
529 a8083063 Iustin Pop

530 a8083063 Iustin Pop
  """
531 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
532 a8083063 Iustin Pop
533 a8083063 Iustin Pop
534 dcb93971 Michael Hanselmann
def NodeVolumes():
535 dcb93971 Michael Hanselmann
  """List all volumes on this node.
536 dcb93971 Michael Hanselmann

537 10c2650b Iustin Pop
  @rtype: list
538 10c2650b Iustin Pop
  @return:
539 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
540 10c2650b Iustin Pop
      - name: the logical volume name,
541 10c2650b Iustin Pop
      - size: the size of the logical volume
542 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
543 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
544 10c2650b Iustin Pop

545 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
546 10c2650b Iustin Pop
    error.
547 10c2650b Iustin Pop

548 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
549 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
550 10c2650b Iustin Pop
    multiple times.
551 10c2650b Iustin Pop

552 dcb93971 Michael Hanselmann
  """
553 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
554 dcb93971 Michael Hanselmann
                         "--separator=|",
555 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
556 dcb93971 Michael Hanselmann
  if result.failed:
557 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
558 18682bca Iustin Pop
                  result.output)
559 3f5bd234 Iustin Pop
    return []
560 dcb93971 Michael Hanselmann
561 dcb93971 Michael Hanselmann
  def parse_dev(dev):
562 dcb93971 Michael Hanselmann
    if '(' in dev:
563 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
564 dcb93971 Michael Hanselmann
    else:
565 dcb93971 Michael Hanselmann
      return dev
566 dcb93971 Michael Hanselmann
567 dcb93971 Michael Hanselmann
  def map_line(line):
568 dcb93971 Michael Hanselmann
    return {
569 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
570 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
571 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
572 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
573 dcb93971 Michael Hanselmann
    }
574 dcb93971 Michael Hanselmann
575 a17a7623 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
576 a17a7623 Iustin Pop
          if line.count('|') >= 3]
577 dcb93971 Michael Hanselmann
578 dcb93971 Michael Hanselmann
579 a8083063 Iustin Pop
def BridgesExist(bridges_list):
580 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
581 a8083063 Iustin Pop

582 b1206984 Iustin Pop
  @rtype: boolean
583 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
584 a8083063 Iustin Pop

585 a8083063 Iustin Pop
  """
586 a8083063 Iustin Pop
  for bridge in bridges_list:
587 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
588 a8083063 Iustin Pop
      return False
589 a8083063 Iustin Pop
590 a8083063 Iustin Pop
  return True
591 a8083063 Iustin Pop
592 a8083063 Iustin Pop
593 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
594 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
595 a8083063 Iustin Pop

596 e69d05fd Iustin Pop
  @type hypervisor_list: list
597 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
598 e69d05fd Iustin Pop

599 e69d05fd Iustin Pop
  @rtype: list
600 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
601 10c2650b Iustin Pop
    - instance1.example.com
602 10c2650b Iustin Pop
    - instance2.example.com
603 a8083063 Iustin Pop

604 098c0958 Michael Hanselmann
  """
605 e69d05fd Iustin Pop
  results = []
606 e69d05fd Iustin Pop
  for hname in hypervisor_list:
607 e69d05fd Iustin Pop
    try:
608 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
609 e69d05fd Iustin Pop
      results.extend(names)
610 7c4d6c7b Michael Hanselmann
    except errors.HypervisorError:
611 e69d05fd Iustin Pop
      logging.exception("Error enumerating instances for hypevisor %s", hname)
612 e69d05fd Iustin Pop
      raise
613 a8083063 Iustin Pop
614 e69d05fd Iustin Pop
  return results
615 a8083063 Iustin Pop
616 a8083063 Iustin Pop
617 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
618 5bbd3f7f Michael Hanselmann
  """Gives back the information about an instance as a dictionary.
619 a8083063 Iustin Pop

620 e69d05fd Iustin Pop
  @type instance: string
621 e69d05fd Iustin Pop
  @param instance: the instance name
622 e69d05fd Iustin Pop
  @type hname: string
623 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
624 a8083063 Iustin Pop

625 e69d05fd Iustin Pop
  @rtype: dict
626 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
627 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
628 e69d05fd Iustin Pop
      - state: xen state of instance (string)
629 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
630 a8083063 Iustin Pop

631 098c0958 Michael Hanselmann
  """
632 a8083063 Iustin Pop
  output = {}
633 a8083063 Iustin Pop
634 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
635 a8083063 Iustin Pop
  if iinfo is not None:
636 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
637 a8083063 Iustin Pop
    output['state'] = iinfo[4]
638 a8083063 Iustin Pop
    output['time'] = iinfo[5]
639 a8083063 Iustin Pop
640 a8083063 Iustin Pop
  return output
641 a8083063 Iustin Pop
642 a8083063 Iustin Pop
643 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
644 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
645 56e7640c Iustin Pop

646 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
647 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
648 56e7640c Iustin Pop

649 56e7640c Iustin Pop
  @rtype: tuple
650 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
651 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
652 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
653 56e7640c Iustin Pop

654 56e7640c Iustin Pop
  """
655 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
656 56e7640c Iustin Pop
  if instance.name not in hyper.ListInstances():
657 56e7640c Iustin Pop
    return (False, 'not running')
658 56e7640c Iustin Pop
659 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
660 56e7640c Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance.name, idx)
661 56e7640c Iustin Pop
    if not os.path.islink(link_name):
662 56e7640c Iustin Pop
      return (False, 'not restarted since ganeti 1.2.5')
663 56e7640c Iustin Pop
664 56e7640c Iustin Pop
  return (True, '')
665 56e7640c Iustin Pop
666 56e7640c Iustin Pop
667 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
668 a8083063 Iustin Pop
  """Gather data about all instances.
669 a8083063 Iustin Pop

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

674 e69d05fd Iustin Pop
  @type hypervisor_list: list
675 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
676 e69d05fd Iustin Pop

677 955db481 Guido Trotter
  @rtype: dict
678 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
679 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
680 e69d05fd Iustin Pop
      - state: xen state of instance (string)
681 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
682 10c2650b Iustin Pop
      - vcpus: the number of vcpus
683 a8083063 Iustin Pop

684 098c0958 Michael Hanselmann
  """
685 a8083063 Iustin Pop
  output = {}
686 a8083063 Iustin Pop
687 e69d05fd Iustin Pop
  for hname in hypervisor_list:
688 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
689 e69d05fd Iustin Pop
    if iinfo:
690 e69d05fd Iustin Pop
      for name, inst_id, memory, vcpus, state, times in iinfo:
691 f23b5ae8 Iustin Pop
        value = {
692 e69d05fd Iustin Pop
          'memory': memory,
693 e69d05fd Iustin Pop
          'vcpus': vcpus,
694 e69d05fd Iustin Pop
          'state': state,
695 e69d05fd Iustin Pop
          'time': times,
696 e69d05fd Iustin Pop
          }
697 b33b6f55 Iustin Pop
        if name in output:
698 b33b6f55 Iustin Pop
          # we only check static parameters, like memory and vcpus,
699 b33b6f55 Iustin Pop
          # and not state and time which can change between the
700 b33b6f55 Iustin Pop
          # invocations of the different hypervisors
701 b33b6f55 Iustin Pop
          for key in 'memory', 'vcpus':
702 b33b6f55 Iustin Pop
            if value[key] != output[name][key]:
703 b33b6f55 Iustin Pop
              raise errors.HypervisorError("Instance %s is running twice"
704 b33b6f55 Iustin Pop
                                           " with different parameters" % name)
705 f23b5ae8 Iustin Pop
        output[name] = value
706 a8083063 Iustin Pop
707 a8083063 Iustin Pop
  return output
708 a8083063 Iustin Pop
709 a8083063 Iustin Pop
710 1268d6fd Iustin Pop
def InstanceOsAdd(instance):
711 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
712 a8083063 Iustin Pop

713 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
714 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
715 10c2650b Iustin Pop
  @rtype: boolean
716 10c2650b Iustin Pop
  @return: the success of the operation
717 a8083063 Iustin Pop

718 a8083063 Iustin Pop
  """
719 1268d6fd Iustin Pop
  try:
720 1268d6fd Iustin Pop
    inst_os = OSFromDisk(instance.os)
721 1268d6fd Iustin Pop
  except errors.InvalidOS, err:
722 1268d6fd Iustin Pop
    os_name, os_dir, os_err = err.args
723 1268d6fd Iustin Pop
    if os_dir is None:
724 1268d6fd Iustin Pop
      return (False, "Can't find OS '%s': %s" % (os_name, os_err))
725 1268d6fd Iustin Pop
    else:
726 1268d6fd Iustin Pop
      return (False, "Error parsing OS '%s' in directory %s: %s" %
727 1268d6fd Iustin Pop
              (os_name, os_dir, os_err))
728 a8083063 Iustin Pop
729 58f6e5ca Guido Trotter
  create_env = OSEnvironment(instance)
730 a8083063 Iustin Pop
731 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
732 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
733 decd5f45 Iustin Pop
734 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
735 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
736 decd5f45 Iustin Pop
  if result.failed:
737 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
738 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
739 18682bca Iustin Pop
                  result.output)
740 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
741 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
742 20e01edd Iustin Pop
    return (False, "OS create script failed (%s), last lines in the"
743 20e01edd Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
744 decd5f45 Iustin Pop
745 20e01edd Iustin Pop
  return (True, "Successfully installed")
746 decd5f45 Iustin Pop
747 decd5f45 Iustin Pop
748 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
749 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
750 decd5f45 Iustin Pop

751 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
752 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
753 d15a9ad3 Guido Trotter
  @type old_name: string
754 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
755 10c2650b Iustin Pop
  @rtype: boolean
756 10c2650b Iustin Pop
  @return: the success of the operation
757 decd5f45 Iustin Pop

758 decd5f45 Iustin Pop
  """
759 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
760 decd5f45 Iustin Pop
761 ff38b6c0 Guido Trotter
  rename_env = OSEnvironment(instance)
762 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
763 decd5f45 Iustin Pop
764 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
765 decd5f45 Iustin Pop
                                           old_name,
766 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
767 a8083063 Iustin Pop
768 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
769 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
770 a8083063 Iustin Pop
771 a8083063 Iustin Pop
  if result.failed:
772 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
773 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
774 26f15862 Iustin Pop
    lines = [utils.SafeEncode(val)
775 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
776 96841384 Iustin Pop
    return (False, "OS rename script failed (%s), last lines in the"
777 96841384 Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
778 a8083063 Iustin Pop
779 96841384 Iustin Pop
  return (True, "Rename successful")
780 a8083063 Iustin Pop
781 a8083063 Iustin Pop
782 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
783 5bbd3f7f Michael Hanselmann
  """Get information about the volume group.
784 a8083063 Iustin Pop

785 10c2650b Iustin Pop
  @type vg_name: str
786 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
787 10c2650b Iustin Pop
  @rtype: dict
788 10c2650b Iustin Pop
  @return:
789 10c2650b Iustin Pop
    A dictionary with the following keys:
790 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
791 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
792 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
793 a8083063 Iustin Pop

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

797 a8083063 Iustin Pop
  """
798 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
799 f4d377e7 Iustin Pop
800 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
801 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
802 a8083063 Iustin Pop
803 a8083063 Iustin Pop
  if retval.failed:
804 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
805 f4d377e7 Iustin Pop
    return retdic
806 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
807 f4d377e7 Iustin Pop
  if len(valarr) == 3:
808 f4d377e7 Iustin Pop
    try:
809 f4d377e7 Iustin Pop
      retdic = {
810 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
811 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
812 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
813 f4d377e7 Iustin Pop
        }
814 f4d377e7 Iustin Pop
    except ValueError, err:
815 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
816 f4d377e7 Iustin Pop
  else:
817 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
818 18682bca Iustin Pop
                  " three): %s", str(valarr))
819 a8083063 Iustin Pop
  return retdic
820 a8083063 Iustin Pop
821 a8083063 Iustin Pop
822 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
823 5282084b Iustin Pop
  return os.path.join(constants.DISK_LINKS_DIR,
824 5282084b Iustin Pop
                      "%s:%d" % (instance_name, idx))
825 5282084b Iustin Pop
826 5282084b Iustin Pop
827 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
828 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
829 9332fd8a Iustin Pop

830 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
831 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
832 9332fd8a Iustin Pop

833 9332fd8a Iustin Pop

834 5282084b Iustin Pop
  @param instance_name: the name of the target instance
835 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
836 5282084b Iustin Pop
  @param idx: the disk index
837 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
838 9332fd8a Iustin Pop

839 9332fd8a Iustin Pop
  """
840 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
841 9332fd8a Iustin Pop
  try:
842 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
843 5282084b Iustin Pop
  except OSError, err:
844 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
845 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
846 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
847 9332fd8a Iustin Pop
        os.remove(link_name)
848 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
849 9332fd8a Iustin Pop
    else:
850 9332fd8a Iustin Pop
      raise
851 9332fd8a Iustin Pop
852 9332fd8a Iustin Pop
  return link_name
853 9332fd8a Iustin Pop
854 9332fd8a Iustin Pop
855 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
856 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
857 3c9c571d Iustin Pop

858 3c9c571d Iustin Pop
  """
859 5282084b Iustin Pop
  for idx, disk in enumerate(disks):
860 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
861 5282084b Iustin Pop
    if os.path.islink(link_name):
862 3c9c571d Iustin Pop
      try:
863 03dfa658 Iustin Pop
        os.remove(link_name)
864 03dfa658 Iustin Pop
      except OSError:
865 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
866 3c9c571d Iustin Pop
867 3c9c571d Iustin Pop
868 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
869 a8083063 Iustin Pop
  """Set up an instance's block device(s).
870 a8083063 Iustin Pop

871 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
872 a8083063 Iustin Pop
  devices must be already assembled.
873 a8083063 Iustin Pop

874 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
875 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
876 069cfbf1 Iustin Pop
  @rtype: list
877 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
878 10c2650b Iustin Pop

879 a8083063 Iustin Pop
  """
880 a8083063 Iustin Pop
  block_devices = []
881 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
882 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
883 a8083063 Iustin Pop
    if device is None:
884 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
885 a8083063 Iustin Pop
                                    str(disk))
886 a8083063 Iustin Pop
    device.Open()
887 9332fd8a Iustin Pop
    try:
888 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
889 9332fd8a Iustin Pop
    except OSError, e:
890 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
891 9332fd8a Iustin Pop
                                    e.strerror)
892 9332fd8a Iustin Pop
893 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
894 9332fd8a Iustin Pop
895 a8083063 Iustin Pop
  return block_devices
896 a8083063 Iustin Pop
897 a8083063 Iustin Pop
898 07813a9e Iustin Pop
def StartInstance(instance):
899 a8083063 Iustin Pop
  """Start an instance.
900 a8083063 Iustin Pop

901 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
902 e69d05fd Iustin Pop
  @param instance: the instance object
903 e69d05fd Iustin Pop
  @rtype: boolean
904 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
905 a8083063 Iustin Pop

906 098c0958 Michael Hanselmann
  """
907 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
908 a8083063 Iustin Pop
909 a8083063 Iustin Pop
  if instance.name in running_instances:
910 dd279568 Iustin Pop
    return (True, "Already running")
911 a8083063 Iustin Pop
912 a8083063 Iustin Pop
  try:
913 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
914 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
915 07813a9e Iustin Pop
    hyper.StartInstance(instance, block_devices)
916 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
917 ec596c24 Iustin Pop
    logging.exception("Failed to start instance")
918 dd279568 Iustin Pop
    return (False, "Block device error: %s" % str(err))
919 a8083063 Iustin Pop
  except errors.HypervisorError, err:
920 18682bca Iustin Pop
    logging.exception("Failed to start instance")
921 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
922 dd279568 Iustin Pop
    return (False, "Hypervisor error: %s" % str(err))
923 a8083063 Iustin Pop
924 dd279568 Iustin Pop
  return (True, "Instance started successfully")
925 a8083063 Iustin Pop
926 a8083063 Iustin Pop
927 1fae010f Iustin Pop
def InstanceShutdown(instance):
928 a8083063 Iustin Pop
  """Shut an instance down.
929 a8083063 Iustin Pop

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

932 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
933 e69d05fd Iustin Pop
  @param instance: the instance object
934 e69d05fd Iustin Pop
  @rtype: boolean
935 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
936 a8083063 Iustin Pop

937 098c0958 Michael Hanselmann
  """
938 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
939 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
940 a8083063 Iustin Pop
941 a8083063 Iustin Pop
  if instance.name not in running_instances:
942 1fae010f Iustin Pop
    return (True, "Instance already stopped")
943 a8083063 Iustin Pop
944 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
945 a8083063 Iustin Pop
  try:
946 a8083063 Iustin Pop
    hyper.StopInstance(instance)
947 a8083063 Iustin Pop
  except errors.HypervisorError, err:
948 1fae010f Iustin Pop
    msg = "Failed to stop instance %s: %s" % (instance.name, err)
949 1fae010f Iustin Pop
    logging.error(msg)
950 1fae010f Iustin Pop
    return (False, msg)
951 a8083063 Iustin Pop
952 a8083063 Iustin Pop
  # test every 10secs for 2min
953 a8083063 Iustin Pop
954 a8083063 Iustin Pop
  time.sleep(1)
955 7c4d6c7b Michael Hanselmann
  for _ in range(11):
956 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
957 a8083063 Iustin Pop
      break
958 a8083063 Iustin Pop
    time.sleep(10)
959 a8083063 Iustin Pop
  else:
960 a8083063 Iustin Pop
    # the shutdown did not succeed
961 ca77edbc Guido Trotter
    logging.error("Shutdown of '%s' unsuccessful, using destroy",
962 ca77edbc Guido Trotter
                  instance.name)
963 a8083063 Iustin Pop
964 a8083063 Iustin Pop
    try:
965 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
966 a8083063 Iustin Pop
    except errors.HypervisorError, err:
967 1fae010f Iustin Pop
      msg = "Failed to force stop instance %s: %s" % (instance.name, err)
968 1fae010f Iustin Pop
      logging.error(msg)
969 1fae010f Iustin Pop
      return (False, msg)
970 a8083063 Iustin Pop
971 a8083063 Iustin Pop
    time.sleep(1)
972 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
973 1fae010f Iustin Pop
      msg = ("Could not shutdown instance %s even by destroy" %
974 1fae010f Iustin Pop
             instance.name)
975 1fae010f Iustin Pop
      logging.error(msg)
976 1fae010f Iustin Pop
      return (False, msg)
977 a8083063 Iustin Pop
978 5282084b Iustin Pop
  _RemoveBlockDevLinks(instance.name, instance.disks)
979 3c9c571d Iustin Pop
980 1fae010f Iustin Pop
  return (True, "Instance has been shutdown successfully")
981 a8083063 Iustin Pop
982 a8083063 Iustin Pop
983 07813a9e Iustin Pop
def InstanceReboot(instance, reboot_type):
984 007a2f3e Alexander Schreiber
  """Reboot an instance.
985 007a2f3e Alexander Schreiber

986 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
987 10c2650b Iustin Pop
  @param instance: the instance object to reboot
988 10c2650b Iustin Pop
  @type reboot_type: str
989 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
990 10c2650b Iustin Pop
    constants:
991 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
992 10c2650b Iustin Pop
        instance OS, do not recreate the VM
993 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
994 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
995 73e5a4f4 Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
996 73e5a4f4 Iustin Pop
        not accepted here, since that mode is handled differently, in
997 73e5a4f4 Iustin Pop
        cmdlib, and translates into full stop and start of the
998 73e5a4f4 Iustin Pop
        instance (instead of a call_instance_reboot RPC)
999 10c2650b Iustin Pop
  @rtype: boolean
1000 10c2650b Iustin Pop
  @return: the success of the operation
1001 007a2f3e Alexander Schreiber

1002 007a2f3e Alexander Schreiber
  """
1003 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
1004 007a2f3e Alexander Schreiber
1005 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
1006 489fcbe9 Iustin Pop
    msg = "Cannot reboot instance %s that is not running" % instance.name
1007 489fcbe9 Iustin Pop
    logging.error(msg)
1008 489fcbe9 Iustin Pop
    return (False, msg)
1009 007a2f3e Alexander Schreiber
1010 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1011 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1012 007a2f3e Alexander Schreiber
    try:
1013 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
1014 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1015 489fcbe9 Iustin Pop
      msg = "Failed to soft reboot instance %s: %s" % (instance.name, err)
1016 489fcbe9 Iustin Pop
      logging.error(msg)
1017 489fcbe9 Iustin Pop
      return (False, msg)
1018 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1019 007a2f3e Alexander Schreiber
    try:
1020 ae48ac32 Iustin Pop
      stop_result = InstanceShutdown(instance)
1021 ae48ac32 Iustin Pop
      if not stop_result[0]:
1022 ae48ac32 Iustin Pop
        return stop_result
1023 07813a9e Iustin Pop
      return StartInstance(instance)
1024 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
1025 489fcbe9 Iustin Pop
      msg = "Failed to hard reboot instance %s: %s" % (instance.name, err)
1026 489fcbe9 Iustin Pop
      logging.error(msg)
1027 489fcbe9 Iustin Pop
      return (False, msg)
1028 007a2f3e Alexander Schreiber
  else:
1029 489fcbe9 Iustin Pop
    return (False, "Invalid reboot_type received: %s" % (reboot_type,))
1030 007a2f3e Alexander Schreiber
1031 489fcbe9 Iustin Pop
  return (True, "Reboot successful")
1032 007a2f3e Alexander Schreiber
1033 007a2f3e Alexander Schreiber
1034 6906a9d8 Guido Trotter
def MigrationInfo(instance):
1035 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
1036 6906a9d8 Guido Trotter

1037 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1038 6906a9d8 Guido Trotter
  @param instance: the instance definition
1039 6906a9d8 Guido Trotter

1040 6906a9d8 Guido Trotter
  """
1041 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1042 cd42d0ad Guido Trotter
  try:
1043 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
1044 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1045 cd42d0ad Guido Trotter
    msg = "Failed to fetch migration information"
1046 cd42d0ad Guido Trotter
    logging.exception(msg)
1047 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1048 cd42d0ad Guido Trotter
  return (True, info)
1049 6906a9d8 Guido Trotter
1050 6906a9d8 Guido Trotter
1051 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
1052 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
1053 6906a9d8 Guido Trotter

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

1061 6906a9d8 Guido Trotter
  """
1062 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1063 cd42d0ad Guido Trotter
  try:
1064 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1065 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1066 cd42d0ad Guido Trotter
    msg = "Failed to accept instance"
1067 cd42d0ad Guido Trotter
    logging.exception(msg)
1068 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1069 5bbd3f7f Michael Hanselmann
  return (True, "Accept successful")
1070 6906a9d8 Guido Trotter
1071 6906a9d8 Guido Trotter
1072 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1073 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1074 6906a9d8 Guido Trotter

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

1082 6906a9d8 Guido Trotter
  """
1083 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1084 cd42d0ad Guido Trotter
  try:
1085 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1086 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1087 cd42d0ad Guido Trotter
    msg = "Failed to finalize migration"
1088 cd42d0ad Guido Trotter
    logging.exception(msg)
1089 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1090 6906a9d8 Guido Trotter
  return (True, "Migration Finalized")
1091 6906a9d8 Guido Trotter
1092 6906a9d8 Guido Trotter
1093 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1094 2a10865c Iustin Pop
  """Migrates an instance to another node.
1095 2a10865c Iustin Pop

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

1108 2a10865c Iustin Pop
  """
1109 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1110 2a10865c Iustin Pop
1111 2a10865c Iustin Pop
  try:
1112 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
1113 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1114 53c776b5 Iustin Pop
    msg = "Failed to migrate instance"
1115 53c776b5 Iustin Pop
    logging.exception(msg)
1116 53c776b5 Iustin Pop
    return (False, "%s: %s" % (msg, err))
1117 5bbd3f7f Michael Hanselmann
  return (True, "Migration successful")
1118 2a10865c Iustin Pop
1119 2a10865c Iustin Pop
1120 821d1bd1 Iustin Pop
def BlockdevCreate(disk, size, owner, on_primary, info):
1121 a8083063 Iustin Pop
  """Creates a block device for an instance.
1122 a8083063 Iustin Pop

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

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

1140 a8083063 Iustin Pop
  """
1141 a8083063 Iustin Pop
  clist = []
1142 a8083063 Iustin Pop
  if disk.children:
1143 a8083063 Iustin Pop
    for child in disk.children:
1144 1063abd1 Iustin Pop
      try:
1145 1063abd1 Iustin Pop
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1146 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1147 1063abd1 Iustin Pop
        errmsg = "Can't assemble device %s: %s" % (child, err)
1148 1063abd1 Iustin Pop
        logging.error(errmsg)
1149 1063abd1 Iustin Pop
        return False, errmsg
1150 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1151 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1152 a8083063 Iustin Pop
        # be assembled
1153 1063abd1 Iustin Pop
        try:
1154 fe267188 Iustin Pop
          # pylint: disable-msg=E1103
1155 1063abd1 Iustin Pop
          crdev.Open()
1156 1063abd1 Iustin Pop
        except errors.BlockDeviceError, err:
1157 33bc6f01 Iustin Pop
          errmsg = "Can't make child '%s' read-write: %s" % (child, err)
1158 1063abd1 Iustin Pop
          logging.error(errmsg)
1159 1063abd1 Iustin Pop
          return False, errmsg
1160 a8083063 Iustin Pop
      clist.append(crdev)
1161 a8083063 Iustin Pop
1162 dab69e97 Iustin Pop
  try:
1163 464f8daf Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1164 1063abd1 Iustin Pop
  except errors.BlockDeviceError, err:
1165 dab69e97 Iustin Pop
    return False, "Can't create block device: %s" % str(err)
1166 6c626518 Iustin Pop
1167 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1168 1063abd1 Iustin Pop
    try:
1169 1063abd1 Iustin Pop
      device.Assemble()
1170 1063abd1 Iustin Pop
    except errors.BlockDeviceError, err:
1171 1063abd1 Iustin Pop
      errmsg = ("Can't assemble device after creation, very"
1172 1063abd1 Iustin Pop
                " unusual event: %s" % str(err))
1173 1063abd1 Iustin Pop
      logging.error(errmsg)
1174 1063abd1 Iustin Pop
      return False, errmsg
1175 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1176 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1177 1063abd1 Iustin Pop
      try:
1178 1063abd1 Iustin Pop
        device.Open(force=True)
1179 1063abd1 Iustin Pop
      except errors.BlockDeviceError, err:
1180 1063abd1 Iustin Pop
        errmsg = ("Can't make device r/w after creation, very"
1181 1063abd1 Iustin Pop
                  " unusual event: %s" % str(err))
1182 1063abd1 Iustin Pop
        logging.error(errmsg)
1183 1063abd1 Iustin Pop
        return False, errmsg
1184 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1185 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1186 a0c3fea1 Michael Hanselmann
1187 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1188 a0c3fea1 Michael Hanselmann
1189 a8083063 Iustin Pop
  physical_id = device.unique_id
1190 dab69e97 Iustin Pop
  return True, physical_id
1191 a8083063 Iustin Pop
1192 a8083063 Iustin Pop
1193 821d1bd1 Iustin Pop
def BlockdevRemove(disk):
1194 a8083063 Iustin Pop
  """Remove a block device.
1195 a8083063 Iustin Pop

1196 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1197 10c2650b Iustin Pop

1198 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1199 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1200 10c2650b Iustin Pop
  @rtype: boolean
1201 10c2650b Iustin Pop
  @return: the success of the operation
1202 a8083063 Iustin Pop

1203 a8083063 Iustin Pop
  """
1204 e1bc0878 Iustin Pop
  msgs = []
1205 e1bc0878 Iustin Pop
  result = True
1206 a8083063 Iustin Pop
  try:
1207 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1208 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1209 a8083063 Iustin Pop
    # probably can't attach
1210 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1211 a8083063 Iustin Pop
    rdev = None
1212 a8083063 Iustin Pop
  if rdev is not None:
1213 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1214 e1bc0878 Iustin Pop
    try:
1215 0c6c04ec Iustin Pop
      rdev.Remove()
1216 e1bc0878 Iustin Pop
    except errors.BlockDeviceError, err:
1217 e1bc0878 Iustin Pop
      msgs.append(str(err))
1218 e1bc0878 Iustin Pop
      result = False
1219 3f78eef2 Iustin Pop
    if result:
1220 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1221 e1bc0878 Iustin Pop
1222 a8083063 Iustin Pop
  if disk.children:
1223 a8083063 Iustin Pop
    for child in disk.children:
1224 e1bc0878 Iustin Pop
      c_status, c_msg = BlockdevRemove(child)
1225 e1bc0878 Iustin Pop
      result = result and c_status
1226 e1bc0878 Iustin Pop
      if c_msg: # not an empty message
1227 e1bc0878 Iustin Pop
        msgs.append(c_msg)
1228 e1bc0878 Iustin Pop
1229 e1bc0878 Iustin Pop
  return (result, "; ".join(msgs))
1230 a8083063 Iustin Pop
1231 a8083063 Iustin Pop
1232 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1233 a8083063 Iustin Pop
  """Activate a block device for an instance.
1234 a8083063 Iustin Pop

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

1237 10c2650b Iustin Pop
  @note: this function is called recursively.
1238 a8083063 Iustin Pop

1239 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1240 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1241 10c2650b Iustin Pop
  @type owner: str
1242 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1243 10c2650b Iustin Pop
  @type as_primary: boolean
1244 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1245 10c2650b Iustin Pop
      read/write
1246 a8083063 Iustin Pop

1247 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1248 10c2650b Iustin Pop
      was assembled)
1249 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1250 10c2650b Iustin Pop
      during the activation of the children or the device
1251 10c2650b Iustin Pop
      itself
1252 a8083063 Iustin Pop

1253 a8083063 Iustin Pop
  """
1254 a8083063 Iustin Pop
  children = []
1255 a8083063 Iustin Pop
  if disk.children:
1256 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1257 fc1dc9d7 Iustin Pop
    if mcn == -1:
1258 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1259 fc1dc9d7 Iustin Pop
    else:
1260 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1261 a8083063 Iustin Pop
    for chld_disk in disk.children:
1262 fc1dc9d7 Iustin Pop
      try:
1263 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1264 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1265 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1266 fc1dc9d7 Iustin Pop
          raise
1267 fc1dc9d7 Iustin Pop
        cdev = None
1268 1063abd1 Iustin Pop
        logging.error("Error in child activation (but continuing): %s",
1269 1063abd1 Iustin Pop
                      str(err))
1270 fc1dc9d7 Iustin Pop
      children.append(cdev)
1271 a8083063 Iustin Pop
1272 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1273 464f8daf Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1274 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1275 a8083063 Iustin Pop
    result = r_dev
1276 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1277 a8083063 Iustin Pop
      r_dev.Open()
1278 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1279 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1280 3f78eef2 Iustin Pop
1281 a8083063 Iustin Pop
  else:
1282 a8083063 Iustin Pop
    result = True
1283 a8083063 Iustin Pop
  return result
1284 a8083063 Iustin Pop
1285 a8083063 Iustin Pop
1286 821d1bd1 Iustin Pop
def BlockdevAssemble(disk, owner, as_primary):
1287 a8083063 Iustin Pop
  """Activate a block device for an instance.
1288 a8083063 Iustin Pop

1289 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1290 a8083063 Iustin Pop

1291 b1206984 Iustin Pop
  @rtype: str or boolean
1292 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1293 b1206984 Iustin Pop
      C{True} for secondary nodes
1294 a8083063 Iustin Pop

1295 a8083063 Iustin Pop
  """
1296 1063abd1 Iustin Pop
  status = True
1297 53c14ef1 Iustin Pop
  result = "no error information"
1298 53c14ef1 Iustin Pop
  try:
1299 53c14ef1 Iustin Pop
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1300 53c14ef1 Iustin Pop
    if isinstance(result, bdev.BlockDev):
1301 fe267188 Iustin Pop
      # pylint: disable-msg=E1103
1302 53c14ef1 Iustin Pop
      result = result.dev_path
1303 53c14ef1 Iustin Pop
  except errors.BlockDeviceError, err:
1304 53c14ef1 Iustin Pop
    result = "Error while assembling disk: %s" % str(err)
1305 1063abd1 Iustin Pop
    status = False
1306 53c14ef1 Iustin Pop
  return (status, result)
1307 a8083063 Iustin Pop
1308 a8083063 Iustin Pop
1309 821d1bd1 Iustin Pop
def BlockdevShutdown(disk):
1310 a8083063 Iustin Pop
  """Shut down a block device.
1311 a8083063 Iustin Pop

1312 5bbd3f7f Michael Hanselmann
  First, if the device is assembled (Attach() is successful), then
1313 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1314 c41eea6e Iustin Pop
  shutdown.
1315 a8083063 Iustin Pop

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

1320 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1321 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1322 10c2650b Iustin Pop
      shutdown
1323 10c2650b Iustin Pop
  @rtype: boolean
1324 10c2650b Iustin Pop
  @return: the success of the operation
1325 10c2650b Iustin Pop

1326 a8083063 Iustin Pop
  """
1327 cacfd1fd Iustin Pop
  msgs = []
1328 746f7476 Iustin Pop
  result = True
1329 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1330 a8083063 Iustin Pop
  if r_dev is not None:
1331 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1332 cacfd1fd Iustin Pop
    try:
1333 746f7476 Iustin Pop
      r_dev.Shutdown()
1334 746f7476 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1335 cacfd1fd Iustin Pop
    except errors.BlockDeviceError, err:
1336 cacfd1fd Iustin Pop
      msgs.append(str(err))
1337 cacfd1fd Iustin Pop
      result = False
1338 746f7476 Iustin Pop
1339 a8083063 Iustin Pop
  if disk.children:
1340 a8083063 Iustin Pop
    for child in disk.children:
1341 cacfd1fd Iustin Pop
      c_status, c_msg = BlockdevShutdown(child)
1342 cacfd1fd Iustin Pop
      result = result and c_status
1343 cacfd1fd Iustin Pop
      if c_msg: # not an empty message
1344 cacfd1fd Iustin Pop
        msgs.append(c_msg)
1345 746f7476 Iustin Pop
1346 cacfd1fd Iustin Pop
  return (result, "; ".join(msgs))
1347 a8083063 Iustin Pop
1348 a8083063 Iustin Pop
1349 821d1bd1 Iustin Pop
def BlockdevAddchildren(parent_cdev, new_cdevs):
1350 153d9724 Iustin Pop
  """Extend 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 to which we should add 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 add
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 bca2e7f4 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 device")
1363 a8083063 Iustin Pop
    return False
1364 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1365 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1366 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
1367 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
1368 a8083063 Iustin Pop
    return False
1369 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1370 a8083063 Iustin Pop
  return True
1371 a8083063 Iustin Pop
1372 a8083063 Iustin Pop
1373 821d1bd1 Iustin Pop
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1374 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1375 a8083063 Iustin Pop

1376 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1377 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1378 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1379 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1380 10c2650b Iustin Pop
  @rtype: boolean
1381 10c2650b Iustin Pop
  @return: the success of the operation
1382 10c2650b Iustin Pop

1383 a8083063 Iustin Pop
  """
1384 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1385 153d9724 Iustin Pop
  if parent_bdev is None:
1386 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
1387 a8083063 Iustin Pop
    return False
1388 e739bd57 Iustin Pop
  devs = []
1389 e739bd57 Iustin Pop
  for disk in new_cdevs:
1390 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1391 e739bd57 Iustin Pop
    if rpath is None:
1392 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1393 e739bd57 Iustin Pop
      if bd is None:
1394 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
1395 18682bca Iustin Pop
                      disk)
1396 e739bd57 Iustin Pop
        return False
1397 e739bd57 Iustin Pop
      else:
1398 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1399 e739bd57 Iustin Pop
    else:
1400 e739bd57 Iustin Pop
      devs.append(rpath)
1401 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1402 a8083063 Iustin Pop
  return True
1403 a8083063 Iustin Pop
1404 a8083063 Iustin Pop
1405 821d1bd1 Iustin Pop
def BlockdevGetmirrorstatus(disks):
1406 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1407 a8083063 Iustin Pop

1408 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1409 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1410 10c2650b Iustin Pop
  @rtype: disk
1411 10c2650b Iustin Pop
  @return:
1412 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1413 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1414 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1415 10c2650b Iustin Pop
      found
1416 a8083063 Iustin Pop

1417 a8083063 Iustin Pop
  """
1418 a8083063 Iustin Pop
  stats = []
1419 a8083063 Iustin Pop
  for dsk in disks:
1420 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1421 a8083063 Iustin Pop
    if rbd is None:
1422 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
1423 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1424 a8083063 Iustin Pop
  return stats
1425 a8083063 Iustin Pop
1426 a8083063 Iustin Pop
1427 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1428 a8083063 Iustin Pop
  """Check if a device is activated.
1429 a8083063 Iustin Pop

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

1432 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1433 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1434 a8083063 Iustin Pop

1435 10c2650b Iustin Pop
  @return: None if the device can't be found,
1436 10c2650b Iustin Pop
      otherwise the device instance
1437 a8083063 Iustin Pop

1438 a8083063 Iustin Pop
  """
1439 a8083063 Iustin Pop
  children = []
1440 a8083063 Iustin Pop
  if disk.children:
1441 a8083063 Iustin Pop
    for chdisk in disk.children:
1442 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1443 a8083063 Iustin Pop
1444 464f8daf Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1445 a8083063 Iustin Pop
1446 a8083063 Iustin Pop
1447 821d1bd1 Iustin Pop
def BlockdevFind(disk):
1448 a8083063 Iustin Pop
  """Check if a device is activated.
1449 a8083063 Iustin Pop

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

1452 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1453 10c2650b Iustin Pop
  @param disk: the disk to find
1454 10c2650b Iustin Pop
  @rtype: None or tuple
1455 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1456 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1457 10c2650b Iustin Pop
      estimated_time, is_degraded)
1458 a8083063 Iustin Pop

1459 a8083063 Iustin Pop
  """
1460 23829f6f Iustin Pop
  try:
1461 23829f6f Iustin Pop
    rbd = _RecursiveFindBD(disk)
1462 23829f6f Iustin Pop
  except errors.BlockDeviceError, err:
1463 23829f6f Iustin Pop
    return (False, str(err))
1464 a8083063 Iustin Pop
  if rbd is None:
1465 23829f6f Iustin Pop
    return (True, None)
1466 23829f6f Iustin Pop
  return (True, (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus())
1467 a8083063 Iustin Pop
1468 a8083063 Iustin Pop
1469 968a7623 Iustin Pop
def BlockdevGetsize(disks):
1470 968a7623 Iustin Pop
  """Computes the size of the given disks.
1471 968a7623 Iustin Pop

1472 968a7623 Iustin Pop
  If a disk is not found, returns None instead.
1473 968a7623 Iustin Pop

1474 968a7623 Iustin Pop
  @type disks: list of L{objects.Disk}
1475 968a7623 Iustin Pop
  @param disks: the list of disk to compute the size for
1476 968a7623 Iustin Pop
  @rtype: list
1477 968a7623 Iustin Pop
  @return: list with elements None if the disk cannot be found,
1478 968a7623 Iustin Pop
      otherwise the size
1479 968a7623 Iustin Pop

1480 968a7623 Iustin Pop
  """
1481 968a7623 Iustin Pop
  result = []
1482 968a7623 Iustin Pop
  for cf in disks:
1483 968a7623 Iustin Pop
    try:
1484 968a7623 Iustin Pop
      rbd = _RecursiveFindBD(cf)
1485 968a7623 Iustin Pop
    except errors.BlockDeviceError, err:
1486 968a7623 Iustin Pop
      result.append(None)
1487 968a7623 Iustin Pop
      continue
1488 968a7623 Iustin Pop
    if rbd is None:
1489 968a7623 Iustin Pop
      result.append(None)
1490 968a7623 Iustin Pop
    else:
1491 968a7623 Iustin Pop
      result.append(rbd.GetActualSize())
1492 968a7623 Iustin Pop
  return result
1493 968a7623 Iustin Pop
1494 968a7623 Iustin Pop
1495 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1496 a8083063 Iustin Pop
  """Write a file to the filesystem.
1497 a8083063 Iustin Pop

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

1501 10c2650b Iustin Pop
  @type file_name: str
1502 10c2650b Iustin Pop
  @param file_name: the target file name
1503 10c2650b Iustin Pop
  @type data: str
1504 10c2650b Iustin Pop
  @param data: the new contents of the file
1505 10c2650b Iustin Pop
  @type mode: int
1506 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1507 10c2650b Iustin Pop
  @type uid: int
1508 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1509 10c2650b Iustin Pop
  @type gid: int
1510 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1511 10c2650b Iustin Pop
  @type atime: float
1512 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1513 10c2650b Iustin Pop
  @type mtime: float
1514 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1515 10c2650b Iustin Pop
  @rtype: boolean
1516 10c2650b Iustin Pop
  @return: the success of the operation; errors are logged
1517 10c2650b Iustin Pop
      in the node daemon log
1518 10c2650b Iustin Pop

1519 a8083063 Iustin Pop
  """
1520 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1521 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
1522 18682bca Iustin Pop
                  file_name)
1523 a8083063 Iustin Pop
    return False
1524 a8083063 Iustin Pop
1525 360b0dc2 Iustin Pop
  if file_name not in _ALLOWED_UPLOAD_FILES:
1526 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
1527 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
1528 a8083063 Iustin Pop
    return False
1529 a8083063 Iustin Pop
1530 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1531 12bce260 Michael Hanselmann
1532 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1533 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1534 a8083063 Iustin Pop
  return True
1535 a8083063 Iustin Pop
1536 386b57af Iustin Pop
1537 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1538 89b14f05 Iustin Pop
  """Update all ssconf files.
1539 89b14f05 Iustin Pop

1540 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1541 89b14f05 Iustin Pop

1542 89b14f05 Iustin Pop
  """
1543 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1544 6ddc95ec Michael Hanselmann
1545 6ddc95ec Michael Hanselmann
1546 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1547 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1548 a8083063 Iustin Pop

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

1553 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1554 10c2650b Iustin Pop
  @param err: the exception to format
1555 a8083063 Iustin Pop

1556 a8083063 Iustin Pop
  """
1557 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1558 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1559 a8083063 Iustin Pop
  else:
1560 a8083063 Iustin Pop
    detail = str(err)
1561 a8083063 Iustin Pop
  return detail
1562 a8083063 Iustin Pop
1563 5d0fe286 Iustin Pop
1564 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1565 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1566 a8083063 Iustin Pop

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

1570 10c2650b Iustin Pop
  @type name: str
1571 10c2650b Iustin Pop
  @param name: the OS name we should look for
1572 10c2650b Iustin Pop
  @type os_dir: str
1573 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1574 10c2650b Iustin Pop
  @rtype: int or None
1575 10c2650b Iustin Pop
  @return:
1576 10c2650b Iustin Pop
      Either an integer denoting the version or None in the
1577 10c2650b Iustin Pop
      case when this is not a valid OS name.
1578 10c2650b Iustin Pop
  @raise errors.InvalidOS: if the OS cannot be found
1579 a8083063 Iustin Pop

1580 a8083063 Iustin Pop
  """
1581 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1582 a8083063 Iustin Pop
1583 a8083063 Iustin Pop
  try:
1584 a8083063 Iustin Pop
    st = os.stat(api_file)
1585 a8083063 Iustin Pop
  except EnvironmentError, err:
1586 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1587 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1588 a8083063 Iustin Pop
1589 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1590 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1591 3ecf6786 Iustin Pop
                           " a regular file")
1592 a8083063 Iustin Pop
1593 a8083063 Iustin Pop
  try:
1594 a8083063 Iustin Pop
    f = open(api_file)
1595 a8083063 Iustin Pop
    try:
1596 082a7f91 Guido Trotter
      api_versions = f.readlines()
1597 a8083063 Iustin Pop
    finally:
1598 a8083063 Iustin Pop
      f.close()
1599 a8083063 Iustin Pop
  except EnvironmentError, err:
1600 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1601 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1602 a8083063 Iustin Pop
1603 082a7f91 Guido Trotter
  api_versions = [version.strip() for version in api_versions]
1604 a8083063 Iustin Pop
  try:
1605 082a7f91 Guido Trotter
    api_versions = [int(version) for version in api_versions]
1606 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1607 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1608 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1609 a8083063 Iustin Pop
1610 082a7f91 Guido Trotter
  return api_versions
1611 a8083063 Iustin Pop
1612 386b57af Iustin Pop
1613 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1614 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1615 a8083063 Iustin Pop

1616 10c2650b Iustin Pop
  @type top_dirs: list
1617 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1618 10c2650b Iustin Pop
      search (if not given defaults to
1619 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1620 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1621 10c2650b Iustin Pop
  @return: an OS object for each name in all the given
1622 10c2650b Iustin Pop
      directories
1623 a8083063 Iustin Pop

1624 a8083063 Iustin Pop
  """
1625 7c3d51d4 Guido Trotter
  if top_dirs is None:
1626 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1627 a8083063 Iustin Pop
1628 a8083063 Iustin Pop
  result = []
1629 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1630 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1631 7c3d51d4 Guido Trotter
      try:
1632 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1633 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1634 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1635 7c3d51d4 Guido Trotter
        break
1636 7c3d51d4 Guido Trotter
      for name in f_names:
1637 7c3d51d4 Guido Trotter
        try:
1638 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1639 7c3d51d4 Guido Trotter
          result.append(os_inst)
1640 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1641 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1642 a8083063 Iustin Pop
1643 a8083063 Iustin Pop
  return result
1644 a8083063 Iustin Pop
1645 a8083063 Iustin Pop
1646 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1647 a8083063 Iustin Pop
  """Create an OS instance from disk.
1648 a8083063 Iustin Pop

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

1653 8ee4dc80 Guido Trotter
  @type base_dir: string
1654 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1655 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1656 10c2650b Iustin Pop
  @rtype: L{objects.OS}
1657 10c2650b Iustin Pop
  @return: the OS instance if we find a valid one
1658 10c2650b Iustin Pop
  @raise errors.InvalidOS: if we don't find a valid OS
1659 7c3d51d4 Guido Trotter

1660 a8083063 Iustin Pop
  """
1661 56bcd3f4 Guido Trotter
  if base_dir is None:
1662 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1663 c34c0cfd Iustin Pop
  else:
1664 f95c81bf Iustin Pop
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1665 f95c81bf Iustin Pop
1666 f95c81bf Iustin Pop
  if os_dir is None:
1667 f95c81bf Iustin Pop
    raise errors.InvalidOS(name, None, "OS dir not found in search path")
1668 a8083063 Iustin Pop
1669 082a7f91 Guido Trotter
  api_versions = _OSOndiskVersion(name, os_dir)
1670 a8083063 Iustin Pop
1671 082a7f91 Guido Trotter
  if constants.OS_API_VERSION not in api_versions:
1672 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1673 305a7297 Guido Trotter
                           " (found %s want %s)"
1674 082a7f91 Guido Trotter
                           % (api_versions, constants.OS_API_VERSION))
1675 a8083063 Iustin Pop
1676 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1677 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1678 a8083063 Iustin Pop
1679 a8083063 Iustin Pop
  for script in os_scripts:
1680 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1681 a8083063 Iustin Pop
1682 a8083063 Iustin Pop
    try:
1683 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1684 a8083063 Iustin Pop
    except EnvironmentError, err:
1685 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1686 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1687 a8083063 Iustin Pop
1688 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1689 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1690 305a7297 Guido Trotter
                             script)
1691 a8083063 Iustin Pop
1692 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1693 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1694 305a7297 Guido Trotter
                             script)
1695 a8083063 Iustin Pop
1696 a8083063 Iustin Pop
1697 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1698 62dbbe7e Guido Trotter
                    create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1699 62dbbe7e Guido Trotter
                    export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1700 62dbbe7e Guido Trotter
                    import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1701 62dbbe7e Guido Trotter
                    rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1702 082a7f91 Guido Trotter
                    api_versions=api_versions)
1703 a8083063 Iustin Pop
1704 2266edb2 Guido Trotter
def OSEnvironment(instance, debug=0):
1705 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1706 2266edb2 Guido Trotter

1707 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1708 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1709 2266edb2 Guido Trotter
  @type debug: integer
1710 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1711 2266edb2 Guido Trotter
  @rtype: dict
1712 2266edb2 Guido Trotter
  @return: dict of environment variables
1713 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1714 10c2650b Iustin Pop
      cannot be found
1715 2266edb2 Guido Trotter

1716 2266edb2 Guido Trotter
  """
1717 2266edb2 Guido Trotter
  result = {}
1718 2266edb2 Guido Trotter
  result['OS_API_VERSION'] = '%d' % constants.OS_API_VERSION
1719 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1720 15552312 Iustin Pop
  result['INSTANCE_OS'] = instance.os
1721 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1722 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1723 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1724 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1725 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1726 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1727 2266edb2 Guido Trotter
    if real_disk is None:
1728 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1729 2266edb2 Guido Trotter
                                    str(disk))
1730 2266edb2 Guido Trotter
    real_disk.Open()
1731 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1732 15552312 Iustin Pop
    result['DISK_%d_ACCESS' % idx] = disk.mode
1733 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1734 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1735 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1736 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1737 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1738 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1739 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1740 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1741 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1742 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1743 2266edb2 Guido Trotter
    if nic.ip:
1744 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1745 2266edb2 Guido Trotter
    result['NIC_%d_BRIDGE' % idx] = nic.bridge
1746 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1747 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1748 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1749 2266edb2 Guido Trotter
1750 67fc3042 Iustin Pop
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1751 67fc3042 Iustin Pop
    for key, value in source.items():
1752 030b218a Iustin Pop
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1753 67fc3042 Iustin Pop
1754 2266edb2 Guido Trotter
  return result
1755 a8083063 Iustin Pop
1756 821d1bd1 Iustin Pop
def BlockdevGrow(disk, amount):
1757 594609c0 Iustin Pop
  """Grow a stack of block devices.
1758 594609c0 Iustin Pop

1759 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1760 10c2650b Iustin Pop
  first ones to resize.
1761 594609c0 Iustin Pop

1762 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1763 10c2650b Iustin Pop
  @param disk: the disk to be grown
1764 10c2650b Iustin Pop
  @rtype: (status, result)
1765 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1766 10c2650b Iustin Pop
      (True/False), and the errors message if status
1767 10c2650b Iustin Pop
      is False
1768 594609c0 Iustin Pop

1769 594609c0 Iustin Pop
  """
1770 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1771 594609c0 Iustin Pop
  if r_dev is None:
1772 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1773 594609c0 Iustin Pop
1774 594609c0 Iustin Pop
  try:
1775 594609c0 Iustin Pop
    r_dev.Grow(amount)
1776 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1777 594609c0 Iustin Pop
    return False, str(err)
1778 594609c0 Iustin Pop
1779 594609c0 Iustin Pop
  return True, None
1780 594609c0 Iustin Pop
1781 594609c0 Iustin Pop
1782 821d1bd1 Iustin Pop
def BlockdevSnapshot(disk):
1783 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1784 a8083063 Iustin Pop

1785 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1786 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1787 a8083063 Iustin Pop

1788 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1789 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1790 e9e9263d Guido Trotter
  @rtype: string
1791 e9e9263d Guido Trotter
  @return: snapshot disk path
1792 a8083063 Iustin Pop

1793 098c0958 Michael Hanselmann
  """
1794 a8083063 Iustin Pop
  if disk.children:
1795 a8083063 Iustin Pop
    if len(disk.children) == 1:
1796 a8083063 Iustin Pop
      # only one child, let's recurse on it
1797 821d1bd1 Iustin Pop
      return BlockdevSnapshot(disk.children[0])
1798 a8083063 Iustin Pop
    else:
1799 a8083063 Iustin Pop
      # more than one child, choose one that matches
1800 a8083063 Iustin Pop
      for child in disk.children:
1801 a8083063 Iustin Pop
        if child.size == disk.size:
1802 a8083063 Iustin Pop
          # return implies breaking the loop
1803 821d1bd1 Iustin Pop
          return BlockdevSnapshot(child)
1804 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1805 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1806 a8083063 Iustin Pop
    if r_dev is not None:
1807 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1808 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1809 a8083063 Iustin Pop
    else:
1810 a8083063 Iustin Pop
      return None
1811 a8083063 Iustin Pop
  else:
1812 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1813 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1814 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1815 a8083063 Iustin Pop
1816 a8083063 Iustin Pop
1817 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1818 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1819 a8083063 Iustin Pop

1820 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1821 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1822 74c47259 Iustin Pop
  @type dest_node: str
1823 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1824 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1825 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1826 74c47259 Iustin Pop
  @type cluster_name: str
1827 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1828 74c47259 Iustin Pop
  @type idx: int
1829 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1830 74c47259 Iustin Pop
      used to export to the OS scripts environment
1831 10c2650b Iustin Pop
  @rtype: boolean
1832 74c47259 Iustin Pop
  @return: the success of the operation
1833 a8083063 Iustin Pop

1834 098c0958 Michael Hanselmann
  """
1835 0607699d Guido Trotter
  export_env = OSEnvironment(instance)
1836 d324e3fc Guido Trotter
1837 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1838 a8083063 Iustin Pop
  export_script = inst_os.export_script
1839 a8083063 Iustin Pop
1840 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1841 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1842 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1843 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1844 0607699d Guido Trotter
  real_disk = _RecursiveFindBD(disk)
1845 0607699d Guido Trotter
  if real_disk is None:
1846 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1847 a8083063 Iustin Pop
                                  str(disk))
1848 0607699d Guido Trotter
  real_disk.Open()
1849 0607699d Guido Trotter
1850 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1851 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
1852 a8083063 Iustin Pop
1853 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1854 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1855 a8083063 Iustin Pop
1856 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1857 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1858 a8083063 Iustin Pop
  # valid parameters
1859 a48b08bf Iustin Pop
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
1860 a48b08bf Iustin Pop
                               inst_os.path, export_script, logfile)
1861 a8083063 Iustin Pop
1862 a8083063 Iustin Pop
  comprcmd = "gzip"
1863 a8083063 Iustin Pop
1864 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1865 00003458 Guido Trotter
                                destdir, destdir, destfile)
1866 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1867 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1868 62c9ec92 Iustin Pop
                                                   destcmd)
1869 a8083063 Iustin Pop
1870 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1871 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1872 a8083063 Iustin Pop
1873 a48b08bf Iustin Pop
  result = utils.RunCmd(["bash", "-c", command], env=export_env)
1874 a8083063 Iustin Pop
1875 a8083063 Iustin Pop
  if result.failed:
1876 18682bca Iustin Pop
    logging.error("os snapshot export command '%s' returned error: %s"
1877 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1878 a8083063 Iustin Pop
    return False
1879 a8083063 Iustin Pop
1880 a8083063 Iustin Pop
  return True
1881 a8083063 Iustin Pop
1882 a8083063 Iustin Pop
1883 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1884 a8083063 Iustin Pop
  """Write out the export configuration information.
1885 a8083063 Iustin Pop

1886 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1887 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
1888 10c2650b Iustin Pop
      saving configuration
1889 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
1890 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
1891 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
1892 a8083063 Iustin Pop

1893 10c2650b Iustin Pop
  @rtype: boolean
1894 10c2650b Iustin Pop
  @return: the success of the operation
1895 a8083063 Iustin Pop

1896 098c0958 Michael Hanselmann
  """
1897 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1898 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1899 a8083063 Iustin Pop
1900 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1901 a8083063 Iustin Pop
1902 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1903 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1904 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1905 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1906 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1907 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1908 a8083063 Iustin Pop
1909 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1910 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1911 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
1912 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
1913 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1914 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
1915 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1916 66f93869 Manuel Franceschini
1917 95268cc3 Iustin Pop
  nic_total = 0
1918 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1919 95268cc3 Iustin Pop
    nic_total += 1
1920 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1921 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1922 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1923 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1924 38206f3c Iustin Pop
               '%s' % nic.bridge)
1925 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1926 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1927 a8083063 Iustin Pop
1928 726d7d68 Iustin Pop
  disk_total = 0
1929 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1930 19d7f90a Guido Trotter
    if disk:
1931 726d7d68 Iustin Pop
      disk_total += 1
1932 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1933 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
1934 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1935 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
1936 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1937 19d7f90a Guido Trotter
                 ('%d' % disk.size))
1938 a8083063 Iustin Pop
1939 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1940 a8083063 Iustin Pop
1941 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1942 726d7d68 Iustin Pop
                  data=config.Dumps())
1943 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1944 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1945 a8083063 Iustin Pop
1946 a8083063 Iustin Pop
  return True
1947 a8083063 Iustin Pop
1948 a8083063 Iustin Pop
1949 a8083063 Iustin Pop
def ExportInfo(dest):
1950 a8083063 Iustin Pop
  """Get export configuration information.
1951 a8083063 Iustin Pop

1952 10c2650b Iustin Pop
  @type dest: str
1953 10c2650b Iustin Pop
  @param dest: directory containing the export
1954 a8083063 Iustin Pop

1955 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
1956 10c2650b Iustin Pop
  @return: a serializable config file containing the
1957 10c2650b Iustin Pop
      export info
1958 a8083063 Iustin Pop

1959 a8083063 Iustin Pop
  """
1960 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1961 a8083063 Iustin Pop
1962 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1963 a8083063 Iustin Pop
  config.read(cff)
1964 a8083063 Iustin Pop
1965 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1966 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1967 a8083063 Iustin Pop
    return None
1968 a8083063 Iustin Pop
1969 a8083063 Iustin Pop
  return config
1970 a8083063 Iustin Pop
1971 a8083063 Iustin Pop
1972 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1973 a8083063 Iustin Pop
  """Import an os image into an instance.
1974 a8083063 Iustin Pop

1975 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1976 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
1977 6c0af70e Guido Trotter
  @type src_node: string
1978 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
1979 6c0af70e Guido Trotter
  @type src_images: list of string
1980 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
1981 6c0af70e Guido Trotter
  @rtype: list of boolean
1982 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
1983 a8083063 Iustin Pop

1984 a8083063 Iustin Pop
  """
1985 6c0af70e Guido Trotter
  import_env = OSEnvironment(instance)
1986 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1987 a8083063 Iustin Pop
  import_script = inst_os.import_script
1988 a8083063 Iustin Pop
1989 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1990 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1991 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1992 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1993 a8083063 Iustin Pop
1994 a8083063 Iustin Pop
  comprcmd = "gunzip"
1995 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1996 d868edb4 Iustin Pop
                               import_script, logfile)
1997 a8083063 Iustin Pop
1998 6c0af70e Guido Trotter
  final_result = []
1999 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
2000 6c0af70e Guido Trotter
    if image:
2001 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
2002 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
2003 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
2004 6c0af70e Guido Trotter
                                                       destcmd)
2005 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
2006 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
2007 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
2008 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
2009 6c0af70e Guido Trotter
      if result.failed:
2010 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
2011 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
2012 726d7d68 Iustin Pop
                      result.output)
2013 6c0af70e Guido Trotter
        final_result.append(False)
2014 6c0af70e Guido Trotter
      else:
2015 6c0af70e Guido Trotter
        final_result.append(True)
2016 6c0af70e Guido Trotter
    else:
2017 6c0af70e Guido Trotter
      final_result.append(True)
2018 a8083063 Iustin Pop
2019 6c0af70e Guido Trotter
  return final_result
2020 a8083063 Iustin Pop
2021 a8083063 Iustin Pop
2022 a8083063 Iustin Pop
def ListExports():
2023 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
2024 098c0958 Michael Hanselmann

2025 10c2650b Iustin Pop
  @rtype: list
2026 10c2650b Iustin Pop
  @return: list of the exports
2027 10c2650b Iustin Pop

2028 a8083063 Iustin Pop
  """
2029 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
2030 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
2031 a8083063 Iustin Pop
  else:
2032 a8083063 Iustin Pop
    return []
2033 a8083063 Iustin Pop
2034 a8083063 Iustin Pop
2035 a8083063 Iustin Pop
def RemoveExport(export):
2036 a8083063 Iustin Pop
  """Remove an existing export from the node.
2037 a8083063 Iustin Pop

2038 10c2650b Iustin Pop
  @type export: str
2039 10c2650b Iustin Pop
  @param export: the name of the export to remove
2040 10c2650b Iustin Pop
  @rtype: boolean
2041 10c2650b Iustin Pop
  @return: the success of the operation
2042 a8083063 Iustin Pop

2043 098c0958 Michael Hanselmann
  """
2044 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
2045 a8083063 Iustin Pop
2046 a8083063 Iustin Pop
  shutil.rmtree(target)
2047 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
2048 a8083063 Iustin Pop
  # error message if rmtree fails.
2049 a8083063 Iustin Pop
2050 a8083063 Iustin Pop
  return True
2051 a8083063 Iustin Pop
2052 a8083063 Iustin Pop
2053 821d1bd1 Iustin Pop
def BlockdevRename(devlist):
2054 f3e513ad Iustin Pop
  """Rename a list of block devices.
2055 f3e513ad Iustin Pop

2056 10c2650b Iustin Pop
  @type devlist: list of tuples
2057 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
2058 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
2059 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
2060 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
2061 10c2650b Iustin Pop
      rename it to
2062 10c2650b Iustin Pop
  @rtype: boolean
2063 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
2064 f3e513ad Iustin Pop

2065 f3e513ad Iustin Pop
  """
2066 f3e513ad Iustin Pop
  result = True
2067 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
2068 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
2069 f3e513ad Iustin Pop
    if dev is None:
2070 f3e513ad Iustin Pop
      result = False
2071 f3e513ad Iustin Pop
      continue
2072 f3e513ad Iustin Pop
    try:
2073 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
2074 f3e513ad Iustin Pop
      dev.Rename(unique_id)
2075 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
2076 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
2077 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
2078 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
2079 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2080 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
2081 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
2082 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
2083 7c4d6c7b Michael Hanselmann
    except errors.BlockDeviceError:
2084 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2085 f3e513ad Iustin Pop
      result = False
2086 f3e513ad Iustin Pop
  return result
2087 f3e513ad Iustin Pop
2088 f3e513ad Iustin Pop
2089 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
2090 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
2091 778b75bb Manuel Franceschini

2092 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
2093 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
2094 778b75bb Manuel Franceschini
  directory are allowed.
2095 778b75bb Manuel Franceschini

2096 b1206984 Iustin Pop
  @type file_storage_dir: str
2097 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
2098 d61cbe76 Iustin Pop

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

2101 778b75bb Manuel Franceschini
  """
2102 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
2103 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
2104 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
2105 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2106 778b75bb Manuel Franceschini
      base_file_storage_dir):
2107 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
2108 18682bca Iustin Pop
                  " storage directory '%s'",
2109 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
2110 778b75bb Manuel Franceschini
    return None
2111 778b75bb Manuel Franceschini
  return file_storage_dir
2112 778b75bb Manuel Franceschini
2113 778b75bb Manuel Franceschini
2114 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
2115 778b75bb Manuel Franceschini
  """Create file storage directory.
2116 778b75bb Manuel Franceschini

2117 b1206984 Iustin Pop
  @type file_storage_dir: str
2118 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
2119 778b75bb Manuel Franceschini

2120 b1206984 Iustin Pop
  @rtype: tuple
2121 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
2122 b1206984 Iustin Pop
      creation was successful or not
2123 778b75bb Manuel Franceschini

2124 778b75bb Manuel Franceschini
  """
2125 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2126 778b75bb Manuel Franceschini
  result = True,
2127 778b75bb Manuel Franceschini
  if not file_storage_dir:
2128 778b75bb Manuel Franceschini
    result = False,
2129 778b75bb Manuel Franceschini
  else:
2130 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2131 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2132 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2133 778b75bb Manuel Franceschini
        result = False,
2134 778b75bb Manuel Franceschini
    else:
2135 778b75bb Manuel Franceschini
      try:
2136 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
2137 778b75bb Manuel Franceschini
      except OSError, err:
2138 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
2139 18682bca Iustin Pop
                      file_storage_dir, err)
2140 778b75bb Manuel Franceschini
        result = False,
2141 778b75bb Manuel Franceschini
  return result
2142 778b75bb Manuel Franceschini
2143 778b75bb Manuel Franceschini
2144 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2145 778b75bb Manuel Franceschini
  """Remove file storage directory.
2146 778b75bb Manuel Franceschini

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

2149 10c2650b Iustin Pop
  @type file_storage_dir: str
2150 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2151 10c2650b Iustin Pop
  @rtype: tuple (success,)
2152 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2153 5bbd3f7f Michael Hanselmann
      whether the operation was successful
2154 778b75bb Manuel Franceschini

2155 778b75bb Manuel Franceschini
  """
2156 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2157 778b75bb Manuel Franceschini
  result = True,
2158 778b75bb Manuel Franceschini
  if not file_storage_dir:
2159 778b75bb Manuel Franceschini
    result = False,
2160 778b75bb Manuel Franceschini
  else:
2161 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2162 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2163 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2164 778b75bb Manuel Franceschini
        result = False,
2165 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
2166 778b75bb Manuel Franceschini
      try:
2167 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
2168 7c4d6c7b Michael Hanselmann
      except OSError:
2169 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
2170 18682bca Iustin Pop
                          file_storage_dir)
2171 778b75bb Manuel Franceschini
        result = False,
2172 778b75bb Manuel Franceschini
  return result
2173 778b75bb Manuel Franceschini
2174 778b75bb Manuel Franceschini
2175 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2176 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2177 778b75bb Manuel Franceschini

2178 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2179 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2180 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2181 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2182 10c2650b Iustin Pop
  @rtype: tuple (success,)
2183 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2184 10c2650b Iustin Pop
      whether the operation was successful
2185 778b75bb Manuel Franceschini

2186 778b75bb Manuel Franceschini
  """
2187 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2188 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2189 778b75bb Manuel Franceschini
  result = True,
2190 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
2191 778b75bb Manuel Franceschini
    result = False,
2192 778b75bb Manuel Franceschini
  else:
2193 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
2194 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
2195 778b75bb Manuel Franceschini
        try:
2196 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
2197 7c4d6c7b Michael Hanselmann
        except OSError:
2198 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
2199 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
2200 778b75bb Manuel Franceschini
          result =  False,
2201 778b75bb Manuel Franceschini
      else:
2202 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
2203 778b75bb Manuel Franceschini
        result = False,
2204 778b75bb Manuel Franceschini
    else:
2205 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
2206 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
2207 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
2208 778b75bb Manuel Franceschini
        result = False,
2209 778b75bb Manuel Franceschini
  return result
2210 778b75bb Manuel Franceschini
2211 778b75bb Manuel Franceschini
2212 dc31eae3 Michael Hanselmann
def _IsJobQueueFile(file_name):
2213 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2214 ca52cdeb Michael Hanselmann

2215 10c2650b Iustin Pop
  @type file_name: str
2216 10c2650b Iustin Pop
  @param file_name: the file name we should check
2217 10c2650b Iustin Pop
  @rtype: boolean
2218 10c2650b Iustin Pop
  @return: whether the file is under the queue directory
2219 10c2650b Iustin Pop

2220 ca52cdeb Michael Hanselmann
  """
2221 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2222 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2223 dc31eae3 Michael Hanselmann
2224 dc31eae3 Michael Hanselmann
  if not result:
2225 ca52cdeb Michael Hanselmann
    logging.error("'%s' is not a file in the queue directory",
2226 ca52cdeb Michael Hanselmann
                  file_name)
2227 dc31eae3 Michael Hanselmann
2228 dc31eae3 Michael Hanselmann
  return result
2229 dc31eae3 Michael Hanselmann
2230 dc31eae3 Michael Hanselmann
2231 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2232 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2233 dc31eae3 Michael Hanselmann

2234 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2235 10c2650b Iustin Pop
  checking.
2236 10c2650b Iustin Pop

2237 10c2650b Iustin Pop
  @type file_name: str
2238 10c2650b Iustin Pop
  @param file_name: the job file name
2239 10c2650b Iustin Pop
  @type content: str
2240 10c2650b Iustin Pop
  @param content: the new job contents
2241 10c2650b Iustin Pop
  @rtype: boolean
2242 10c2650b Iustin Pop
  @return: the success of the operation
2243 10c2650b Iustin Pop

2244 dc31eae3 Michael Hanselmann
  """
2245 dc31eae3 Michael Hanselmann
  if not _IsJobQueueFile(file_name):
2246 ca52cdeb Michael Hanselmann
    return False
2247 ca52cdeb Michael Hanselmann
2248 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2249 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2250 ca52cdeb Michael Hanselmann
2251 ca52cdeb Michael Hanselmann
  return True
2252 ca52cdeb Michael Hanselmann
2253 ca52cdeb Michael Hanselmann
2254 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2255 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2256 af5ebcb1 Michael Hanselmann

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

2259 10c2650b Iustin Pop
  @type old: str
2260 10c2650b Iustin Pop
  @param old: the old (actual) file name
2261 10c2650b Iustin Pop
  @type new: str
2262 10c2650b Iustin Pop
  @param new: the desired file name
2263 10c2650b Iustin Pop
  @rtype: boolean
2264 10c2650b Iustin Pop
  @return: the success of the operation
2265 10c2650b Iustin Pop

2266 af5ebcb1 Michael Hanselmann
  """
2267 af5ebcb1 Michael Hanselmann
  if not (_IsJobQueueFile(old) and _IsJobQueueFile(new)):
2268 af5ebcb1 Michael Hanselmann
    return False
2269 af5ebcb1 Michael Hanselmann
2270 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2271 af5ebcb1 Michael Hanselmann
2272 af5ebcb1 Michael Hanselmann
  return True
2273 af5ebcb1 Michael Hanselmann
2274 af5ebcb1 Michael Hanselmann
2275 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2276 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2277 5d672980 Iustin Pop

2278 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2279 5d672980 Iustin Pop

2280 10c2650b Iustin Pop
  @type drain_flag: boolean
2281 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2282 10c2650b Iustin Pop
  @rtype: boolean
2283 10c2650b Iustin Pop
  @return: always True
2284 10c2650b Iustin Pop
  @warning: the function always returns True
2285 5d672980 Iustin Pop

2286 5d672980 Iustin Pop
  """
2287 5d672980 Iustin Pop
  if drain_flag:
2288 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2289 5d672980 Iustin Pop
  else:
2290 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2291 5d672980 Iustin Pop
2292 5d672980 Iustin Pop
  return True
2293 5d672980 Iustin Pop
2294 5d672980 Iustin Pop
2295 821d1bd1 Iustin Pop
def BlockdevClose(instance_name, disks):
2296 d61cbe76 Iustin Pop
  """Closes the given block devices.
2297 d61cbe76 Iustin Pop

2298 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2299 10c2650b Iustin Pop
  DRBD).
2300 10c2650b Iustin Pop

2301 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2302 b2e7666a Iustin Pop
      of this instance will be removed
2303 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2304 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2305 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2306 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2307 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2308 10c2650b Iustin Pop
      which will contain the error details in case we
2309 10c2650b Iustin Pop
      failed
2310 d61cbe76 Iustin Pop

2311 d61cbe76 Iustin Pop
  """
2312 d61cbe76 Iustin Pop
  bdevs = []
2313 d61cbe76 Iustin Pop
  for cf in disks:
2314 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2315 d61cbe76 Iustin Pop
    if rd is None:
2316 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
2317 d61cbe76 Iustin Pop
    bdevs.append(rd)
2318 d61cbe76 Iustin Pop
2319 d61cbe76 Iustin Pop
  msg = []
2320 d61cbe76 Iustin Pop
  for rd in bdevs:
2321 d61cbe76 Iustin Pop
    try:
2322 d61cbe76 Iustin Pop
      rd.Close()
2323 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2324 d61cbe76 Iustin Pop
      msg.append(str(err))
2325 d61cbe76 Iustin Pop
  if msg:
2326 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
2327 d61cbe76 Iustin Pop
  else:
2328 b2e7666a Iustin Pop
    if instance_name:
2329 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2330 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
2331 d61cbe76 Iustin Pop
2332 d61cbe76 Iustin Pop
2333 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2334 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2335 6217e295 Iustin Pop

2336 6217e295 Iustin Pop
  @type hvname: string
2337 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2338 6217e295 Iustin Pop
  @type hvparams: dict
2339 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2340 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2341 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2342 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2343 10c2650b Iustin Pop
      which will contain the error details in case we
2344 10c2650b Iustin Pop
      failed
2345 6217e295 Iustin Pop

2346 6217e295 Iustin Pop
  """
2347 6217e295 Iustin Pop
  try:
2348 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2349 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2350 6217e295 Iustin Pop
    return (True, "Validation passed")
2351 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2352 6217e295 Iustin Pop
    return (False, str(err))
2353 6217e295 Iustin Pop
2354 6217e295 Iustin Pop
2355 56aa9fd5 Iustin Pop
def DemoteFromMC():
2356 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2357 56aa9fd5 Iustin Pop

2358 56aa9fd5 Iustin Pop
  """
2359 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2360 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2361 56aa9fd5 Iustin Pop
  if master == myself:
2362 56aa9fd5 Iustin Pop
    return (False, "ssconf status shows I'm the master node, will not demote")
2363 56aa9fd5 Iustin Pop
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2364 56aa9fd5 Iustin Pop
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2365 56aa9fd5 Iustin Pop
    return (False, "The master daemon is running, will not demote")
2366 56aa9fd5 Iustin Pop
  try:
2367 9a5cb537 Iustin Pop
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2368 9a5cb537 Iustin Pop
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2369 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2370 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2371 56aa9fd5 Iustin Pop
      return (False, "Error while backing up cluster file: %s" % str(err))
2372 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2373 56aa9fd5 Iustin Pop
  return (True, "Done")
2374 56aa9fd5 Iustin Pop
2375 56aa9fd5 Iustin Pop
2376 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2377 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2378 6b93ec9d Iustin Pop

2379 6b93ec9d Iustin Pop
  """
2380 6b93ec9d Iustin Pop
  # set the correct physical ID
2381 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2382 6b93ec9d Iustin Pop
  for cf in disks:
2383 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2384 6b93ec9d Iustin Pop
2385 6b93ec9d Iustin Pop
  bdevs = []
2386 6b93ec9d Iustin Pop
2387 6b93ec9d Iustin Pop
  for cf in disks:
2388 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2389 6b93ec9d Iustin Pop
    if rd is None:
2390 6b93ec9d Iustin Pop
      return (False, "Can't find device %s" % cf)
2391 6b93ec9d Iustin Pop
    bdevs.append(rd)
2392 6b93ec9d Iustin Pop
  return (True, bdevs)
2393 6b93ec9d Iustin Pop
2394 6b93ec9d Iustin Pop
2395 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2396 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2397 6b93ec9d Iustin Pop

2398 6b93ec9d Iustin Pop
  """
2399 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2400 6b93ec9d Iustin Pop
  if not status:
2401 6b93ec9d Iustin Pop
    return status, bdevs
2402 6b93ec9d Iustin Pop
2403 6b93ec9d Iustin Pop
  # disconnect disks
2404 6b93ec9d Iustin Pop
  for rd in bdevs:
2405 6b93ec9d Iustin Pop
    try:
2406 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2407 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2408 6b93ec9d Iustin Pop
      logging.exception("Failed to go into standalone mode")
2409 6b93ec9d Iustin Pop
      return (False, "Can't change network configuration: %s" % str(err))
2410 6b93ec9d Iustin Pop
  return (True, "All disks are now disconnected")
2411 6b93ec9d Iustin Pop
2412 6b93ec9d Iustin Pop
2413 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2414 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2415 6b93ec9d Iustin Pop

2416 6b93ec9d Iustin Pop
  """
2417 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2418 6b93ec9d Iustin Pop
  if not status:
2419 6b93ec9d Iustin Pop
    return status, bdevs
2420 6b93ec9d Iustin Pop
2421 6b93ec9d Iustin Pop
  if multimaster:
2422 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2423 6b93ec9d Iustin Pop
      try:
2424 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2425 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2426 6b93ec9d Iustin Pop
        return (False, "Can't create symlink: %s" % str(err))
2427 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2428 6b93ec9d Iustin Pop
  # needed primary mode
2429 6b93ec9d Iustin Pop
  for rd in bdevs:
2430 6b93ec9d Iustin Pop
    try:
2431 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2432 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2433 6b93ec9d Iustin Pop
      return (False, "Can't change network configuration: %s" % str(err))
2434 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2435 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2436 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2437 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2438 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2439 6b93ec9d Iustin Pop
  RECONNECT_TIMEOUT = 2 * 60
2440 6b93ec9d Iustin Pop
  sleep_time = 0.100 # start with 100 miliseconds
2441 6b93ec9d Iustin Pop
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2442 6b93ec9d Iustin Pop
  while time.time() < timeout_limit:
2443 6b93ec9d Iustin Pop
    all_connected = True
2444 6b93ec9d Iustin Pop
    for rd in bdevs:
2445 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2446 6b93ec9d Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2447 6b93ec9d Iustin Pop
        all_connected = False
2448 6b93ec9d Iustin Pop
      if stats.is_standalone:
2449 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2450 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2451 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2452 6b93ec9d Iustin Pop
        try:
2453 c738375b Iustin Pop
          rd.AttachNet(multimaster)
2454 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2455 6b93ec9d Iustin Pop
          return (False, "Can't change network configuration: %s" % str(err))
2456 6b93ec9d Iustin Pop
    if all_connected:
2457 6b93ec9d Iustin Pop
      break
2458 6b93ec9d Iustin Pop
    time.sleep(sleep_time)
2459 6b93ec9d Iustin Pop
    sleep_time = min(5, sleep_time * 1.5)
2460 6b93ec9d Iustin Pop
  if not all_connected:
2461 6b93ec9d Iustin Pop
    return (False, "Timeout in disk reconnecting")
2462 6b93ec9d Iustin Pop
  if multimaster:
2463 6b93ec9d Iustin Pop
    # change to primary mode
2464 6b93ec9d Iustin Pop
    for rd in bdevs:
2465 d3da87b8 Iustin Pop
      try:
2466 d3da87b8 Iustin Pop
        rd.Open()
2467 d3da87b8 Iustin Pop
      except errors.BlockDeviceError, err:
2468 d3da87b8 Iustin Pop
        return (False, "Can't change to primary mode: %s" % str(err))
2469 6b93ec9d Iustin Pop
  if multimaster:
2470 6b93ec9d Iustin Pop
    msg = "multi-master and primary"
2471 6b93ec9d Iustin Pop
  else:
2472 6b93ec9d Iustin Pop
    msg = "single-master"
2473 6b93ec9d Iustin Pop
  return (True, "Disks are now configured as %s" % msg)
2474 6b93ec9d Iustin Pop
2475 6b93ec9d Iustin Pop
2476 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2477 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2478 6b93ec9d Iustin Pop

2479 6b93ec9d Iustin Pop
  """
2480 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2481 6b93ec9d Iustin Pop
  if not status:
2482 6b93ec9d Iustin Pop
    return status, bdevs
2483 6b93ec9d Iustin Pop
2484 6b93ec9d Iustin Pop
  min_resync = 100
2485 6b93ec9d Iustin Pop
  alldone = True
2486 6b93ec9d Iustin Pop
  failure = False
2487 6b93ec9d Iustin Pop
  for rd in bdevs:
2488 6b93ec9d Iustin Pop
    stats = rd.GetProcStatus()
2489 6b93ec9d Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2490 6b93ec9d Iustin Pop
      failure = True
2491 6b93ec9d Iustin Pop
      break
2492 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2493 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2494 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2495 6b93ec9d Iustin Pop
  return (not failure, (alldone, min_resync))
2496 6b93ec9d Iustin Pop
2497 6b93ec9d Iustin Pop
2498 a8083063 Iustin Pop
class HooksRunner(object):
2499 a8083063 Iustin Pop
  """Hook runner.
2500 a8083063 Iustin Pop

2501 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2502 10c2650b Iustin Pop
  on the master side.
2503 a8083063 Iustin Pop

2504 a8083063 Iustin Pop
  """
2505 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2506 a8083063 Iustin Pop
    """Constructor for hooks runner.
2507 a8083063 Iustin Pop

2508 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2509 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2510 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2511 a8083063 Iustin Pop

2512 a8083063 Iustin Pop
    """
2513 a8083063 Iustin Pop
    if hooks_base_dir is None:
2514 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2515 fe267188 Iustin Pop
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
2516 fe267188 Iustin Pop
    # constant
2517 fe267188 Iustin Pop
    self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
2518 a8083063 Iustin Pop
2519 a8083063 Iustin Pop
  @staticmethod
2520 a8083063 Iustin Pop
  def ExecHook(script, env):
2521 a8083063 Iustin Pop
    """Exec one hook script.
2522 a8083063 Iustin Pop

2523 10c2650b Iustin Pop
    @type script: str
2524 10c2650b Iustin Pop
    @param script: the full path to the script
2525 10c2650b Iustin Pop
    @type env: dict
2526 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2527 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2528 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2529 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2530 10c2650b Iustin Pop
        which will contain the error details in case we
2531 10c2650b Iustin Pop
        failed
2532 a8083063 Iustin Pop

2533 a8083063 Iustin Pop
    """
2534 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2535 a8083063 Iustin Pop
    fdstdin = None
2536 a8083063 Iustin Pop
    try:
2537 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2538 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2539 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2540 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2541 a8083063 Iustin Pop
      output = ""
2542 a8083063 Iustin Pop
      try:
2543 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2544 a8083063 Iustin Pop
        child.stdout.close()
2545 a8083063 Iustin Pop
      except EnvironmentError, err:
2546 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2547 a8083063 Iustin Pop
2548 a8083063 Iustin Pop
      while True:
2549 a8083063 Iustin Pop
        try:
2550 a8083063 Iustin Pop
          result = child.wait()
2551 a8083063 Iustin Pop
          break
2552 a8083063 Iustin Pop
        except EnvironmentError, err:
2553 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2554 a8083063 Iustin Pop
            continue
2555 a8083063 Iustin Pop
          raise
2556 a8083063 Iustin Pop
    finally:
2557 a8083063 Iustin Pop
      # try not to leak fds
2558 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2559 a8083063 Iustin Pop
        if fd is not None:
2560 a8083063 Iustin Pop
          try:
2561 a8083063 Iustin Pop
            fd.close()
2562 a8083063 Iustin Pop
          except EnvironmentError, err:
2563 a8083063 Iustin Pop
            # just log the error
2564 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2565 a8083063 Iustin Pop
            pass
2566 a8083063 Iustin Pop
2567 26f15862 Iustin Pop
    return result == 0, utils.SafeEncode(output.strip())
2568 a8083063 Iustin Pop
2569 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2570 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2571 a8083063 Iustin Pop

2572 10c2650b Iustin Pop
    @type hpath: str
2573 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2574 10c2650b Iustin Pop
        holds the scripts
2575 10c2650b Iustin Pop
    @type phase: str
2576 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2577 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2578 10c2650b Iustin Pop
    @type env: dict
2579 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2580 10c2650b Iustin Pop
    @rtype: list
2581 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2582 10c2650b Iustin Pop
      - script path
2583 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2584 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2585 10c2650b Iustin Pop
      - output of the script
2586 10c2650b Iustin Pop

2587 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2588 10c2650b Iustin Pop
        parameters
2589 a8083063 Iustin Pop

2590 a8083063 Iustin Pop
    """
2591 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2592 a8083063 Iustin Pop
      suffix = "pre"
2593 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2594 a8083063 Iustin Pop
      suffix = "post"
2595 a8083063 Iustin Pop
    else:
2596 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
2597 a8083063 Iustin Pop
    rr = []
2598 a8083063 Iustin Pop
2599 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2600 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2601 a8083063 Iustin Pop
    try:
2602 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2603 7c4d6c7b Michael Hanselmann
    except OSError:
2604 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2605 a8083063 Iustin Pop
      return rr
2606 a8083063 Iustin Pop
2607 a8083063 Iustin Pop
    # we use the standard python sort order,
2608 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2609 a8083063 Iustin Pop
    dir_contents.sort()
2610 a8083063 Iustin Pop
    for relname in dir_contents:
2611 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2612 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2613 4fe80ef2 Iustin Pop
              constants.EXT_PLUGIN_MASK.match(relname) is not None):
2614 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2615 a8083063 Iustin Pop
        output = ""
2616 a8083063 Iustin Pop
      else:
2617 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2618 a8083063 Iustin Pop
        if not result:
2619 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2620 a8083063 Iustin Pop
        else:
2621 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2622 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2623 a8083063 Iustin Pop
2624 a8083063 Iustin Pop
    return rr
2625 3f78eef2 Iustin Pop
2626 3f78eef2 Iustin Pop
2627 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2628 8d528b7c Iustin Pop
  """IAllocator runner.
2629 8d528b7c Iustin Pop

2630 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2631 8d528b7c Iustin Pop
  the master side.
2632 8d528b7c Iustin Pop

2633 8d528b7c Iustin Pop
  """
2634 8d528b7c Iustin Pop
  def Run(self, name, idata):
2635 8d528b7c Iustin Pop
    """Run an iallocator script.
2636 8d528b7c Iustin Pop

2637 10c2650b Iustin Pop
    @type name: str
2638 10c2650b Iustin Pop
    @param name: the iallocator script name
2639 10c2650b Iustin Pop
    @type idata: str
2640 10c2650b Iustin Pop
    @param idata: the allocator input data
2641 10c2650b Iustin Pop

2642 10c2650b Iustin Pop
    @rtype: tuple
2643 10c2650b Iustin Pop
    @return: four element tuple of:
2644 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
2645 8d528b7c Iustin Pop
       - stdout
2646 8d528b7c Iustin Pop
       - stderr
2647 10c2650b Iustin Pop
       - fail reason (as from L{utils.RunResult})
2648 8d528b7c Iustin Pop

2649 8d528b7c Iustin Pop
    """
2650 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2651 8d528b7c Iustin Pop
                                  os.path.isfile)
2652 8d528b7c Iustin Pop
    if alloc_script is None:
2653 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
2654 8d528b7c Iustin Pop
2655 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2656 8d528b7c Iustin Pop
    try:
2657 8d528b7c Iustin Pop
      os.write(fd, idata)
2658 8d528b7c Iustin Pop
      os.close(fd)
2659 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2660 8d528b7c Iustin Pop
      if result.failed:
2661 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
2662 8d528b7c Iustin Pop
                result.fail_reason)
2663 8d528b7c Iustin Pop
    finally:
2664 8d528b7c Iustin Pop
      os.unlink(fin_name)
2665 8d528b7c Iustin Pop
2666 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
2667 8d528b7c Iustin Pop
2668 8d528b7c Iustin Pop
2669 3f78eef2 Iustin Pop
class DevCacheManager(object):
2670 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2671 3f78eef2 Iustin Pop

2672 3f78eef2 Iustin Pop
  """
2673 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2674 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2675 3f78eef2 Iustin Pop
2676 3f78eef2 Iustin Pop
  @classmethod
2677 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2678 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2679 3f78eef2 Iustin Pop

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

2683 10c2650b Iustin Pop
    @type dev_path: str
2684 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2685 10c2650b Iustin Pop
    @rtype: str
2686 10c2650b Iustin Pop
    @return: the converted path name
2687 3f78eef2 Iustin Pop

2688 3f78eef2 Iustin Pop
    """
2689 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2690 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2691 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2692 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2693 3f78eef2 Iustin Pop
    return fpath
2694 3f78eef2 Iustin Pop
2695 3f78eef2 Iustin Pop
  @classmethod
2696 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2697 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2698 3f78eef2 Iustin Pop

2699 10c2650b Iustin Pop
    @type dev_path: str
2700 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2701 10c2650b Iustin Pop
    @type owner: str
2702 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2703 10c2650b Iustin Pop
    @type on_primary: bool
2704 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2705 10c2650b Iustin Pop
        node nor not
2706 10c2650b Iustin Pop
    @type iv_name: str
2707 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2708 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2709 10c2650b Iustin Pop

2710 10c2650b Iustin Pop
    @rtype: None
2711 10c2650b Iustin Pop

2712 3f78eef2 Iustin Pop
    """
2713 cf5a8306 Iustin Pop
    if dev_path is None:
2714 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2715 cf5a8306 Iustin Pop
      return
2716 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2717 3f78eef2 Iustin Pop
    if on_primary:
2718 3f78eef2 Iustin Pop
      state = "primary"
2719 3f78eef2 Iustin Pop
    else:
2720 3f78eef2 Iustin Pop
      state = "secondary"
2721 3f78eef2 Iustin Pop
    if iv_name is None:
2722 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2723 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2724 3f78eef2 Iustin Pop
    try:
2725 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2726 7c4d6c7b Michael Hanselmann
    except EnvironmentError:
2727 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
2728 3f78eef2 Iustin Pop
2729 3f78eef2 Iustin Pop
  @classmethod
2730 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2731 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2732 3f78eef2 Iustin Pop

2733 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2734 10c2650b Iustin Pop
    path name and logging.
2735 10c2650b Iustin Pop

2736 10c2650b Iustin Pop
    @type dev_path: str
2737 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2738 10c2650b Iustin Pop

2739 10c2650b Iustin Pop
    @rtype: None
2740 10c2650b Iustin Pop

2741 3f78eef2 Iustin Pop
    """
2742 cf5a8306 Iustin Pop
    if dev_path is None:
2743 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2744 cf5a8306 Iustin Pop
      return
2745 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2746 3f78eef2 Iustin Pop
    try:
2747 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2748 7c4d6c7b Michael Hanselmann
    except EnvironmentError:
2749 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)