Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 468b46f9

History | View | Annotate | Download (186.9 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 e7c6e02b Michael Hanselmann
# Copyright (C) 2006, 2007, 2008 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 880478f8 Iustin Pop
"""Module implementing the master-side code."""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
# pylint: disable-msg=W0613,W0201
25 a8083063 Iustin Pop
26 a8083063 Iustin Pop
import os
27 a8083063 Iustin Pop
import os.path
28 a8083063 Iustin Pop
import sha
29 a8083063 Iustin Pop
import time
30 a8083063 Iustin Pop
import tempfile
31 a8083063 Iustin Pop
import re
32 a8083063 Iustin Pop
import platform
33 ffa1c0dc Iustin Pop
import logging
34 a8083063 Iustin Pop
35 a8083063 Iustin Pop
from ganeti import rpc
36 a8083063 Iustin Pop
from ganeti import ssh
37 a8083063 Iustin Pop
from ganeti import logger
38 a8083063 Iustin Pop
from ganeti import utils
39 a8083063 Iustin Pop
from ganeti import errors
40 a8083063 Iustin Pop
from ganeti import hypervisor
41 6048c986 Guido Trotter
from ganeti import locking
42 a8083063 Iustin Pop
from ganeti import constants
43 a8083063 Iustin Pop
from ganeti import objects
44 a8083063 Iustin Pop
from ganeti import opcodes
45 8d14b30d Iustin Pop
from ganeti import serializer
46 d61df03e Iustin Pop
47 d61df03e Iustin Pop
48 a8083063 Iustin Pop
class LogicalUnit(object):
49 396e1b78 Michael Hanselmann
  """Logical Unit base class.
50 a8083063 Iustin Pop

51 a8083063 Iustin Pop
  Subclasses must follow these rules:
52 d465bdc8 Guido Trotter
    - implement ExpandNames
53 d465bdc8 Guido Trotter
    - implement CheckPrereq
54 a8083063 Iustin Pop
    - implement Exec
55 a8083063 Iustin Pop
    - implement BuildHooksEnv
56 a8083063 Iustin Pop
    - redefine HPATH and HTYPE
57 05f86716 Guido Trotter
    - optionally redefine their run requirements:
58 05f86716 Guido Trotter
        REQ_MASTER: the LU needs to run on the master node
59 05f86716 Guido Trotter
        REQ_WSSTORE: the LU needs a writable SimpleStore
60 7e55040e Guido Trotter
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
61 05f86716 Guido Trotter

62 05f86716 Guido Trotter
  Note that all commands require root permissions.
63 a8083063 Iustin Pop

64 a8083063 Iustin Pop
  """
65 a8083063 Iustin Pop
  HPATH = None
66 a8083063 Iustin Pop
  HTYPE = None
67 a8083063 Iustin Pop
  _OP_REQP = []
68 a8083063 Iustin Pop
  REQ_MASTER = True
69 05f86716 Guido Trotter
  REQ_WSSTORE = False
70 7e55040e Guido Trotter
  REQ_BGL = True
71 a8083063 Iustin Pop
72 77b657a3 Guido Trotter
  def __init__(self, processor, op, context, sstore):
73 a8083063 Iustin Pop
    """Constructor for LogicalUnit.
74 a8083063 Iustin Pop

75 a8083063 Iustin Pop
    This needs to be overriden in derived classes in order to check op
76 a8083063 Iustin Pop
    validity.
77 a8083063 Iustin Pop

78 a8083063 Iustin Pop
    """
79 5bfac263 Iustin Pop
    self.proc = processor
80 a8083063 Iustin Pop
    self.op = op
81 77b657a3 Guido Trotter
    self.cfg = context.cfg
82 a8083063 Iustin Pop
    self.sstore = sstore
83 77b657a3 Guido Trotter
    self.context = context
84 ca2a79e1 Guido Trotter
    # Dicts used to declare locking needs to mcpu
85 d465bdc8 Guido Trotter
    self.needed_locks = None
86 6683bba2 Guido Trotter
    self.acquired_locks = {}
87 3977a4c1 Guido Trotter
    self.share_locks = dict(((i, 0) for i in locking.LEVELS))
88 ca2a79e1 Guido Trotter
    self.add_locks = {}
89 ca2a79e1 Guido Trotter
    self.remove_locks = {}
90 c4a2fee1 Guido Trotter
    # Used to force good behavior when calling helper functions
91 c4a2fee1 Guido Trotter
    self.recalculate_locks = {}
92 c92b310a Michael Hanselmann
    self.__ssh = None
93 c92b310a Michael Hanselmann
94 a8083063 Iustin Pop
    for attr_name in self._OP_REQP:
95 a8083063 Iustin Pop
      attr_val = getattr(op, attr_name, None)
96 a8083063 Iustin Pop
      if attr_val is None:
97 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Required parameter '%s' missing" %
98 3ecf6786 Iustin Pop
                                   attr_name)
99 c6d58a2b Michael Hanselmann
100 f64c9de6 Guido Trotter
    if not self.cfg.IsCluster():
101 c6d58a2b Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized yet,"
102 c6d58a2b Michael Hanselmann
                                 " use 'gnt-cluster init' first.")
103 c6d58a2b Michael Hanselmann
    if self.REQ_MASTER:
104 c6d58a2b Michael Hanselmann
      master = sstore.GetMasterNode()
105 c6d58a2b Michael Hanselmann
      if master != utils.HostInfo().name:
106 c6d58a2b Michael Hanselmann
        raise errors.OpPrereqError("Commands must be run on the master"
107 c6d58a2b Michael Hanselmann
                                   " node %s" % master)
108 a8083063 Iustin Pop
109 c92b310a Michael Hanselmann
  def __GetSSH(self):
110 c92b310a Michael Hanselmann
    """Returns the SshRunner object
111 c92b310a Michael Hanselmann

112 c92b310a Michael Hanselmann
    """
113 c92b310a Michael Hanselmann
    if not self.__ssh:
114 1ff08570 Michael Hanselmann
      self.__ssh = ssh.SshRunner(self.sstore)
115 c92b310a Michael Hanselmann
    return self.__ssh
116 c92b310a Michael Hanselmann
117 c92b310a Michael Hanselmann
  ssh = property(fget=__GetSSH)
118 c92b310a Michael Hanselmann
119 d465bdc8 Guido Trotter
  def ExpandNames(self):
120 d465bdc8 Guido Trotter
    """Expand names for this LU.
121 d465bdc8 Guido Trotter

122 d465bdc8 Guido Trotter
    This method is called before starting to execute the opcode, and it should
123 d465bdc8 Guido Trotter
    update all the parameters of the opcode to their canonical form (e.g. a
124 d465bdc8 Guido Trotter
    short node name must be fully expanded after this method has successfully
125 d465bdc8 Guido Trotter
    completed). This way locking, hooks, logging, ecc. can work correctly.
126 d465bdc8 Guido Trotter

127 d465bdc8 Guido Trotter
    LUs which implement this method must also populate the self.needed_locks
128 d465bdc8 Guido Trotter
    member, as a dict with lock levels as keys, and a list of needed lock names
129 d465bdc8 Guido Trotter
    as values. Rules:
130 d465bdc8 Guido Trotter
      - Use an empty dict if you don't need any lock
131 d465bdc8 Guido Trotter
      - If you don't need any lock at a particular level omit that level
132 d465bdc8 Guido Trotter
      - Don't put anything for the BGL level
133 e310b019 Guido Trotter
      - If you want all locks at a level use locking.ALL_SET as a value
134 d465bdc8 Guido Trotter

135 3977a4c1 Guido Trotter
    If you need to share locks (rather than acquire them exclusively) at one
136 3977a4c1 Guido Trotter
    level you can modify self.share_locks, setting a true value (usually 1) for
137 3977a4c1 Guido Trotter
    that level. By default locks are not shared.
138 3977a4c1 Guido Trotter

139 d465bdc8 Guido Trotter
    Examples:
140 d465bdc8 Guido Trotter
    # Acquire all nodes and one instance
141 d465bdc8 Guido Trotter
    self.needed_locks = {
142 e310b019 Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
143 3a5d7305 Guido Trotter
      locking.LEVEL_INSTANCE: ['instance1.example.tld'],
144 d465bdc8 Guido Trotter
    }
145 d465bdc8 Guido Trotter
    # Acquire just two nodes
146 d465bdc8 Guido Trotter
    self.needed_locks = {
147 d465bdc8 Guido Trotter
      locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
148 d465bdc8 Guido Trotter
    }
149 d465bdc8 Guido Trotter
    # Acquire no locks
150 d465bdc8 Guido Trotter
    self.needed_locks = {} # No, you can't leave it to the default value None
151 d465bdc8 Guido Trotter

152 d465bdc8 Guido Trotter
    """
153 d465bdc8 Guido Trotter
    # The implementation of this method is mandatory only if the new LU is
154 d465bdc8 Guido Trotter
    # concurrent, so that old LUs don't need to be changed all at the same
155 d465bdc8 Guido Trotter
    # time.
156 d465bdc8 Guido Trotter
    if self.REQ_BGL:
157 d465bdc8 Guido Trotter
      self.needed_locks = {} # Exclusive LUs don't need locks.
158 d465bdc8 Guido Trotter
    else:
159 d465bdc8 Guido Trotter
      raise NotImplementedError
160 d465bdc8 Guido Trotter
161 fb8dcb62 Guido Trotter
  def DeclareLocks(self, level):
162 fb8dcb62 Guido Trotter
    """Declare LU locking needs for a level
163 fb8dcb62 Guido Trotter

164 fb8dcb62 Guido Trotter
    While most LUs can just declare their locking needs at ExpandNames time,
165 fb8dcb62 Guido Trotter
    sometimes there's the need to calculate some locks after having acquired
166 fb8dcb62 Guido Trotter
    the ones before. This function is called just before acquiring locks at a
167 fb8dcb62 Guido Trotter
    particular level, but after acquiring the ones at lower levels, and permits
168 fb8dcb62 Guido Trotter
    such calculations. It can be used to modify self.needed_locks, and by
169 fb8dcb62 Guido Trotter
    default it does nothing.
170 fb8dcb62 Guido Trotter

171 fb8dcb62 Guido Trotter
    This function is only called if you have something already set in
172 fb8dcb62 Guido Trotter
    self.needed_locks for the level.
173 fb8dcb62 Guido Trotter

174 fb8dcb62 Guido Trotter
    @param level: Locking level which is going to be locked
175 fb8dcb62 Guido Trotter
    @type level: member of ganeti.locking.LEVELS
176 fb8dcb62 Guido Trotter

177 fb8dcb62 Guido Trotter
    """
178 fb8dcb62 Guido Trotter
179 a8083063 Iustin Pop
  def CheckPrereq(self):
180 a8083063 Iustin Pop
    """Check prerequisites for this LU.
181 a8083063 Iustin Pop

182 a8083063 Iustin Pop
    This method should check that the prerequisites for the execution
183 a8083063 Iustin Pop
    of this LU are fulfilled. It can do internode communication, but
184 a8083063 Iustin Pop
    it should be idempotent - no cluster or system changes are
185 a8083063 Iustin Pop
    allowed.
186 a8083063 Iustin Pop

187 a8083063 Iustin Pop
    The method should raise errors.OpPrereqError in case something is
188 a8083063 Iustin Pop
    not fulfilled. Its return value is ignored.
189 a8083063 Iustin Pop

190 a8083063 Iustin Pop
    This method should also update all the parameters of the opcode to
191 d465bdc8 Guido Trotter
    their canonical form if it hasn't been done by ExpandNames before.
192 a8083063 Iustin Pop

193 a8083063 Iustin Pop
    """
194 a8083063 Iustin Pop
    raise NotImplementedError
195 a8083063 Iustin Pop
196 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
197 a8083063 Iustin Pop
    """Execute the LU.
198 a8083063 Iustin Pop

199 a8083063 Iustin Pop
    This method should implement the actual work. It should raise
200 a8083063 Iustin Pop
    errors.OpExecError for failures that are somewhat dealt with in
201 a8083063 Iustin Pop
    code, or expected.
202 a8083063 Iustin Pop

203 a8083063 Iustin Pop
    """
204 a8083063 Iustin Pop
    raise NotImplementedError
205 a8083063 Iustin Pop
206 a8083063 Iustin Pop
  def BuildHooksEnv(self):
207 a8083063 Iustin Pop
    """Build hooks environment for this LU.
208 a8083063 Iustin Pop

209 a8083063 Iustin Pop
    This method should return a three-node tuple consisting of: a dict
210 a8083063 Iustin Pop
    containing the environment that will be used for running the
211 a8083063 Iustin Pop
    specific hook for this LU, a list of node names on which the hook
212 a8083063 Iustin Pop
    should run before the execution, and a list of node names on which
213 a8083063 Iustin Pop
    the hook should run after the execution.
214 a8083063 Iustin Pop

215 a8083063 Iustin Pop
    The keys of the dict must not have 'GANETI_' prefixed as this will
216 a8083063 Iustin Pop
    be handled in the hooks runner. Also note additional keys will be
217 a8083063 Iustin Pop
    added by the hooks runner. If the LU doesn't define any
218 a8083063 Iustin Pop
    environment, an empty dict (and not None) should be returned.
219 a8083063 Iustin Pop

220 8a3fe350 Guido Trotter
    No nodes should be returned as an empty list (and not None).
221 a8083063 Iustin Pop

222 a8083063 Iustin Pop
    Note that if the HPATH for a LU class is None, this function will
223 a8083063 Iustin Pop
    not be called.
224 a8083063 Iustin Pop

225 a8083063 Iustin Pop
    """
226 a8083063 Iustin Pop
    raise NotImplementedError
227 a8083063 Iustin Pop
228 1fce5219 Guido Trotter
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
229 1fce5219 Guido Trotter
    """Notify the LU about the results of its hooks.
230 1fce5219 Guido Trotter

231 1fce5219 Guido Trotter
    This method is called every time a hooks phase is executed, and notifies
232 1fce5219 Guido Trotter
    the Logical Unit about the hooks' result. The LU can then use it to alter
233 1fce5219 Guido Trotter
    its result based on the hooks.  By default the method does nothing and the
234 1fce5219 Guido Trotter
    previous result is passed back unchanged but any LU can define it if it
235 1fce5219 Guido Trotter
    wants to use the local cluster hook-scripts somehow.
236 1fce5219 Guido Trotter

237 1fce5219 Guido Trotter
    Args:
238 1fce5219 Guido Trotter
      phase: the hooks phase that has just been run
239 1fce5219 Guido Trotter
      hooks_results: the results of the multi-node hooks rpc call
240 1fce5219 Guido Trotter
      feedback_fn: function to send feedback back to the caller
241 1fce5219 Guido Trotter
      lu_result: the previous result this LU had, or None in the PRE phase.
242 1fce5219 Guido Trotter

243 1fce5219 Guido Trotter
    """
244 1fce5219 Guido Trotter
    return lu_result
245 1fce5219 Guido Trotter
246 43905206 Guido Trotter
  def _ExpandAndLockInstance(self):
247 43905206 Guido Trotter
    """Helper function to expand and lock an instance.
248 43905206 Guido Trotter

249 43905206 Guido Trotter
    Many LUs that work on an instance take its name in self.op.instance_name
250 43905206 Guido Trotter
    and need to expand it and then declare the expanded name for locking. This
251 43905206 Guido Trotter
    function does it, and then updates self.op.instance_name to the expanded
252 43905206 Guido Trotter
    name. It also initializes needed_locks as a dict, if this hasn't been done
253 43905206 Guido Trotter
    before.
254 43905206 Guido Trotter

255 43905206 Guido Trotter
    """
256 43905206 Guido Trotter
    if self.needed_locks is None:
257 43905206 Guido Trotter
      self.needed_locks = {}
258 43905206 Guido Trotter
    else:
259 43905206 Guido Trotter
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
260 43905206 Guido Trotter
        "_ExpandAndLockInstance called with instance-level locks set"
261 43905206 Guido Trotter
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
262 43905206 Guido Trotter
    if expanded_name is None:
263 43905206 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' not known" %
264 43905206 Guido Trotter
                                  self.op.instance_name)
265 43905206 Guido Trotter
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
266 43905206 Guido Trotter
    self.op.instance_name = expanded_name
267 43905206 Guido Trotter
268 a82ce292 Guido Trotter
  def _LockInstancesNodes(self, primary_only=False):
269 c4a2fee1 Guido Trotter
    """Helper function to declare instances' nodes for locking.
270 c4a2fee1 Guido Trotter

271 c4a2fee1 Guido Trotter
    This function should be called after locking one or more instances to lock
272 c4a2fee1 Guido Trotter
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
273 c4a2fee1 Guido Trotter
    with all primary or secondary nodes for instances already locked and
274 c4a2fee1 Guido Trotter
    present in self.needed_locks[locking.LEVEL_INSTANCE].
275 c4a2fee1 Guido Trotter

276 c4a2fee1 Guido Trotter
    It should be called from DeclareLocks, and for safety only works if
277 c4a2fee1 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] is set.
278 c4a2fee1 Guido Trotter

279 c4a2fee1 Guido Trotter
    In the future it may grow parameters to just lock some instance's nodes, or
280 c4a2fee1 Guido Trotter
    to just lock primaries or secondary nodes, if needed.
281 c4a2fee1 Guido Trotter

282 c4a2fee1 Guido Trotter
    If should be called in DeclareLocks in a way similar to:
283 c4a2fee1 Guido Trotter

284 c4a2fee1 Guido Trotter
    if level == locking.LEVEL_NODE:
285 c4a2fee1 Guido Trotter
      self._LockInstancesNodes()
286 c4a2fee1 Guido Trotter

287 a82ce292 Guido Trotter
    @type primary_only: boolean
288 a82ce292 Guido Trotter
    @param primary_only: only lock primary nodes of locked instances
289 a82ce292 Guido Trotter

290 c4a2fee1 Guido Trotter
    """
291 c4a2fee1 Guido Trotter
    assert locking.LEVEL_NODE in self.recalculate_locks, \
292 c4a2fee1 Guido Trotter
      "_LockInstancesNodes helper function called with no nodes to recalculate"
293 c4a2fee1 Guido Trotter
294 c4a2fee1 Guido Trotter
    # TODO: check if we're really been called with the instance locks held
295 c4a2fee1 Guido Trotter
296 c4a2fee1 Guido Trotter
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
297 c4a2fee1 Guido Trotter
    # future we might want to have different behaviors depending on the value
298 c4a2fee1 Guido Trotter
    # of self.recalculate_locks[locking.LEVEL_NODE]
299 c4a2fee1 Guido Trotter
    wanted_nodes = []
300 6683bba2 Guido Trotter
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
301 c4a2fee1 Guido Trotter
      instance = self.context.cfg.GetInstanceInfo(instance_name)
302 c4a2fee1 Guido Trotter
      wanted_nodes.append(instance.primary_node)
303 a82ce292 Guido Trotter
      if not primary_only:
304 a82ce292 Guido Trotter
        wanted_nodes.extend(instance.secondary_nodes)
305 9513b6ab Guido Trotter
306 9513b6ab Guido Trotter
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
307 9513b6ab Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
308 9513b6ab Guido Trotter
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
309 9513b6ab Guido Trotter
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
310 c4a2fee1 Guido Trotter
311 c4a2fee1 Guido Trotter
    del self.recalculate_locks[locking.LEVEL_NODE]
312 c4a2fee1 Guido Trotter
313 a8083063 Iustin Pop
314 a8083063 Iustin Pop
class NoHooksLU(LogicalUnit):
315 a8083063 Iustin Pop
  """Simple LU which runs no hooks.
316 a8083063 Iustin Pop

317 a8083063 Iustin Pop
  This LU is intended as a parent for other LogicalUnits which will
318 a8083063 Iustin Pop
  run no hooks, in order to reduce duplicate code.
319 a8083063 Iustin Pop

320 a8083063 Iustin Pop
  """
321 a8083063 Iustin Pop
  HPATH = None
322 a8083063 Iustin Pop
  HTYPE = None
323 a8083063 Iustin Pop
324 a8083063 Iustin Pop
325 dcb93971 Michael Hanselmann
def _GetWantedNodes(lu, nodes):
326 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded node names.
327 83120a01 Michael Hanselmann

328 83120a01 Michael Hanselmann
  Args:
329 83120a01 Michael Hanselmann
    nodes: List of nodes (strings) or None for all
330 83120a01 Michael Hanselmann

331 83120a01 Michael Hanselmann
  """
332 3312b702 Iustin Pop
  if not isinstance(nodes, list):
333 3ecf6786 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
334 dcb93971 Michael Hanselmann
335 ea47808a Guido Trotter
  if not nodes:
336 ea47808a Guido Trotter
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
337 ea47808a Guido Trotter
      " non-empty list of nodes whose name is to be expanded.")
338 dcb93971 Michael Hanselmann
339 ea47808a Guido Trotter
  wanted = []
340 ea47808a Guido Trotter
  for name in nodes:
341 ea47808a Guido Trotter
    node = lu.cfg.ExpandNodeName(name)
342 ea47808a Guido Trotter
    if node is None:
343 ea47808a Guido Trotter
      raise errors.OpPrereqError("No such node name '%s'" % name)
344 ea47808a Guido Trotter
    wanted.append(node)
345 dcb93971 Michael Hanselmann
346 a7ba5e53 Iustin Pop
  return utils.NiceSort(wanted)
347 3312b702 Iustin Pop
348 3312b702 Iustin Pop
349 3312b702 Iustin Pop
def _GetWantedInstances(lu, instances):
350 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded instance names.
351 3312b702 Iustin Pop

352 3312b702 Iustin Pop
  Args:
353 3312b702 Iustin Pop
    instances: List of instances (strings) or None for all
354 3312b702 Iustin Pop

355 3312b702 Iustin Pop
  """
356 3312b702 Iustin Pop
  if not isinstance(instances, list):
357 3312b702 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'instances'")
358 3312b702 Iustin Pop
359 3312b702 Iustin Pop
  if instances:
360 3312b702 Iustin Pop
    wanted = []
361 3312b702 Iustin Pop
362 3312b702 Iustin Pop
    for name in instances:
363 a7ba5e53 Iustin Pop
      instance = lu.cfg.ExpandInstanceName(name)
364 3312b702 Iustin Pop
      if instance is None:
365 3312b702 Iustin Pop
        raise errors.OpPrereqError("No such instance name '%s'" % name)
366 3312b702 Iustin Pop
      wanted.append(instance)
367 3312b702 Iustin Pop
368 3312b702 Iustin Pop
  else:
369 a7ba5e53 Iustin Pop
    wanted = lu.cfg.GetInstanceList()
370 a7ba5e53 Iustin Pop
  return utils.NiceSort(wanted)
371 dcb93971 Michael Hanselmann
372 dcb93971 Michael Hanselmann
373 dcb93971 Michael Hanselmann
def _CheckOutputFields(static, dynamic, selected):
374 83120a01 Michael Hanselmann
  """Checks whether all selected fields are valid.
375 83120a01 Michael Hanselmann

376 83120a01 Michael Hanselmann
  Args:
377 83120a01 Michael Hanselmann
    static: Static fields
378 83120a01 Michael Hanselmann
    dynamic: Dynamic fields
379 83120a01 Michael Hanselmann

380 83120a01 Michael Hanselmann
  """
381 83120a01 Michael Hanselmann
  static_fields = frozenset(static)
382 83120a01 Michael Hanselmann
  dynamic_fields = frozenset(dynamic)
383 dcb93971 Michael Hanselmann
384 83120a01 Michael Hanselmann
  all_fields = static_fields | dynamic_fields
385 dcb93971 Michael Hanselmann
386 83120a01 Michael Hanselmann
  if not all_fields.issuperset(selected):
387 3ecf6786 Iustin Pop
    raise errors.OpPrereqError("Unknown output fields selected: %s"
388 3ecf6786 Iustin Pop
                               % ",".join(frozenset(selected).
389 3ecf6786 Iustin Pop
                                          difference(all_fields)))
390 dcb93971 Michael Hanselmann
391 dcb93971 Michael Hanselmann
392 ecb215b5 Michael Hanselmann
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
393 396e1b78 Michael Hanselmann
                          memory, vcpus, nics):
394 ecb215b5 Michael Hanselmann
  """Builds instance related env variables for hooks from single variables.
395 ecb215b5 Michael Hanselmann

396 ecb215b5 Michael Hanselmann
  Args:
397 ecb215b5 Michael Hanselmann
    secondary_nodes: List of secondary nodes as strings
398 396e1b78 Michael Hanselmann
  """
399 396e1b78 Michael Hanselmann
  env = {
400 0e137c28 Iustin Pop
    "OP_TARGET": name,
401 396e1b78 Michael Hanselmann
    "INSTANCE_NAME": name,
402 396e1b78 Michael Hanselmann
    "INSTANCE_PRIMARY": primary_node,
403 396e1b78 Michael Hanselmann
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
404 ecb215b5 Michael Hanselmann
    "INSTANCE_OS_TYPE": os_type,
405 396e1b78 Michael Hanselmann
    "INSTANCE_STATUS": status,
406 396e1b78 Michael Hanselmann
    "INSTANCE_MEMORY": memory,
407 396e1b78 Michael Hanselmann
    "INSTANCE_VCPUS": vcpus,
408 396e1b78 Michael Hanselmann
  }
409 396e1b78 Michael Hanselmann
410 396e1b78 Michael Hanselmann
  if nics:
411 396e1b78 Michael Hanselmann
    nic_count = len(nics)
412 53e4e875 Guido Trotter
    for idx, (ip, bridge, mac) in enumerate(nics):
413 396e1b78 Michael Hanselmann
      if ip is None:
414 396e1b78 Michael Hanselmann
        ip = ""
415 396e1b78 Michael Hanselmann
      env["INSTANCE_NIC%d_IP" % idx] = ip
416 396e1b78 Michael Hanselmann
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
417 53e4e875 Guido Trotter
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
418 396e1b78 Michael Hanselmann
  else:
419 396e1b78 Michael Hanselmann
    nic_count = 0
420 396e1b78 Michael Hanselmann
421 396e1b78 Michael Hanselmann
  env["INSTANCE_NIC_COUNT"] = nic_count
422 396e1b78 Michael Hanselmann
423 396e1b78 Michael Hanselmann
  return env
424 396e1b78 Michael Hanselmann
425 396e1b78 Michael Hanselmann
426 396e1b78 Michael Hanselmann
def _BuildInstanceHookEnvByObject(instance, override=None):
427 ecb215b5 Michael Hanselmann
  """Builds instance related env variables for hooks from an object.
428 ecb215b5 Michael Hanselmann

429 ecb215b5 Michael Hanselmann
  Args:
430 ecb215b5 Michael Hanselmann
    instance: objects.Instance object of instance
431 ecb215b5 Michael Hanselmann
    override: dict of values to override
432 ecb215b5 Michael Hanselmann
  """
433 396e1b78 Michael Hanselmann
  args = {
434 396e1b78 Michael Hanselmann
    'name': instance.name,
435 396e1b78 Michael Hanselmann
    'primary_node': instance.primary_node,
436 396e1b78 Michael Hanselmann
    'secondary_nodes': instance.secondary_nodes,
437 ecb215b5 Michael Hanselmann
    'os_type': instance.os,
438 396e1b78 Michael Hanselmann
    'status': instance.os,
439 396e1b78 Michael Hanselmann
    'memory': instance.memory,
440 396e1b78 Michael Hanselmann
    'vcpus': instance.vcpus,
441 53e4e875 Guido Trotter
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
442 396e1b78 Michael Hanselmann
  }
443 396e1b78 Michael Hanselmann
  if override:
444 396e1b78 Michael Hanselmann
    args.update(override)
445 396e1b78 Michael Hanselmann
  return _BuildInstanceHookEnv(**args)
446 396e1b78 Michael Hanselmann
447 396e1b78 Michael Hanselmann
448 bf6929a2 Alexander Schreiber
def _CheckInstanceBridgesExist(instance):
449 bf6929a2 Alexander Schreiber
  """Check that the brigdes needed by an instance exist.
450 bf6929a2 Alexander Schreiber

451 bf6929a2 Alexander Schreiber
  """
452 bf6929a2 Alexander Schreiber
  # check bridges existance
453 bf6929a2 Alexander Schreiber
  brlist = [nic.bridge for nic in instance.nics]
454 bf6929a2 Alexander Schreiber
  if not rpc.call_bridges_exist(instance.primary_node, brlist):
455 bf6929a2 Alexander Schreiber
    raise errors.OpPrereqError("one or more target bridges %s does not"
456 bf6929a2 Alexander Schreiber
                               " exist on destination node '%s'" %
457 bf6929a2 Alexander Schreiber
                               (brlist, instance.primary_node))
458 bf6929a2 Alexander Schreiber
459 bf6929a2 Alexander Schreiber
460 a8083063 Iustin Pop
class LUDestroyCluster(NoHooksLU):
461 a8083063 Iustin Pop
  """Logical unit for destroying the cluster.
462 a8083063 Iustin Pop

463 a8083063 Iustin Pop
  """
464 a8083063 Iustin Pop
  _OP_REQP = []
465 a8083063 Iustin Pop
466 a8083063 Iustin Pop
  def CheckPrereq(self):
467 a8083063 Iustin Pop
    """Check prerequisites.
468 a8083063 Iustin Pop

469 a8083063 Iustin Pop
    This checks whether the cluster is empty.
470 a8083063 Iustin Pop

471 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
472 a8083063 Iustin Pop

473 a8083063 Iustin Pop
    """
474 880478f8 Iustin Pop
    master = self.sstore.GetMasterNode()
475 a8083063 Iustin Pop
476 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
477 db915bd1 Michael Hanselmann
    if len(nodelist) != 1 or nodelist[0] != master:
478 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d node(s) in"
479 3ecf6786 Iustin Pop
                                 " this cluster." % (len(nodelist) - 1))
480 db915bd1 Michael Hanselmann
    instancelist = self.cfg.GetInstanceList()
481 db915bd1 Michael Hanselmann
    if instancelist:
482 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d instance(s) in"
483 3ecf6786 Iustin Pop
                                 " this cluster." % len(instancelist))
484 a8083063 Iustin Pop
485 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
486 a8083063 Iustin Pop
    """Destroys the cluster.
487 a8083063 Iustin Pop

488 a8083063 Iustin Pop
    """
489 c8a0948f Michael Hanselmann
    master = self.sstore.GetMasterNode()
490 1c65840b Iustin Pop
    if not rpc.call_node_stop_master(master, False):
491 c9064964 Iustin Pop
      raise errors.OpExecError("Could not disable the master role")
492 70d9e3d8 Iustin Pop
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
493 70d9e3d8 Iustin Pop
    utils.CreateBackup(priv_key)
494 70d9e3d8 Iustin Pop
    utils.CreateBackup(pub_key)
495 140aa4a8 Iustin Pop
    return master
496 a8083063 Iustin Pop
497 a8083063 Iustin Pop
498 d8fff41c Guido Trotter
class LUVerifyCluster(LogicalUnit):
499 a8083063 Iustin Pop
  """Verifies the cluster status.
500 a8083063 Iustin Pop

501 a8083063 Iustin Pop
  """
502 d8fff41c Guido Trotter
  HPATH = "cluster-verify"
503 d8fff41c Guido Trotter
  HTYPE = constants.HTYPE_CLUSTER
504 e54c4c5e Guido Trotter
  _OP_REQP = ["skip_checks"]
505 d4b9d97f Guido Trotter
  REQ_BGL = False
506 d4b9d97f Guido Trotter
507 d4b9d97f Guido Trotter
  def ExpandNames(self):
508 d4b9d97f Guido Trotter
    self.needed_locks = {
509 d4b9d97f Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
510 d4b9d97f Guido Trotter
      locking.LEVEL_INSTANCE: locking.ALL_SET,
511 d4b9d97f Guido Trotter
    }
512 d4b9d97f Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
513 a8083063 Iustin Pop
514 a8083063 Iustin Pop
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
515 a8083063 Iustin Pop
                  remote_version, feedback_fn):
516 a8083063 Iustin Pop
    """Run multiple tests against a node.
517 a8083063 Iustin Pop

518 a8083063 Iustin Pop
    Test list:
519 a8083063 Iustin Pop
      - compares ganeti version
520 a8083063 Iustin Pop
      - checks vg existance and size > 20G
521 a8083063 Iustin Pop
      - checks config file checksum
522 a8083063 Iustin Pop
      - checks ssh to other nodes
523 a8083063 Iustin Pop

524 a8083063 Iustin Pop
    Args:
525 a8083063 Iustin Pop
      node: name of the node to check
526 a8083063 Iustin Pop
      file_list: required list of files
527 a8083063 Iustin Pop
      local_cksum: dictionary of local files and their checksums
528 098c0958 Michael Hanselmann

529 a8083063 Iustin Pop
    """
530 a8083063 Iustin Pop
    # compares ganeti version
531 a8083063 Iustin Pop
    local_version = constants.PROTOCOL_VERSION
532 a8083063 Iustin Pop
    if not remote_version:
533 c840ae6f Guido Trotter
      feedback_fn("  - ERROR: connection to %s failed" % (node))
534 a8083063 Iustin Pop
      return True
535 a8083063 Iustin Pop
536 a8083063 Iustin Pop
    if local_version != remote_version:
537 a8083063 Iustin Pop
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
538 a8083063 Iustin Pop
                      (local_version, node, remote_version))
539 a8083063 Iustin Pop
      return True
540 a8083063 Iustin Pop
541 a8083063 Iustin Pop
    # checks vg existance and size > 20G
542 a8083063 Iustin Pop
543 a8083063 Iustin Pop
    bad = False
544 a8083063 Iustin Pop
    if not vglist:
545 a8083063 Iustin Pop
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
546 a8083063 Iustin Pop
                      (node,))
547 a8083063 Iustin Pop
      bad = True
548 a8083063 Iustin Pop
    else:
549 8d1a2a64 Michael Hanselmann
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
550 8d1a2a64 Michael Hanselmann
                                            constants.MIN_VG_SIZE)
551 a8083063 Iustin Pop
      if vgstatus:
552 a8083063 Iustin Pop
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
553 a8083063 Iustin Pop
        bad = True
554 a8083063 Iustin Pop
555 a8083063 Iustin Pop
    # checks config file checksum
556 a8083063 Iustin Pop
    # checks ssh to any
557 a8083063 Iustin Pop
558 a8083063 Iustin Pop
    if 'filelist' not in node_result:
559 a8083063 Iustin Pop
      bad = True
560 a8083063 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
561 a8083063 Iustin Pop
    else:
562 a8083063 Iustin Pop
      remote_cksum = node_result['filelist']
563 a8083063 Iustin Pop
      for file_name in file_list:
564 a8083063 Iustin Pop
        if file_name not in remote_cksum:
565 a8083063 Iustin Pop
          bad = True
566 a8083063 Iustin Pop
          feedback_fn("  - ERROR: file '%s' missing" % file_name)
567 a8083063 Iustin Pop
        elif remote_cksum[file_name] != local_cksum[file_name]:
568 a8083063 Iustin Pop
          bad = True
569 a8083063 Iustin Pop
          feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
570 a8083063 Iustin Pop
571 a8083063 Iustin Pop
    if 'nodelist' not in node_result:
572 a8083063 Iustin Pop
      bad = True
573 9d4bfc96 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
574 a8083063 Iustin Pop
    else:
575 a8083063 Iustin Pop
      if node_result['nodelist']:
576 a8083063 Iustin Pop
        bad = True
577 a8083063 Iustin Pop
        for node in node_result['nodelist']:
578 9d4bfc96 Iustin Pop
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
579 a8083063 Iustin Pop
                          (node, node_result['nodelist'][node]))
580 9d4bfc96 Iustin Pop
    if 'node-net-test' not in node_result:
581 9d4bfc96 Iustin Pop
      bad = True
582 9d4bfc96 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
583 9d4bfc96 Iustin Pop
    else:
584 9d4bfc96 Iustin Pop
      if node_result['node-net-test']:
585 9d4bfc96 Iustin Pop
        bad = True
586 9d4bfc96 Iustin Pop
        nlist = utils.NiceSort(node_result['node-net-test'].keys())
587 9d4bfc96 Iustin Pop
        for node in nlist:
588 9d4bfc96 Iustin Pop
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
589 9d4bfc96 Iustin Pop
                          (node, node_result['node-net-test'][node]))
590 9d4bfc96 Iustin Pop
591 a8083063 Iustin Pop
    hyp_result = node_result.get('hypervisor', None)
592 a8083063 Iustin Pop
    if hyp_result is not None:
593 a8083063 Iustin Pop
      feedback_fn("  - ERROR: hypervisor verify failure: '%s'" % hyp_result)
594 a8083063 Iustin Pop
    return bad
595 a8083063 Iustin Pop
596 c5705f58 Guido Trotter
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
597 c5705f58 Guido Trotter
                      node_instance, feedback_fn):
598 a8083063 Iustin Pop
    """Verify an instance.
599 a8083063 Iustin Pop

600 a8083063 Iustin Pop
    This function checks to see if the required block devices are
601 a8083063 Iustin Pop
    available on the instance's node.
602 a8083063 Iustin Pop

603 a8083063 Iustin Pop
    """
604 a8083063 Iustin Pop
    bad = False
605 a8083063 Iustin Pop
606 a8083063 Iustin Pop
    node_current = instanceconfig.primary_node
607 a8083063 Iustin Pop
608 a8083063 Iustin Pop
    node_vol_should = {}
609 a8083063 Iustin Pop
    instanceconfig.MapLVsByNode(node_vol_should)
610 a8083063 Iustin Pop
611 a8083063 Iustin Pop
    for node in node_vol_should:
612 a8083063 Iustin Pop
      for volume in node_vol_should[node]:
613 a8083063 Iustin Pop
        if node not in node_vol_is or volume not in node_vol_is[node]:
614 a8083063 Iustin Pop
          feedback_fn("  - ERROR: volume %s missing on node %s" %
615 a8083063 Iustin Pop
                          (volume, node))
616 a8083063 Iustin Pop
          bad = True
617 a8083063 Iustin Pop
618 a8083063 Iustin Pop
    if not instanceconfig.status == 'down':
619 a872dae6 Guido Trotter
      if (node_current not in node_instance or
620 a872dae6 Guido Trotter
          not instance in node_instance[node_current]):
621 a8083063 Iustin Pop
        feedback_fn("  - ERROR: instance %s not running on node %s" %
622 a8083063 Iustin Pop
                        (instance, node_current))
623 a8083063 Iustin Pop
        bad = True
624 a8083063 Iustin Pop
625 a8083063 Iustin Pop
    for node in node_instance:
626 a8083063 Iustin Pop
      if (not node == node_current):
627 a8083063 Iustin Pop
        if instance in node_instance[node]:
628 a8083063 Iustin Pop
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
629 a8083063 Iustin Pop
                          (instance, node))
630 a8083063 Iustin Pop
          bad = True
631 a8083063 Iustin Pop
632 6a438c98 Michael Hanselmann
    return bad
633 a8083063 Iustin Pop
634 a8083063 Iustin Pop
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
635 a8083063 Iustin Pop
    """Verify if there are any unknown volumes in the cluster.
636 a8083063 Iustin Pop

637 a8083063 Iustin Pop
    The .os, .swap and backup volumes are ignored. All other volumes are
638 a8083063 Iustin Pop
    reported as unknown.
639 a8083063 Iustin Pop

640 a8083063 Iustin Pop
    """
641 a8083063 Iustin Pop
    bad = False
642 a8083063 Iustin Pop
643 a8083063 Iustin Pop
    for node in node_vol_is:
644 a8083063 Iustin Pop
      for volume in node_vol_is[node]:
645 a8083063 Iustin Pop
        if node not in node_vol_should or volume not in node_vol_should[node]:
646 a8083063 Iustin Pop
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
647 a8083063 Iustin Pop
                      (volume, node))
648 a8083063 Iustin Pop
          bad = True
649 a8083063 Iustin Pop
    return bad
650 a8083063 Iustin Pop
651 a8083063 Iustin Pop
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
652 a8083063 Iustin Pop
    """Verify the list of running instances.
653 a8083063 Iustin Pop

654 a8083063 Iustin Pop
    This checks what instances are running but unknown to the cluster.
655 a8083063 Iustin Pop

656 a8083063 Iustin Pop
    """
657 a8083063 Iustin Pop
    bad = False
658 a8083063 Iustin Pop
    for node in node_instance:
659 a8083063 Iustin Pop
      for runninginstance in node_instance[node]:
660 a8083063 Iustin Pop
        if runninginstance not in instancelist:
661 a8083063 Iustin Pop
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
662 a8083063 Iustin Pop
                          (runninginstance, node))
663 a8083063 Iustin Pop
          bad = True
664 a8083063 Iustin Pop
    return bad
665 a8083063 Iustin Pop
666 2b3b6ddd Guido Trotter
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
667 2b3b6ddd Guido Trotter
    """Verify N+1 Memory Resilience.
668 2b3b6ddd Guido Trotter

669 2b3b6ddd Guido Trotter
    Check that if one single node dies we can still start all the instances it
670 2b3b6ddd Guido Trotter
    was primary for.
671 2b3b6ddd Guido Trotter

672 2b3b6ddd Guido Trotter
    """
673 2b3b6ddd Guido Trotter
    bad = False
674 2b3b6ddd Guido Trotter
675 2b3b6ddd Guido Trotter
    for node, nodeinfo in node_info.iteritems():
676 2b3b6ddd Guido Trotter
      # This code checks that every node which is now listed as secondary has
677 2b3b6ddd Guido Trotter
      # enough memory to host all instances it is supposed to should a single
678 2b3b6ddd Guido Trotter
      # other node in the cluster fail.
679 2b3b6ddd Guido Trotter
      # FIXME: not ready for failover to an arbitrary node
680 2b3b6ddd Guido Trotter
      # FIXME: does not support file-backed instances
681 2b3b6ddd Guido Trotter
      # WARNING: we currently take into account down instances as well as up
682 2b3b6ddd Guido Trotter
      # ones, considering that even if they're down someone might want to start
683 2b3b6ddd Guido Trotter
      # them even in the event of a node failure.
684 2b3b6ddd Guido Trotter
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
685 2b3b6ddd Guido Trotter
        needed_mem = 0
686 2b3b6ddd Guido Trotter
        for instance in instances:
687 2b3b6ddd Guido Trotter
          needed_mem += instance_cfg[instance].memory
688 2b3b6ddd Guido Trotter
        if nodeinfo['mfree'] < needed_mem:
689 2b3b6ddd Guido Trotter
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
690 2b3b6ddd Guido Trotter
                      " failovers should node %s fail" % (node, prinode))
691 2b3b6ddd Guido Trotter
          bad = True
692 2b3b6ddd Guido Trotter
    return bad
693 2b3b6ddd Guido Trotter
694 a8083063 Iustin Pop
  def CheckPrereq(self):
695 a8083063 Iustin Pop
    """Check prerequisites.
696 a8083063 Iustin Pop

697 e54c4c5e Guido Trotter
    Transform the list of checks we're going to skip into a set and check that
698 e54c4c5e Guido Trotter
    all its members are valid.
699 a8083063 Iustin Pop

700 a8083063 Iustin Pop
    """
701 e54c4c5e Guido Trotter
    self.skip_set = frozenset(self.op.skip_checks)
702 e54c4c5e Guido Trotter
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
703 e54c4c5e Guido Trotter
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
704 a8083063 Iustin Pop
705 d8fff41c Guido Trotter
  def BuildHooksEnv(self):
706 d8fff41c Guido Trotter
    """Build hooks env.
707 d8fff41c Guido Trotter

708 d8fff41c Guido Trotter
    Cluster-Verify hooks just rone in the post phase and their failure makes
709 d8fff41c Guido Trotter
    the output be logged in the verify output and the verification to fail.
710 d8fff41c Guido Trotter

711 d8fff41c Guido Trotter
    """
712 d8fff41c Guido Trotter
    all_nodes = self.cfg.GetNodeList()
713 d8fff41c Guido Trotter
    # TODO: populate the environment with useful information for verify hooks
714 d8fff41c Guido Trotter
    env = {}
715 d8fff41c Guido Trotter
    return env, [], all_nodes
716 d8fff41c Guido Trotter
717 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
718 a8083063 Iustin Pop
    """Verify integrity of cluster, performing various test on nodes.
719 a8083063 Iustin Pop

720 a8083063 Iustin Pop
    """
721 a8083063 Iustin Pop
    bad = False
722 a8083063 Iustin Pop
    feedback_fn("* Verifying global settings")
723 8522ceeb Iustin Pop
    for msg in self.cfg.VerifyConfig():
724 8522ceeb Iustin Pop
      feedback_fn("  - ERROR: %s" % msg)
725 a8083063 Iustin Pop
726 a8083063 Iustin Pop
    vg_name = self.cfg.GetVGName()
727 a8083063 Iustin Pop
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
728 9d4bfc96 Iustin Pop
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
729 a8083063 Iustin Pop
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
730 93e4c50b Guido Trotter
    i_non_redundant = [] # Non redundant instances
731 a8083063 Iustin Pop
    node_volume = {}
732 a8083063 Iustin Pop
    node_instance = {}
733 9c9c7d30 Guido Trotter
    node_info = {}
734 26b6af5e Guido Trotter
    instance_cfg = {}
735 a8083063 Iustin Pop
736 a8083063 Iustin Pop
    # FIXME: verify OS list
737 a8083063 Iustin Pop
    # do local checksums
738 cb91d46e Iustin Pop
    file_names = list(self.sstore.GetFileList())
739 cb91d46e Iustin Pop
    file_names.append(constants.SSL_CERT_FILE)
740 cb91d46e Iustin Pop
    file_names.append(constants.CLUSTER_CONF_FILE)
741 a8083063 Iustin Pop
    local_checksums = utils.FingerprintFiles(file_names)
742 a8083063 Iustin Pop
743 a8083063 Iustin Pop
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
744 a8083063 Iustin Pop
    all_volumeinfo = rpc.call_volume_list(nodelist, vg_name)
745 a8083063 Iustin Pop
    all_instanceinfo = rpc.call_instance_list(nodelist)
746 a8083063 Iustin Pop
    all_vglist = rpc.call_vg_list(nodelist)
747 a8083063 Iustin Pop
    node_verify_param = {
748 a8083063 Iustin Pop
      'filelist': file_names,
749 a8083063 Iustin Pop
      'nodelist': nodelist,
750 a8083063 Iustin Pop
      'hypervisor': None,
751 9d4bfc96 Iustin Pop
      'node-net-test': [(node.name, node.primary_ip, node.secondary_ip)
752 9d4bfc96 Iustin Pop
                        for node in nodeinfo]
753 a8083063 Iustin Pop
      }
754 a8083063 Iustin Pop
    all_nvinfo = rpc.call_node_verify(nodelist, node_verify_param)
755 a8083063 Iustin Pop
    all_rversion = rpc.call_version(nodelist)
756 9c9c7d30 Guido Trotter
    all_ninfo = rpc.call_node_info(nodelist, self.cfg.GetVGName())
757 a8083063 Iustin Pop
758 a8083063 Iustin Pop
    for node in nodelist:
759 a8083063 Iustin Pop
      feedback_fn("* Verifying node %s" % node)
760 a8083063 Iustin Pop
      result = self._VerifyNode(node, file_names, local_checksums,
761 a8083063 Iustin Pop
                                all_vglist[node], all_nvinfo[node],
762 a8083063 Iustin Pop
                                all_rversion[node], feedback_fn)
763 a8083063 Iustin Pop
      bad = bad or result
764 a8083063 Iustin Pop
765 a8083063 Iustin Pop
      # node_volume
766 a8083063 Iustin Pop
      volumeinfo = all_volumeinfo[node]
767 a8083063 Iustin Pop
768 b63ed789 Iustin Pop
      if isinstance(volumeinfo, basestring):
769 b63ed789 Iustin Pop
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
770 b63ed789 Iustin Pop
                    (node, volumeinfo[-400:].encode('string_escape')))
771 b63ed789 Iustin Pop
        bad = True
772 b63ed789 Iustin Pop
        node_volume[node] = {}
773 b63ed789 Iustin Pop
      elif not isinstance(volumeinfo, dict):
774 a8083063 Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
775 a8083063 Iustin Pop
        bad = True
776 a8083063 Iustin Pop
        continue
777 b63ed789 Iustin Pop
      else:
778 b63ed789 Iustin Pop
        node_volume[node] = volumeinfo
779 a8083063 Iustin Pop
780 a8083063 Iustin Pop
      # node_instance
781 a8083063 Iustin Pop
      nodeinstance = all_instanceinfo[node]
782 a8083063 Iustin Pop
      if type(nodeinstance) != list:
783 a8083063 Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
784 a8083063 Iustin Pop
        bad = True
785 a8083063 Iustin Pop
        continue
786 a8083063 Iustin Pop
787 a8083063 Iustin Pop
      node_instance[node] = nodeinstance
788 a8083063 Iustin Pop
789 9c9c7d30 Guido Trotter
      # node_info
790 9c9c7d30 Guido Trotter
      nodeinfo = all_ninfo[node]
791 9c9c7d30 Guido Trotter
      if not isinstance(nodeinfo, dict):
792 9c9c7d30 Guido Trotter
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
793 9c9c7d30 Guido Trotter
        bad = True
794 9c9c7d30 Guido Trotter
        continue
795 9c9c7d30 Guido Trotter
796 9c9c7d30 Guido Trotter
      try:
797 9c9c7d30 Guido Trotter
        node_info[node] = {
798 9c9c7d30 Guido Trotter
          "mfree": int(nodeinfo['memory_free']),
799 9c9c7d30 Guido Trotter
          "dfree": int(nodeinfo['vg_free']),
800 93e4c50b Guido Trotter
          "pinst": [],
801 93e4c50b Guido Trotter
          "sinst": [],
802 36e7da50 Guido Trotter
          # dictionary holding all instances this node is secondary for,
803 36e7da50 Guido Trotter
          # grouped by their primary node. Each key is a cluster node, and each
804 36e7da50 Guido Trotter
          # value is a list of instances which have the key as primary and the
805 36e7da50 Guido Trotter
          # current node as secondary.  this is handy to calculate N+1 memory
806 36e7da50 Guido Trotter
          # availability if you can only failover from a primary to its
807 36e7da50 Guido Trotter
          # secondary.
808 36e7da50 Guido Trotter
          "sinst-by-pnode": {},
809 9c9c7d30 Guido Trotter
        }
810 9c9c7d30 Guido Trotter
      except ValueError:
811 9c9c7d30 Guido Trotter
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
812 9c9c7d30 Guido Trotter
        bad = True
813 9c9c7d30 Guido Trotter
        continue
814 9c9c7d30 Guido Trotter
815 a8083063 Iustin Pop
    node_vol_should = {}
816 a8083063 Iustin Pop
817 a8083063 Iustin Pop
    for instance in instancelist:
818 a8083063 Iustin Pop
      feedback_fn("* Verifying instance %s" % instance)
819 a8083063 Iustin Pop
      inst_config = self.cfg.GetInstanceInfo(instance)
820 c5705f58 Guido Trotter
      result =  self._VerifyInstance(instance, inst_config, node_volume,
821 c5705f58 Guido Trotter
                                     node_instance, feedback_fn)
822 c5705f58 Guido Trotter
      bad = bad or result
823 a8083063 Iustin Pop
824 a8083063 Iustin Pop
      inst_config.MapLVsByNode(node_vol_should)
825 a8083063 Iustin Pop
826 26b6af5e Guido Trotter
      instance_cfg[instance] = inst_config
827 26b6af5e Guido Trotter
828 93e4c50b Guido Trotter
      pnode = inst_config.primary_node
829 93e4c50b Guido Trotter
      if pnode in node_info:
830 93e4c50b Guido Trotter
        node_info[pnode]['pinst'].append(instance)
831 93e4c50b Guido Trotter
      else:
832 93e4c50b Guido Trotter
        feedback_fn("  - ERROR: instance %s, connection to primary node"
833 93e4c50b Guido Trotter
                    " %s failed" % (instance, pnode))
834 93e4c50b Guido Trotter
        bad = True
835 93e4c50b Guido Trotter
836 93e4c50b Guido Trotter
      # If the instance is non-redundant we cannot survive losing its primary
837 93e4c50b Guido Trotter
      # node, so we are not N+1 compliant. On the other hand we have no disk
838 93e4c50b Guido Trotter
      # templates with more than one secondary so that situation is not well
839 93e4c50b Guido Trotter
      # supported either.
840 93e4c50b Guido Trotter
      # FIXME: does not support file-backed instances
841 93e4c50b Guido Trotter
      if len(inst_config.secondary_nodes) == 0:
842 93e4c50b Guido Trotter
        i_non_redundant.append(instance)
843 93e4c50b Guido Trotter
      elif len(inst_config.secondary_nodes) > 1:
844 93e4c50b Guido Trotter
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
845 93e4c50b Guido Trotter
                    % instance)
846 93e4c50b Guido Trotter
847 93e4c50b Guido Trotter
      for snode in inst_config.secondary_nodes:
848 93e4c50b Guido Trotter
        if snode in node_info:
849 93e4c50b Guido Trotter
          node_info[snode]['sinst'].append(instance)
850 36e7da50 Guido Trotter
          if pnode not in node_info[snode]['sinst-by-pnode']:
851 36e7da50 Guido Trotter
            node_info[snode]['sinst-by-pnode'][pnode] = []
852 36e7da50 Guido Trotter
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
853 93e4c50b Guido Trotter
        else:
854 93e4c50b Guido Trotter
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
855 93e4c50b Guido Trotter
                      " %s failed" % (instance, snode))
856 93e4c50b Guido Trotter
857 a8083063 Iustin Pop
    feedback_fn("* Verifying orphan volumes")
858 a8083063 Iustin Pop
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
859 a8083063 Iustin Pop
                                       feedback_fn)
860 a8083063 Iustin Pop
    bad = bad or result
861 a8083063 Iustin Pop
862 a8083063 Iustin Pop
    feedback_fn("* Verifying remaining instances")
863 a8083063 Iustin Pop
    result = self._VerifyOrphanInstances(instancelist, node_instance,
864 a8083063 Iustin Pop
                                         feedback_fn)
865 a8083063 Iustin Pop
    bad = bad or result
866 a8083063 Iustin Pop
867 e54c4c5e Guido Trotter
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
868 e54c4c5e Guido Trotter
      feedback_fn("* Verifying N+1 Memory redundancy")
869 e54c4c5e Guido Trotter
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
870 e54c4c5e Guido Trotter
      bad = bad or result
871 2b3b6ddd Guido Trotter
872 2b3b6ddd Guido Trotter
    feedback_fn("* Other Notes")
873 2b3b6ddd Guido Trotter
    if i_non_redundant:
874 2b3b6ddd Guido Trotter
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
875 2b3b6ddd Guido Trotter
                  % len(i_non_redundant))
876 2b3b6ddd Guido Trotter
877 34290825 Michael Hanselmann
    return not bad
878 a8083063 Iustin Pop
879 d8fff41c Guido Trotter
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
880 d8fff41c Guido Trotter
    """Analize the post-hooks' result, handle it, and send some
881 d8fff41c Guido Trotter
    nicely-formatted feedback back to the user.
882 d8fff41c Guido Trotter

883 d8fff41c Guido Trotter
    Args:
884 d8fff41c Guido Trotter
      phase: the hooks phase that has just been run
885 d8fff41c Guido Trotter
      hooks_results: the results of the multi-node hooks rpc call
886 d8fff41c Guido Trotter
      feedback_fn: function to send feedback back to the caller
887 d8fff41c Guido Trotter
      lu_result: previous Exec result
888 d8fff41c Guido Trotter

889 d8fff41c Guido Trotter
    """
890 38206f3c Iustin Pop
    # We only really run POST phase hooks, and are only interested in
891 38206f3c Iustin Pop
    # their results
892 d8fff41c Guido Trotter
    if phase == constants.HOOKS_PHASE_POST:
893 d8fff41c Guido Trotter
      # Used to change hooks' output to proper indentation
894 d8fff41c Guido Trotter
      indent_re = re.compile('^', re.M)
895 d8fff41c Guido Trotter
      feedback_fn("* Hooks Results")
896 d8fff41c Guido Trotter
      if not hooks_results:
897 d8fff41c Guido Trotter
        feedback_fn("  - ERROR: general communication failure")
898 d8fff41c Guido Trotter
        lu_result = 1
899 d8fff41c Guido Trotter
      else:
900 d8fff41c Guido Trotter
        for node_name in hooks_results:
901 d8fff41c Guido Trotter
          show_node_header = True
902 d8fff41c Guido Trotter
          res = hooks_results[node_name]
903 d8fff41c Guido Trotter
          if res is False or not isinstance(res, list):
904 d8fff41c Guido Trotter
            feedback_fn("    Communication failure")
905 d8fff41c Guido Trotter
            lu_result = 1
906 d8fff41c Guido Trotter
            continue
907 d8fff41c Guido Trotter
          for script, hkr, output in res:
908 d8fff41c Guido Trotter
            if hkr == constants.HKR_FAIL:
909 d8fff41c Guido Trotter
              # The node header is only shown once, if there are
910 d8fff41c Guido Trotter
              # failing hooks on that node
911 d8fff41c Guido Trotter
              if show_node_header:
912 d8fff41c Guido Trotter
                feedback_fn("  Node %s:" % node_name)
913 d8fff41c Guido Trotter
                show_node_header = False
914 d8fff41c Guido Trotter
              feedback_fn("    ERROR: Script %s failed, output:" % script)
915 d8fff41c Guido Trotter
              output = indent_re.sub('      ', output)
916 d8fff41c Guido Trotter
              feedback_fn("%s" % output)
917 d8fff41c Guido Trotter
              lu_result = 1
918 d8fff41c Guido Trotter
919 d8fff41c Guido Trotter
      return lu_result
920 d8fff41c Guido Trotter
921 a8083063 Iustin Pop
922 2c95a8d4 Iustin Pop
class LUVerifyDisks(NoHooksLU):
923 2c95a8d4 Iustin Pop
  """Verifies the cluster disks status.
924 2c95a8d4 Iustin Pop

925 2c95a8d4 Iustin Pop
  """
926 2c95a8d4 Iustin Pop
  _OP_REQP = []
927 d4b9d97f Guido Trotter
  REQ_BGL = False
928 d4b9d97f Guido Trotter
929 d4b9d97f Guido Trotter
  def ExpandNames(self):
930 d4b9d97f Guido Trotter
    self.needed_locks = {
931 d4b9d97f Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
932 d4b9d97f Guido Trotter
      locking.LEVEL_INSTANCE: locking.ALL_SET,
933 d4b9d97f Guido Trotter
    }
934 d4b9d97f Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
935 2c95a8d4 Iustin Pop
936 2c95a8d4 Iustin Pop
  def CheckPrereq(self):
937 2c95a8d4 Iustin Pop
    """Check prerequisites.
938 2c95a8d4 Iustin Pop

939 2c95a8d4 Iustin Pop
    This has no prerequisites.
940 2c95a8d4 Iustin Pop

941 2c95a8d4 Iustin Pop
    """
942 2c95a8d4 Iustin Pop
    pass
943 2c95a8d4 Iustin Pop
944 2c95a8d4 Iustin Pop
  def Exec(self, feedback_fn):
945 2c95a8d4 Iustin Pop
    """Verify integrity of cluster disks.
946 2c95a8d4 Iustin Pop

947 2c95a8d4 Iustin Pop
    """
948 b63ed789 Iustin Pop
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
949 2c95a8d4 Iustin Pop
950 2c95a8d4 Iustin Pop
    vg_name = self.cfg.GetVGName()
951 2c95a8d4 Iustin Pop
    nodes = utils.NiceSort(self.cfg.GetNodeList())
952 2c95a8d4 Iustin Pop
    instances = [self.cfg.GetInstanceInfo(name)
953 2c95a8d4 Iustin Pop
                 for name in self.cfg.GetInstanceList()]
954 2c95a8d4 Iustin Pop
955 2c95a8d4 Iustin Pop
    nv_dict = {}
956 2c95a8d4 Iustin Pop
    for inst in instances:
957 2c95a8d4 Iustin Pop
      inst_lvs = {}
958 2c95a8d4 Iustin Pop
      if (inst.status != "up" or
959 2c95a8d4 Iustin Pop
          inst.disk_template not in constants.DTS_NET_MIRROR):
960 2c95a8d4 Iustin Pop
        continue
961 2c95a8d4 Iustin Pop
      inst.MapLVsByNode(inst_lvs)
962 2c95a8d4 Iustin Pop
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
963 2c95a8d4 Iustin Pop
      for node, vol_list in inst_lvs.iteritems():
964 2c95a8d4 Iustin Pop
        for vol in vol_list:
965 2c95a8d4 Iustin Pop
          nv_dict[(node, vol)] = inst
966 2c95a8d4 Iustin Pop
967 2c95a8d4 Iustin Pop
    if not nv_dict:
968 2c95a8d4 Iustin Pop
      return result
969 2c95a8d4 Iustin Pop
970 2c95a8d4 Iustin Pop
    node_lvs = rpc.call_volume_list(nodes, vg_name)
971 2c95a8d4 Iustin Pop
972 2c95a8d4 Iustin Pop
    to_act = set()
973 2c95a8d4 Iustin Pop
    for node in nodes:
974 2c95a8d4 Iustin Pop
      # node_volume
975 2c95a8d4 Iustin Pop
      lvs = node_lvs[node]
976 2c95a8d4 Iustin Pop
977 b63ed789 Iustin Pop
      if isinstance(lvs, basestring):
978 b63ed789 Iustin Pop
        logger.Info("error enumerating LVs on node %s: %s" % (node, lvs))
979 b63ed789 Iustin Pop
        res_nlvm[node] = lvs
980 b63ed789 Iustin Pop
      elif not isinstance(lvs, dict):
981 2c95a8d4 Iustin Pop
        logger.Info("connection to node %s failed or invalid data returned" %
982 2c95a8d4 Iustin Pop
                    (node,))
983 2c95a8d4 Iustin Pop
        res_nodes.append(node)
984 2c95a8d4 Iustin Pop
        continue
985 2c95a8d4 Iustin Pop
986 2c95a8d4 Iustin Pop
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
987 b63ed789 Iustin Pop
        inst = nv_dict.pop((node, lv_name), None)
988 b63ed789 Iustin Pop
        if (not lv_online and inst is not None
989 b63ed789 Iustin Pop
            and inst.name not in res_instances):
990 b08d5a87 Iustin Pop
          res_instances.append(inst.name)
991 2c95a8d4 Iustin Pop
992 b63ed789 Iustin Pop
    # any leftover items in nv_dict are missing LVs, let's arrange the
993 b63ed789 Iustin Pop
    # data better
994 b63ed789 Iustin Pop
    for key, inst in nv_dict.iteritems():
995 b63ed789 Iustin Pop
      if inst.name not in res_missing:
996 b63ed789 Iustin Pop
        res_missing[inst.name] = []
997 b63ed789 Iustin Pop
      res_missing[inst.name].append(key)
998 b63ed789 Iustin Pop
999 2c95a8d4 Iustin Pop
    return result
1000 2c95a8d4 Iustin Pop
1001 2c95a8d4 Iustin Pop
1002 07bd8a51 Iustin Pop
class LURenameCluster(LogicalUnit):
1003 07bd8a51 Iustin Pop
  """Rename the cluster.
1004 07bd8a51 Iustin Pop

1005 07bd8a51 Iustin Pop
  """
1006 07bd8a51 Iustin Pop
  HPATH = "cluster-rename"
1007 07bd8a51 Iustin Pop
  HTYPE = constants.HTYPE_CLUSTER
1008 07bd8a51 Iustin Pop
  _OP_REQP = ["name"]
1009 05f86716 Guido Trotter
  REQ_WSSTORE = True
1010 07bd8a51 Iustin Pop
1011 07bd8a51 Iustin Pop
  def BuildHooksEnv(self):
1012 07bd8a51 Iustin Pop
    """Build hooks env.
1013 07bd8a51 Iustin Pop

1014 07bd8a51 Iustin Pop
    """
1015 07bd8a51 Iustin Pop
    env = {
1016 488b540d Iustin Pop
      "OP_TARGET": self.sstore.GetClusterName(),
1017 07bd8a51 Iustin Pop
      "NEW_NAME": self.op.name,
1018 07bd8a51 Iustin Pop
      }
1019 07bd8a51 Iustin Pop
    mn = self.sstore.GetMasterNode()
1020 07bd8a51 Iustin Pop
    return env, [mn], [mn]
1021 07bd8a51 Iustin Pop
1022 07bd8a51 Iustin Pop
  def CheckPrereq(self):
1023 07bd8a51 Iustin Pop
    """Verify that the passed name is a valid one.
1024 07bd8a51 Iustin Pop

1025 07bd8a51 Iustin Pop
    """
1026 89e1fc26 Iustin Pop
    hostname = utils.HostInfo(self.op.name)
1027 07bd8a51 Iustin Pop
1028 bcf043c9 Iustin Pop
    new_name = hostname.name
1029 bcf043c9 Iustin Pop
    self.ip = new_ip = hostname.ip
1030 07bd8a51 Iustin Pop
    old_name = self.sstore.GetClusterName()
1031 07bd8a51 Iustin Pop
    old_ip = self.sstore.GetMasterIP()
1032 07bd8a51 Iustin Pop
    if new_name == old_name and new_ip == old_ip:
1033 07bd8a51 Iustin Pop
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1034 07bd8a51 Iustin Pop
                                 " cluster has changed")
1035 07bd8a51 Iustin Pop
    if new_ip != old_ip:
1036 937f983d Guido Trotter
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1037 07bd8a51 Iustin Pop
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1038 07bd8a51 Iustin Pop
                                   " reachable on the network. Aborting." %
1039 07bd8a51 Iustin Pop
                                   new_ip)
1040 07bd8a51 Iustin Pop
1041 07bd8a51 Iustin Pop
    self.op.name = new_name
1042 07bd8a51 Iustin Pop
1043 07bd8a51 Iustin Pop
  def Exec(self, feedback_fn):
1044 07bd8a51 Iustin Pop
    """Rename the cluster.
1045 07bd8a51 Iustin Pop

1046 07bd8a51 Iustin Pop
    """
1047 07bd8a51 Iustin Pop
    clustername = self.op.name
1048 07bd8a51 Iustin Pop
    ip = self.ip
1049 07bd8a51 Iustin Pop
    ss = self.sstore
1050 07bd8a51 Iustin Pop
1051 07bd8a51 Iustin Pop
    # shutdown the master IP
1052 07bd8a51 Iustin Pop
    master = ss.GetMasterNode()
1053 1c65840b Iustin Pop
    if not rpc.call_node_stop_master(master, False):
1054 07bd8a51 Iustin Pop
      raise errors.OpExecError("Could not disable the master role")
1055 07bd8a51 Iustin Pop
1056 07bd8a51 Iustin Pop
    try:
1057 07bd8a51 Iustin Pop
      # modify the sstore
1058 07bd8a51 Iustin Pop
      ss.SetKey(ss.SS_MASTER_IP, ip)
1059 07bd8a51 Iustin Pop
      ss.SetKey(ss.SS_CLUSTER_NAME, clustername)
1060 07bd8a51 Iustin Pop
1061 07bd8a51 Iustin Pop
      # Distribute updated ss config to all nodes
1062 07bd8a51 Iustin Pop
      myself = self.cfg.GetNodeInfo(master)
1063 07bd8a51 Iustin Pop
      dist_nodes = self.cfg.GetNodeList()
1064 07bd8a51 Iustin Pop
      if myself.name in dist_nodes:
1065 07bd8a51 Iustin Pop
        dist_nodes.remove(myself.name)
1066 07bd8a51 Iustin Pop
1067 07bd8a51 Iustin Pop
      logger.Debug("Copying updated ssconf data to all nodes")
1068 07bd8a51 Iustin Pop
      for keyname in [ss.SS_CLUSTER_NAME, ss.SS_MASTER_IP]:
1069 07bd8a51 Iustin Pop
        fname = ss.KeyToFilename(keyname)
1070 07bd8a51 Iustin Pop
        result = rpc.call_upload_file(dist_nodes, fname)
1071 07bd8a51 Iustin Pop
        for to_node in dist_nodes:
1072 07bd8a51 Iustin Pop
          if not result[to_node]:
1073 07bd8a51 Iustin Pop
            logger.Error("copy of file %s to node %s failed" %
1074 07bd8a51 Iustin Pop
                         (fname, to_node))
1075 07bd8a51 Iustin Pop
    finally:
1076 1c65840b Iustin Pop
      if not rpc.call_node_start_master(master, False):
1077 f4bc1f2c Michael Hanselmann
        logger.Error("Could not re-enable the master role on the master,"
1078 f4bc1f2c Michael Hanselmann
                     " please restart manually.")
1079 07bd8a51 Iustin Pop
1080 07bd8a51 Iustin Pop
1081 8084f9f6 Manuel Franceschini
def _RecursiveCheckIfLVMBased(disk):
1082 8084f9f6 Manuel Franceschini
  """Check if the given disk or its children are lvm-based.
1083 8084f9f6 Manuel Franceschini

1084 8084f9f6 Manuel Franceschini
  Args:
1085 8084f9f6 Manuel Franceschini
    disk: ganeti.objects.Disk object
1086 8084f9f6 Manuel Franceschini

1087 8084f9f6 Manuel Franceschini
  Returns:
1088 8084f9f6 Manuel Franceschini
    boolean indicating whether a LD_LV dev_type was found or not
1089 8084f9f6 Manuel Franceschini

1090 8084f9f6 Manuel Franceschini
  """
1091 8084f9f6 Manuel Franceschini
  if disk.children:
1092 8084f9f6 Manuel Franceschini
    for chdisk in disk.children:
1093 8084f9f6 Manuel Franceschini
      if _RecursiveCheckIfLVMBased(chdisk):
1094 8084f9f6 Manuel Franceschini
        return True
1095 8084f9f6 Manuel Franceschini
  return disk.dev_type == constants.LD_LV
1096 8084f9f6 Manuel Franceschini
1097 8084f9f6 Manuel Franceschini
1098 8084f9f6 Manuel Franceschini
class LUSetClusterParams(LogicalUnit):
1099 8084f9f6 Manuel Franceschini
  """Change the parameters of the cluster.
1100 8084f9f6 Manuel Franceschini

1101 8084f9f6 Manuel Franceschini
  """
1102 8084f9f6 Manuel Franceschini
  HPATH = "cluster-modify"
1103 8084f9f6 Manuel Franceschini
  HTYPE = constants.HTYPE_CLUSTER
1104 8084f9f6 Manuel Franceschini
  _OP_REQP = []
1105 c53279cf Guido Trotter
  REQ_BGL = False
1106 c53279cf Guido Trotter
1107 c53279cf Guido Trotter
  def ExpandNames(self):
1108 c53279cf Guido Trotter
    # FIXME: in the future maybe other cluster params won't require checking on
1109 c53279cf Guido Trotter
    # all nodes to be modified.
1110 c53279cf Guido Trotter
    self.needed_locks = {
1111 c53279cf Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
1112 c53279cf Guido Trotter
    }
1113 c53279cf Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1114 8084f9f6 Manuel Franceschini
1115 8084f9f6 Manuel Franceschini
  def BuildHooksEnv(self):
1116 8084f9f6 Manuel Franceschini
    """Build hooks env.
1117 8084f9f6 Manuel Franceschini

1118 8084f9f6 Manuel Franceschini
    """
1119 8084f9f6 Manuel Franceschini
    env = {
1120 8084f9f6 Manuel Franceschini
      "OP_TARGET": self.sstore.GetClusterName(),
1121 8084f9f6 Manuel Franceschini
      "NEW_VG_NAME": self.op.vg_name,
1122 8084f9f6 Manuel Franceschini
      }
1123 8084f9f6 Manuel Franceschini
    mn = self.sstore.GetMasterNode()
1124 8084f9f6 Manuel Franceschini
    return env, [mn], [mn]
1125 8084f9f6 Manuel Franceschini
1126 8084f9f6 Manuel Franceschini
  def CheckPrereq(self):
1127 8084f9f6 Manuel Franceschini
    """Check prerequisites.
1128 8084f9f6 Manuel Franceschini

1129 8084f9f6 Manuel Franceschini
    This checks whether the given params don't conflict and
1130 5f83e263 Iustin Pop
    if the given volume group is valid.
1131 8084f9f6 Manuel Franceschini

1132 8084f9f6 Manuel Franceschini
    """
1133 c53279cf Guido Trotter
    # FIXME: This only works because there is only one parameter that can be
1134 c53279cf Guido Trotter
    # changed or removed.
1135 8084f9f6 Manuel Franceschini
    if not self.op.vg_name:
1136 c53279cf Guido Trotter
      instances = self.cfg.GetAllInstancesInfo().values()
1137 8084f9f6 Manuel Franceschini
      for inst in instances:
1138 8084f9f6 Manuel Franceschini
        for disk in inst.disks:
1139 8084f9f6 Manuel Franceschini
          if _RecursiveCheckIfLVMBased(disk):
1140 8084f9f6 Manuel Franceschini
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1141 8084f9f6 Manuel Franceschini
                                       " lvm-based instances exist")
1142 8084f9f6 Manuel Franceschini
1143 8084f9f6 Manuel Franceschini
    # if vg_name not None, checks given volume group on all nodes
1144 8084f9f6 Manuel Franceschini
    if self.op.vg_name:
1145 c53279cf Guido Trotter
      node_list = self.acquired_locks[locking.LEVEL_NODE]
1146 8084f9f6 Manuel Franceschini
      vglist = rpc.call_vg_list(node_list)
1147 8084f9f6 Manuel Franceschini
      for node in node_list:
1148 8d1a2a64 Michael Hanselmann
        vgstatus = utils.CheckVolumeGroupSize(vglist[node], self.op.vg_name,
1149 8d1a2a64 Michael Hanselmann
                                              constants.MIN_VG_SIZE)
1150 8084f9f6 Manuel Franceschini
        if vgstatus:
1151 8084f9f6 Manuel Franceschini
          raise errors.OpPrereqError("Error on node '%s': %s" %
1152 8084f9f6 Manuel Franceschini
                                     (node, vgstatus))
1153 8084f9f6 Manuel Franceschini
1154 8084f9f6 Manuel Franceschini
  def Exec(self, feedback_fn):
1155 8084f9f6 Manuel Franceschini
    """Change the parameters of the cluster.
1156 8084f9f6 Manuel Franceschini

1157 8084f9f6 Manuel Franceschini
    """
1158 8084f9f6 Manuel Franceschini
    if self.op.vg_name != self.cfg.GetVGName():
1159 8084f9f6 Manuel Franceschini
      self.cfg.SetVGName(self.op.vg_name)
1160 8084f9f6 Manuel Franceschini
    else:
1161 8084f9f6 Manuel Franceschini
      feedback_fn("Cluster LVM configuration already in desired"
1162 8084f9f6 Manuel Franceschini
                  " state, not changing")
1163 8084f9f6 Manuel Franceschini
1164 8084f9f6 Manuel Franceschini
1165 5bfac263 Iustin Pop
def _WaitForSync(cfgw, instance, proc, oneshot=False, unlock=False):
1166 a8083063 Iustin Pop
  """Sleep and poll for an instance's disk to sync.
1167 a8083063 Iustin Pop

1168 a8083063 Iustin Pop
  """
1169 a8083063 Iustin Pop
  if not instance.disks:
1170 a8083063 Iustin Pop
    return True
1171 a8083063 Iustin Pop
1172 a8083063 Iustin Pop
  if not oneshot:
1173 5bfac263 Iustin Pop
    proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1174 a8083063 Iustin Pop
1175 a8083063 Iustin Pop
  node = instance.primary_node
1176 a8083063 Iustin Pop
1177 a8083063 Iustin Pop
  for dev in instance.disks:
1178 a8083063 Iustin Pop
    cfgw.SetDiskID(dev, node)
1179 a8083063 Iustin Pop
1180 a8083063 Iustin Pop
  retries = 0
1181 a8083063 Iustin Pop
  while True:
1182 a8083063 Iustin Pop
    max_time = 0
1183 a8083063 Iustin Pop
    done = True
1184 a8083063 Iustin Pop
    cumul_degraded = False
1185 a8083063 Iustin Pop
    rstats = rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1186 a8083063 Iustin Pop
    if not rstats:
1187 5bfac263 Iustin Pop
      proc.LogWarning("Can't get any data from node %s" % node)
1188 a8083063 Iustin Pop
      retries += 1
1189 a8083063 Iustin Pop
      if retries >= 10:
1190 3ecf6786 Iustin Pop
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1191 3ecf6786 Iustin Pop
                                 " aborting." % node)
1192 a8083063 Iustin Pop
      time.sleep(6)
1193 a8083063 Iustin Pop
      continue
1194 a8083063 Iustin Pop
    retries = 0
1195 a8083063 Iustin Pop
    for i in range(len(rstats)):
1196 a8083063 Iustin Pop
      mstat = rstats[i]
1197 a8083063 Iustin Pop
      if mstat is None:
1198 5bfac263 Iustin Pop
        proc.LogWarning("Can't compute data for node %s/%s" %
1199 a8083063 Iustin Pop
                        (node, instance.disks[i].iv_name))
1200 a8083063 Iustin Pop
        continue
1201 0834c866 Iustin Pop
      # we ignore the ldisk parameter
1202 0834c866 Iustin Pop
      perc_done, est_time, is_degraded, _ = mstat
1203 a8083063 Iustin Pop
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1204 a8083063 Iustin Pop
      if perc_done is not None:
1205 a8083063 Iustin Pop
        done = False
1206 a8083063 Iustin Pop
        if est_time is not None:
1207 a8083063 Iustin Pop
          rem_time = "%d estimated seconds remaining" % est_time
1208 a8083063 Iustin Pop
          max_time = est_time
1209 a8083063 Iustin Pop
        else:
1210 a8083063 Iustin Pop
          rem_time = "no time estimate"
1211 5bfac263 Iustin Pop
        proc.LogInfo("- device %s: %5.2f%% done, %s" %
1212 5bfac263 Iustin Pop
                     (instance.disks[i].iv_name, perc_done, rem_time))
1213 a8083063 Iustin Pop
    if done or oneshot:
1214 a8083063 Iustin Pop
      break
1215 a8083063 Iustin Pop
1216 d4fa5c23 Iustin Pop
    time.sleep(min(60, max_time))
1217 a8083063 Iustin Pop
1218 a8083063 Iustin Pop
  if done:
1219 5bfac263 Iustin Pop
    proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1220 a8083063 Iustin Pop
  return not cumul_degraded
1221 a8083063 Iustin Pop
1222 a8083063 Iustin Pop
1223 0834c866 Iustin Pop
def _CheckDiskConsistency(cfgw, dev, node, on_primary, ldisk=False):
1224 a8083063 Iustin Pop
  """Check that mirrors are not degraded.
1225 a8083063 Iustin Pop

1226 0834c866 Iustin Pop
  The ldisk parameter, if True, will change the test from the
1227 0834c866 Iustin Pop
  is_degraded attribute (which represents overall non-ok status for
1228 0834c866 Iustin Pop
  the device(s)) to the ldisk (representing the local storage status).
1229 0834c866 Iustin Pop

1230 a8083063 Iustin Pop
  """
1231 a8083063 Iustin Pop
  cfgw.SetDiskID(dev, node)
1232 0834c866 Iustin Pop
  if ldisk:
1233 0834c866 Iustin Pop
    idx = 6
1234 0834c866 Iustin Pop
  else:
1235 0834c866 Iustin Pop
    idx = 5
1236 a8083063 Iustin Pop
1237 a8083063 Iustin Pop
  result = True
1238 a8083063 Iustin Pop
  if on_primary or dev.AssembleOnSecondary():
1239 a8083063 Iustin Pop
    rstats = rpc.call_blockdev_find(node, dev)
1240 a8083063 Iustin Pop
    if not rstats:
1241 aa9d0c32 Guido Trotter
      logger.ToStderr("Node %s: Disk degraded, not found or node down" % node)
1242 a8083063 Iustin Pop
      result = False
1243 a8083063 Iustin Pop
    else:
1244 0834c866 Iustin Pop
      result = result and (not rstats[idx])
1245 a8083063 Iustin Pop
  if dev.children:
1246 a8083063 Iustin Pop
    for child in dev.children:
1247 a8083063 Iustin Pop
      result = result and _CheckDiskConsistency(cfgw, child, node, on_primary)
1248 a8083063 Iustin Pop
1249 a8083063 Iustin Pop
  return result
1250 a8083063 Iustin Pop
1251 a8083063 Iustin Pop
1252 a8083063 Iustin Pop
class LUDiagnoseOS(NoHooksLU):
1253 a8083063 Iustin Pop
  """Logical unit for OS diagnose/query.
1254 a8083063 Iustin Pop

1255 a8083063 Iustin Pop
  """
1256 1f9430d6 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1257 6bf01bbb Guido Trotter
  REQ_BGL = False
1258 a8083063 Iustin Pop
1259 6bf01bbb Guido Trotter
  def ExpandNames(self):
1260 1f9430d6 Iustin Pop
    if self.op.names:
1261 1f9430d6 Iustin Pop
      raise errors.OpPrereqError("Selective OS query not supported")
1262 1f9430d6 Iustin Pop
1263 1f9430d6 Iustin Pop
    self.dynamic_fields = frozenset(["name", "valid", "node_status"])
1264 1f9430d6 Iustin Pop
    _CheckOutputFields(static=[],
1265 1f9430d6 Iustin Pop
                       dynamic=self.dynamic_fields,
1266 1f9430d6 Iustin Pop
                       selected=self.op.output_fields)
1267 1f9430d6 Iustin Pop
1268 6bf01bbb Guido Trotter
    # Lock all nodes, in shared mode
1269 6bf01bbb Guido Trotter
    self.needed_locks = {}
1270 6bf01bbb Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1271 e310b019 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1272 6bf01bbb Guido Trotter
1273 6bf01bbb Guido Trotter
  def CheckPrereq(self):
1274 6bf01bbb Guido Trotter
    """Check prerequisites.
1275 6bf01bbb Guido Trotter

1276 6bf01bbb Guido Trotter
    """
1277 6bf01bbb Guido Trotter
1278 1f9430d6 Iustin Pop
  @staticmethod
1279 1f9430d6 Iustin Pop
  def _DiagnoseByOS(node_list, rlist):
1280 1f9430d6 Iustin Pop
    """Remaps a per-node return list into an a per-os per-node dictionary
1281 1f9430d6 Iustin Pop

1282 1f9430d6 Iustin Pop
      Args:
1283 1f9430d6 Iustin Pop
        node_list: a list with the names of all nodes
1284 1f9430d6 Iustin Pop
        rlist: a map with node names as keys and OS objects as values
1285 1f9430d6 Iustin Pop

1286 1f9430d6 Iustin Pop
      Returns:
1287 1f9430d6 Iustin Pop
        map: a map with osnames as keys and as value another map, with
1288 1f9430d6 Iustin Pop
             nodes as
1289 1f9430d6 Iustin Pop
             keys and list of OS objects as values
1290 1f9430d6 Iustin Pop
             e.g. {"debian-etch": {"node1": [<object>,...],
1291 1f9430d6 Iustin Pop
                                   "node2": [<object>,]}
1292 1f9430d6 Iustin Pop
                  }
1293 1f9430d6 Iustin Pop

1294 1f9430d6 Iustin Pop
    """
1295 1f9430d6 Iustin Pop
    all_os = {}
1296 1f9430d6 Iustin Pop
    for node_name, nr in rlist.iteritems():
1297 1f9430d6 Iustin Pop
      if not nr:
1298 1f9430d6 Iustin Pop
        continue
1299 b4de68a9 Iustin Pop
      for os_obj in nr:
1300 b4de68a9 Iustin Pop
        if os_obj.name not in all_os:
1301 1f9430d6 Iustin Pop
          # build a list of nodes for this os containing empty lists
1302 1f9430d6 Iustin Pop
          # for each node in node_list
1303 b4de68a9 Iustin Pop
          all_os[os_obj.name] = {}
1304 1f9430d6 Iustin Pop
          for nname in node_list:
1305 b4de68a9 Iustin Pop
            all_os[os_obj.name][nname] = []
1306 b4de68a9 Iustin Pop
        all_os[os_obj.name][node_name].append(os_obj)
1307 1f9430d6 Iustin Pop
    return all_os
1308 a8083063 Iustin Pop
1309 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1310 a8083063 Iustin Pop
    """Compute the list of OSes.
1311 a8083063 Iustin Pop

1312 a8083063 Iustin Pop
    """
1313 6bf01bbb Guido Trotter
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1314 a8083063 Iustin Pop
    node_data = rpc.call_os_diagnose(node_list)
1315 a8083063 Iustin Pop
    if node_data == False:
1316 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't gather the list of OSes")
1317 1f9430d6 Iustin Pop
    pol = self._DiagnoseByOS(node_list, node_data)
1318 1f9430d6 Iustin Pop
    output = []
1319 1f9430d6 Iustin Pop
    for os_name, os_data in pol.iteritems():
1320 1f9430d6 Iustin Pop
      row = []
1321 1f9430d6 Iustin Pop
      for field in self.op.output_fields:
1322 1f9430d6 Iustin Pop
        if field == "name":
1323 1f9430d6 Iustin Pop
          val = os_name
1324 1f9430d6 Iustin Pop
        elif field == "valid":
1325 1f9430d6 Iustin Pop
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1326 1f9430d6 Iustin Pop
        elif field == "node_status":
1327 1f9430d6 Iustin Pop
          val = {}
1328 1f9430d6 Iustin Pop
          for node_name, nos_list in os_data.iteritems():
1329 1f9430d6 Iustin Pop
            val[node_name] = [(v.status, v.path) for v in nos_list]
1330 1f9430d6 Iustin Pop
        else:
1331 1f9430d6 Iustin Pop
          raise errors.ParameterError(field)
1332 1f9430d6 Iustin Pop
        row.append(val)
1333 1f9430d6 Iustin Pop
      output.append(row)
1334 1f9430d6 Iustin Pop
1335 1f9430d6 Iustin Pop
    return output
1336 a8083063 Iustin Pop
1337 a8083063 Iustin Pop
1338 a8083063 Iustin Pop
class LURemoveNode(LogicalUnit):
1339 a8083063 Iustin Pop
  """Logical unit for removing a node.
1340 a8083063 Iustin Pop

1341 a8083063 Iustin Pop
  """
1342 a8083063 Iustin Pop
  HPATH = "node-remove"
1343 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1344 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1345 a8083063 Iustin Pop
1346 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1347 a8083063 Iustin Pop
    """Build hooks env.
1348 a8083063 Iustin Pop

1349 a8083063 Iustin Pop
    This doesn't run on the target node in the pre phase as a failed
1350 d08869ee Guido Trotter
    node would then be impossible to remove.
1351 a8083063 Iustin Pop

1352 a8083063 Iustin Pop
    """
1353 396e1b78 Michael Hanselmann
    env = {
1354 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1355 396e1b78 Michael Hanselmann
      "NODE_NAME": self.op.node_name,
1356 396e1b78 Michael Hanselmann
      }
1357 a8083063 Iustin Pop
    all_nodes = self.cfg.GetNodeList()
1358 a8083063 Iustin Pop
    all_nodes.remove(self.op.node_name)
1359 396e1b78 Michael Hanselmann
    return env, all_nodes, all_nodes
1360 a8083063 Iustin Pop
1361 a8083063 Iustin Pop
  def CheckPrereq(self):
1362 a8083063 Iustin Pop
    """Check prerequisites.
1363 a8083063 Iustin Pop

1364 a8083063 Iustin Pop
    This checks:
1365 a8083063 Iustin Pop
     - the node exists in the configuration
1366 a8083063 Iustin Pop
     - it does not have primary or secondary instances
1367 a8083063 Iustin Pop
     - it's not the master
1368 a8083063 Iustin Pop

1369 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1370 a8083063 Iustin Pop

1371 a8083063 Iustin Pop
    """
1372 a8083063 Iustin Pop
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1373 a8083063 Iustin Pop
    if node is None:
1374 a02bc76e Iustin Pop
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1375 a8083063 Iustin Pop
1376 a8083063 Iustin Pop
    instance_list = self.cfg.GetInstanceList()
1377 a8083063 Iustin Pop
1378 880478f8 Iustin Pop
    masternode = self.sstore.GetMasterNode()
1379 a8083063 Iustin Pop
    if node.name == masternode:
1380 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node is the master node,"
1381 3ecf6786 Iustin Pop
                                 " you need to failover first.")
1382 a8083063 Iustin Pop
1383 a8083063 Iustin Pop
    for instance_name in instance_list:
1384 a8083063 Iustin Pop
      instance = self.cfg.GetInstanceInfo(instance_name)
1385 a8083063 Iustin Pop
      if node.name == instance.primary_node:
1386 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Instance %s still running on the node,"
1387 3ecf6786 Iustin Pop
                                   " please remove first." % instance_name)
1388 a8083063 Iustin Pop
      if node.name in instance.secondary_nodes:
1389 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1390 3ecf6786 Iustin Pop
                                   " please remove first." % instance_name)
1391 a8083063 Iustin Pop
    self.op.node_name = node.name
1392 a8083063 Iustin Pop
    self.node = node
1393 a8083063 Iustin Pop
1394 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1395 a8083063 Iustin Pop
    """Removes the node from the cluster.
1396 a8083063 Iustin Pop

1397 a8083063 Iustin Pop
    """
1398 a8083063 Iustin Pop
    node = self.node
1399 a8083063 Iustin Pop
    logger.Info("stopping the node daemon and removing configs from node %s" %
1400 a8083063 Iustin Pop
                node.name)
1401 a8083063 Iustin Pop
1402 d8470559 Michael Hanselmann
    self.context.RemoveNode(node.name)
1403 a8083063 Iustin Pop
1404 d8470559 Michael Hanselmann
    rpc.call_node_leave_cluster(node.name)
1405 c8a0948f Michael Hanselmann
1406 a8083063 Iustin Pop
1407 a8083063 Iustin Pop
class LUQueryNodes(NoHooksLU):
1408 a8083063 Iustin Pop
  """Logical unit for querying nodes.
1409 a8083063 Iustin Pop

1410 a8083063 Iustin Pop
  """
1411 246e180a Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1412 35705d8f Guido Trotter
  REQ_BGL = False
1413 a8083063 Iustin Pop
1414 35705d8f Guido Trotter
  def ExpandNames(self):
1415 e8a4c138 Iustin Pop
    self.dynamic_fields = frozenset([
1416 e8a4c138 Iustin Pop
      "dtotal", "dfree",
1417 e8a4c138 Iustin Pop
      "mtotal", "mnode", "mfree",
1418 e8a4c138 Iustin Pop
      "bootid",
1419 e8a4c138 Iustin Pop
      "ctotal",
1420 e8a4c138 Iustin Pop
      ])
1421 a8083063 Iustin Pop
1422 c8d8b4c8 Iustin Pop
    self.static_fields = frozenset([
1423 c8d8b4c8 Iustin Pop
      "name", "pinst_cnt", "sinst_cnt",
1424 c8d8b4c8 Iustin Pop
      "pinst_list", "sinst_list",
1425 c8d8b4c8 Iustin Pop
      "pip", "sip", "tags",
1426 c8d8b4c8 Iustin Pop
      ])
1427 c8d8b4c8 Iustin Pop
1428 c8d8b4c8 Iustin Pop
    _CheckOutputFields(static=self.static_fields,
1429 dcb93971 Michael Hanselmann
                       dynamic=self.dynamic_fields,
1430 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
1431 a8083063 Iustin Pop
1432 35705d8f Guido Trotter
    self.needed_locks = {}
1433 35705d8f Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1434 c8d8b4c8 Iustin Pop
1435 c8d8b4c8 Iustin Pop
    if self.op.names:
1436 c8d8b4c8 Iustin Pop
      self.wanted = _GetWantedNodes(self, self.op.names)
1437 35705d8f Guido Trotter
    else:
1438 c8d8b4c8 Iustin Pop
      self.wanted = locking.ALL_SET
1439 c8d8b4c8 Iustin Pop
1440 c8d8b4c8 Iustin Pop
    self.do_locking = not self.static_fields.issuperset(self.op.output_fields)
1441 c8d8b4c8 Iustin Pop
    if self.do_locking:
1442 c8d8b4c8 Iustin Pop
      # if we don't request only static fields, we need to lock the nodes
1443 c8d8b4c8 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1444 c8d8b4c8 Iustin Pop
1445 35705d8f Guido Trotter
1446 35705d8f Guido Trotter
  def CheckPrereq(self):
1447 35705d8f Guido Trotter
    """Check prerequisites.
1448 35705d8f Guido Trotter

1449 35705d8f Guido Trotter
    """
1450 c8d8b4c8 Iustin Pop
    # The validation of the node list is done in the _GetWantedNodes,
1451 c8d8b4c8 Iustin Pop
    # if non empty, and if empty, there's no validation to do
1452 c8d8b4c8 Iustin Pop
    pass
1453 a8083063 Iustin Pop
1454 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1455 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
1456 a8083063 Iustin Pop

1457 a8083063 Iustin Pop
    """
1458 c8d8b4c8 Iustin Pop
    all_info = self.cfg.GetAllNodesInfo()
1459 c8d8b4c8 Iustin Pop
    if self.do_locking:
1460 c8d8b4c8 Iustin Pop
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1461 3fa93523 Guido Trotter
    elif self.wanted != locking.ALL_SET:
1462 3fa93523 Guido Trotter
      nodenames = self.wanted
1463 3fa93523 Guido Trotter
      missing = set(nodenames).difference(all_info.keys())
1464 3fa93523 Guido Trotter
      if missing:
1465 3fa93523 Guido Trotter
        raise self.OpExecError(
1466 3fa93523 Guido Trotter
          "Some nodes were removed before retrieving their data: %s" % missing)
1467 c8d8b4c8 Iustin Pop
    else:
1468 c8d8b4c8 Iustin Pop
      nodenames = all_info.keys()
1469 c8d8b4c8 Iustin Pop
    nodelist = [all_info[name] for name in nodenames]
1470 a8083063 Iustin Pop
1471 a8083063 Iustin Pop
    # begin data gathering
1472 a8083063 Iustin Pop
1473 a8083063 Iustin Pop
    if self.dynamic_fields.intersection(self.op.output_fields):
1474 a8083063 Iustin Pop
      live_data = {}
1475 a8083063 Iustin Pop
      node_data = rpc.call_node_info(nodenames, self.cfg.GetVGName())
1476 a8083063 Iustin Pop
      for name in nodenames:
1477 a8083063 Iustin Pop
        nodeinfo = node_data.get(name, None)
1478 a8083063 Iustin Pop
        if nodeinfo:
1479 a8083063 Iustin Pop
          live_data[name] = {
1480 a8083063 Iustin Pop
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1481 a8083063 Iustin Pop
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1482 a8083063 Iustin Pop
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1483 a8083063 Iustin Pop
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1484 a8083063 Iustin Pop
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1485 e8a4c138 Iustin Pop
            "ctotal": utils.TryConvert(int, nodeinfo['cpu_total']),
1486 3ef10550 Michael Hanselmann
            "bootid": nodeinfo['bootid'],
1487 a8083063 Iustin Pop
            }
1488 a8083063 Iustin Pop
        else:
1489 a8083063 Iustin Pop
          live_data[name] = {}
1490 a8083063 Iustin Pop
    else:
1491 a8083063 Iustin Pop
      live_data = dict.fromkeys(nodenames, {})
1492 a8083063 Iustin Pop
1493 ec223efb Iustin Pop
    node_to_primary = dict([(name, set()) for name in nodenames])
1494 ec223efb Iustin Pop
    node_to_secondary = dict([(name, set()) for name in nodenames])
1495 a8083063 Iustin Pop
1496 ec223efb Iustin Pop
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1497 ec223efb Iustin Pop
                             "sinst_cnt", "sinst_list"))
1498 ec223efb Iustin Pop
    if inst_fields & frozenset(self.op.output_fields):
1499 a8083063 Iustin Pop
      instancelist = self.cfg.GetInstanceList()
1500 a8083063 Iustin Pop
1501 ec223efb Iustin Pop
      for instance_name in instancelist:
1502 ec223efb Iustin Pop
        inst = self.cfg.GetInstanceInfo(instance_name)
1503 ec223efb Iustin Pop
        if inst.primary_node in node_to_primary:
1504 ec223efb Iustin Pop
          node_to_primary[inst.primary_node].add(inst.name)
1505 ec223efb Iustin Pop
        for secnode in inst.secondary_nodes:
1506 ec223efb Iustin Pop
          if secnode in node_to_secondary:
1507 ec223efb Iustin Pop
            node_to_secondary[secnode].add(inst.name)
1508 a8083063 Iustin Pop
1509 a8083063 Iustin Pop
    # end data gathering
1510 a8083063 Iustin Pop
1511 a8083063 Iustin Pop
    output = []
1512 a8083063 Iustin Pop
    for node in nodelist:
1513 a8083063 Iustin Pop
      node_output = []
1514 a8083063 Iustin Pop
      for field in self.op.output_fields:
1515 a8083063 Iustin Pop
        if field == "name":
1516 a8083063 Iustin Pop
          val = node.name
1517 ec223efb Iustin Pop
        elif field == "pinst_list":
1518 ec223efb Iustin Pop
          val = list(node_to_primary[node.name])
1519 ec223efb Iustin Pop
        elif field == "sinst_list":
1520 ec223efb Iustin Pop
          val = list(node_to_secondary[node.name])
1521 ec223efb Iustin Pop
        elif field == "pinst_cnt":
1522 ec223efb Iustin Pop
          val = len(node_to_primary[node.name])
1523 ec223efb Iustin Pop
        elif field == "sinst_cnt":
1524 ec223efb Iustin Pop
          val = len(node_to_secondary[node.name])
1525 a8083063 Iustin Pop
        elif field == "pip":
1526 a8083063 Iustin Pop
          val = node.primary_ip
1527 a8083063 Iustin Pop
        elif field == "sip":
1528 a8083063 Iustin Pop
          val = node.secondary_ip
1529 130a6a6f Iustin Pop
        elif field == "tags":
1530 130a6a6f Iustin Pop
          val = list(node.GetTags())
1531 a8083063 Iustin Pop
        elif field in self.dynamic_fields:
1532 ec223efb Iustin Pop
          val = live_data[node.name].get(field, None)
1533 a8083063 Iustin Pop
        else:
1534 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
1535 a8083063 Iustin Pop
        node_output.append(val)
1536 a8083063 Iustin Pop
      output.append(node_output)
1537 a8083063 Iustin Pop
1538 a8083063 Iustin Pop
    return output
1539 a8083063 Iustin Pop
1540 a8083063 Iustin Pop
1541 dcb93971 Michael Hanselmann
class LUQueryNodeVolumes(NoHooksLU):
1542 dcb93971 Michael Hanselmann
  """Logical unit for getting volumes on node(s).
1543 dcb93971 Michael Hanselmann

1544 dcb93971 Michael Hanselmann
  """
1545 dcb93971 Michael Hanselmann
  _OP_REQP = ["nodes", "output_fields"]
1546 21a15682 Guido Trotter
  REQ_BGL = False
1547 21a15682 Guido Trotter
1548 21a15682 Guido Trotter
  def ExpandNames(self):
1549 21a15682 Guido Trotter
    _CheckOutputFields(static=["node"],
1550 21a15682 Guido Trotter
                       dynamic=["phys", "vg", "name", "size", "instance"],
1551 21a15682 Guido Trotter
                       selected=self.op.output_fields)
1552 21a15682 Guido Trotter
1553 21a15682 Guido Trotter
    self.needed_locks = {}
1554 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1555 21a15682 Guido Trotter
    if not self.op.nodes:
1556 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1557 21a15682 Guido Trotter
    else:
1558 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
1559 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
1560 dcb93971 Michael Hanselmann
1561 dcb93971 Michael Hanselmann
  def CheckPrereq(self):
1562 dcb93971 Michael Hanselmann
    """Check prerequisites.
1563 dcb93971 Michael Hanselmann

1564 dcb93971 Michael Hanselmann
    This checks that the fields required are valid output fields.
1565 dcb93971 Michael Hanselmann

1566 dcb93971 Michael Hanselmann
    """
1567 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1568 dcb93971 Michael Hanselmann
1569 dcb93971 Michael Hanselmann
  def Exec(self, feedback_fn):
1570 dcb93971 Michael Hanselmann
    """Computes the list of nodes and their attributes.
1571 dcb93971 Michael Hanselmann

1572 dcb93971 Michael Hanselmann
    """
1573 a7ba5e53 Iustin Pop
    nodenames = self.nodes
1574 dcb93971 Michael Hanselmann
    volumes = rpc.call_node_volumes(nodenames)
1575 dcb93971 Michael Hanselmann
1576 dcb93971 Michael Hanselmann
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1577 dcb93971 Michael Hanselmann
             in self.cfg.GetInstanceList()]
1578 dcb93971 Michael Hanselmann
1579 dcb93971 Michael Hanselmann
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1580 dcb93971 Michael Hanselmann
1581 dcb93971 Michael Hanselmann
    output = []
1582 dcb93971 Michael Hanselmann
    for node in nodenames:
1583 37d19eb2 Michael Hanselmann
      if node not in volumes or not volumes[node]:
1584 37d19eb2 Michael Hanselmann
        continue
1585 37d19eb2 Michael Hanselmann
1586 dcb93971 Michael Hanselmann
      node_vols = volumes[node][:]
1587 dcb93971 Michael Hanselmann
      node_vols.sort(key=lambda vol: vol['dev'])
1588 dcb93971 Michael Hanselmann
1589 dcb93971 Michael Hanselmann
      for vol in node_vols:
1590 dcb93971 Michael Hanselmann
        node_output = []
1591 dcb93971 Michael Hanselmann
        for field in self.op.output_fields:
1592 dcb93971 Michael Hanselmann
          if field == "node":
1593 dcb93971 Michael Hanselmann
            val = node
1594 dcb93971 Michael Hanselmann
          elif field == "phys":
1595 dcb93971 Michael Hanselmann
            val = vol['dev']
1596 dcb93971 Michael Hanselmann
          elif field == "vg":
1597 dcb93971 Michael Hanselmann
            val = vol['vg']
1598 dcb93971 Michael Hanselmann
          elif field == "name":
1599 dcb93971 Michael Hanselmann
            val = vol['name']
1600 dcb93971 Michael Hanselmann
          elif field == "size":
1601 dcb93971 Michael Hanselmann
            val = int(float(vol['size']))
1602 dcb93971 Michael Hanselmann
          elif field == "instance":
1603 dcb93971 Michael Hanselmann
            for inst in ilist:
1604 dcb93971 Michael Hanselmann
              if node not in lv_by_node[inst]:
1605 dcb93971 Michael Hanselmann
                continue
1606 dcb93971 Michael Hanselmann
              if vol['name'] in lv_by_node[inst][node]:
1607 dcb93971 Michael Hanselmann
                val = inst.name
1608 dcb93971 Michael Hanselmann
                break
1609 dcb93971 Michael Hanselmann
            else:
1610 dcb93971 Michael Hanselmann
              val = '-'
1611 dcb93971 Michael Hanselmann
          else:
1612 3ecf6786 Iustin Pop
            raise errors.ParameterError(field)
1613 dcb93971 Michael Hanselmann
          node_output.append(str(val))
1614 dcb93971 Michael Hanselmann
1615 dcb93971 Michael Hanselmann
        output.append(node_output)
1616 dcb93971 Michael Hanselmann
1617 dcb93971 Michael Hanselmann
    return output
1618 dcb93971 Michael Hanselmann
1619 dcb93971 Michael Hanselmann
1620 a8083063 Iustin Pop
class LUAddNode(LogicalUnit):
1621 a8083063 Iustin Pop
  """Logical unit for adding node to the cluster.
1622 a8083063 Iustin Pop

1623 a8083063 Iustin Pop
  """
1624 a8083063 Iustin Pop
  HPATH = "node-add"
1625 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1626 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1627 a8083063 Iustin Pop
1628 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1629 a8083063 Iustin Pop
    """Build hooks env.
1630 a8083063 Iustin Pop

1631 a8083063 Iustin Pop
    This will run on all nodes before, and on all nodes + the new node after.
1632 a8083063 Iustin Pop

1633 a8083063 Iustin Pop
    """
1634 a8083063 Iustin Pop
    env = {
1635 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1636 a8083063 Iustin Pop
      "NODE_NAME": self.op.node_name,
1637 a8083063 Iustin Pop
      "NODE_PIP": self.op.primary_ip,
1638 a8083063 Iustin Pop
      "NODE_SIP": self.op.secondary_ip,
1639 a8083063 Iustin Pop
      }
1640 a8083063 Iustin Pop
    nodes_0 = self.cfg.GetNodeList()
1641 a8083063 Iustin Pop
    nodes_1 = nodes_0 + [self.op.node_name, ]
1642 a8083063 Iustin Pop
    return env, nodes_0, nodes_1
1643 a8083063 Iustin Pop
1644 a8083063 Iustin Pop
  def CheckPrereq(self):
1645 a8083063 Iustin Pop
    """Check prerequisites.
1646 a8083063 Iustin Pop

1647 a8083063 Iustin Pop
    This checks:
1648 a8083063 Iustin Pop
     - the new node is not already in the config
1649 a8083063 Iustin Pop
     - it is resolvable
1650 a8083063 Iustin Pop
     - its parameters (single/dual homed) matches the cluster
1651 a8083063 Iustin Pop

1652 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1653 a8083063 Iustin Pop

1654 a8083063 Iustin Pop
    """
1655 a8083063 Iustin Pop
    node_name = self.op.node_name
1656 a8083063 Iustin Pop
    cfg = self.cfg
1657 a8083063 Iustin Pop
1658 89e1fc26 Iustin Pop
    dns_data = utils.HostInfo(node_name)
1659 a8083063 Iustin Pop
1660 bcf043c9 Iustin Pop
    node = dns_data.name
1661 bcf043c9 Iustin Pop
    primary_ip = self.op.primary_ip = dns_data.ip
1662 a8083063 Iustin Pop
    secondary_ip = getattr(self.op, "secondary_ip", None)
1663 a8083063 Iustin Pop
    if secondary_ip is None:
1664 a8083063 Iustin Pop
      secondary_ip = primary_ip
1665 a8083063 Iustin Pop
    if not utils.IsValidIP(secondary_ip):
1666 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid secondary IP given")
1667 a8083063 Iustin Pop
    self.op.secondary_ip = secondary_ip
1668 e7c6e02b Michael Hanselmann
1669 a8083063 Iustin Pop
    node_list = cfg.GetNodeList()
1670 e7c6e02b Michael Hanselmann
    if not self.op.readd and node in node_list:
1671 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1672 e7c6e02b Michael Hanselmann
                                 node)
1673 e7c6e02b Michael Hanselmann
    elif self.op.readd and node not in node_list:
1674 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1675 a8083063 Iustin Pop
1676 a8083063 Iustin Pop
    for existing_node_name in node_list:
1677 a8083063 Iustin Pop
      existing_node = cfg.GetNodeInfo(existing_node_name)
1678 e7c6e02b Michael Hanselmann
1679 e7c6e02b Michael Hanselmann
      if self.op.readd and node == existing_node_name:
1680 e7c6e02b Michael Hanselmann
        if (existing_node.primary_ip != primary_ip or
1681 e7c6e02b Michael Hanselmann
            existing_node.secondary_ip != secondary_ip):
1682 e7c6e02b Michael Hanselmann
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
1683 e7c6e02b Michael Hanselmann
                                     " address configuration as before")
1684 e7c6e02b Michael Hanselmann
        continue
1685 e7c6e02b Michael Hanselmann
1686 a8083063 Iustin Pop
      if (existing_node.primary_ip == primary_ip or
1687 a8083063 Iustin Pop
          existing_node.secondary_ip == primary_ip or
1688 a8083063 Iustin Pop
          existing_node.primary_ip == secondary_ip or
1689 a8083063 Iustin Pop
          existing_node.secondary_ip == secondary_ip):
1690 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1691 3ecf6786 Iustin Pop
                                   " existing node %s" % existing_node.name)
1692 a8083063 Iustin Pop
1693 a8083063 Iustin Pop
    # check that the type of the node (single versus dual homed) is the
1694 a8083063 Iustin Pop
    # same as for the master
1695 880478f8 Iustin Pop
    myself = cfg.GetNodeInfo(self.sstore.GetMasterNode())
1696 a8083063 Iustin Pop
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1697 a8083063 Iustin Pop
    newbie_singlehomed = secondary_ip == primary_ip
1698 a8083063 Iustin Pop
    if master_singlehomed != newbie_singlehomed:
1699 a8083063 Iustin Pop
      if master_singlehomed:
1700 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has no private ip but the"
1701 3ecf6786 Iustin Pop
                                   " new node has one")
1702 a8083063 Iustin Pop
      else:
1703 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has a private ip but the"
1704 3ecf6786 Iustin Pop
                                   " new node doesn't have one")
1705 a8083063 Iustin Pop
1706 a8083063 Iustin Pop
    # checks reachablity
1707 b15d625f Iustin Pop
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
1708 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node not reachable by ping")
1709 a8083063 Iustin Pop
1710 a8083063 Iustin Pop
    if not newbie_singlehomed:
1711 a8083063 Iustin Pop
      # check reachability from my secondary ip to newbie's secondary ip
1712 b15d625f Iustin Pop
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
1713 b15d625f Iustin Pop
                           source=myself.secondary_ip):
1714 f4bc1f2c Michael Hanselmann
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
1715 f4bc1f2c Michael Hanselmann
                                   " based ping to noded port")
1716 a8083063 Iustin Pop
1717 a8083063 Iustin Pop
    self.new_node = objects.Node(name=node,
1718 a8083063 Iustin Pop
                                 primary_ip=primary_ip,
1719 a8083063 Iustin Pop
                                 secondary_ip=secondary_ip)
1720 a8083063 Iustin Pop
1721 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1722 a8083063 Iustin Pop
    """Adds the new node to the cluster.
1723 a8083063 Iustin Pop

1724 a8083063 Iustin Pop
    """
1725 a8083063 Iustin Pop
    new_node = self.new_node
1726 a8083063 Iustin Pop
    node = new_node.name
1727 a8083063 Iustin Pop
1728 a8083063 Iustin Pop
    # check connectivity
1729 a8083063 Iustin Pop
    result = rpc.call_version([node])[node]
1730 a8083063 Iustin Pop
    if result:
1731 a8083063 Iustin Pop
      if constants.PROTOCOL_VERSION == result:
1732 a8083063 Iustin Pop
        logger.Info("communication to node %s fine, sw version %s match" %
1733 a8083063 Iustin Pop
                    (node, result))
1734 a8083063 Iustin Pop
      else:
1735 3ecf6786 Iustin Pop
        raise errors.OpExecError("Version mismatch master version %s,"
1736 3ecf6786 Iustin Pop
                                 " node version %s" %
1737 3ecf6786 Iustin Pop
                                 (constants.PROTOCOL_VERSION, result))
1738 a8083063 Iustin Pop
    else:
1739 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot get version from the new node")
1740 a8083063 Iustin Pop
1741 a8083063 Iustin Pop
    # setup ssh on node
1742 a8083063 Iustin Pop
    logger.Info("copy ssh key to node %s" % node)
1743 70d9e3d8 Iustin Pop
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1744 a8083063 Iustin Pop
    keyarray = []
1745 70d9e3d8 Iustin Pop
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
1746 70d9e3d8 Iustin Pop
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
1747 70d9e3d8 Iustin Pop
                priv_key, pub_key]
1748 a8083063 Iustin Pop
1749 a8083063 Iustin Pop
    for i in keyfiles:
1750 a8083063 Iustin Pop
      f = open(i, 'r')
1751 a8083063 Iustin Pop
      try:
1752 a8083063 Iustin Pop
        keyarray.append(f.read())
1753 a8083063 Iustin Pop
      finally:
1754 a8083063 Iustin Pop
        f.close()
1755 a8083063 Iustin Pop
1756 a8083063 Iustin Pop
    result = rpc.call_node_add(node, keyarray[0], keyarray[1], keyarray[2],
1757 a8083063 Iustin Pop
                               keyarray[3], keyarray[4], keyarray[5])
1758 a8083063 Iustin Pop
1759 a8083063 Iustin Pop
    if not result:
1760 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
1761 a8083063 Iustin Pop
1762 a8083063 Iustin Pop
    # Add node to our /etc/hosts, and add key to known_hosts
1763 d9c02ca6 Michael Hanselmann
    utils.AddHostToEtcHosts(new_node.name)
1764 c8a0948f Michael Hanselmann
1765 a8083063 Iustin Pop
    if new_node.secondary_ip != new_node.primary_ip:
1766 16abfbc2 Alexander Schreiber
      if not rpc.call_node_tcp_ping(new_node.name,
1767 16abfbc2 Alexander Schreiber
                                    constants.LOCALHOST_IP_ADDRESS,
1768 16abfbc2 Alexander Schreiber
                                    new_node.secondary_ip,
1769 16abfbc2 Alexander Schreiber
                                    constants.DEFAULT_NODED_PORT,
1770 16abfbc2 Alexander Schreiber
                                    10, False):
1771 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
1772 f4bc1f2c Michael Hanselmann
                                 " you gave (%s). Please fix and re-run this"
1773 f4bc1f2c Michael Hanselmann
                                 " command." % new_node.secondary_ip)
1774 a8083063 Iustin Pop
1775 5c0527ed Guido Trotter
    node_verify_list = [self.sstore.GetMasterNode()]
1776 5c0527ed Guido Trotter
    node_verify_param = {
1777 5c0527ed Guido Trotter
      'nodelist': [node],
1778 5c0527ed Guido Trotter
      # TODO: do a node-net-test as well?
1779 5c0527ed Guido Trotter
    }
1780 5c0527ed Guido Trotter
1781 5c0527ed Guido Trotter
    result = rpc.call_node_verify(node_verify_list, node_verify_param)
1782 5c0527ed Guido Trotter
    for verifier in node_verify_list:
1783 5c0527ed Guido Trotter
      if not result[verifier]:
1784 5c0527ed Guido Trotter
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
1785 5c0527ed Guido Trotter
                                 " for remote verification" % verifier)
1786 5c0527ed Guido Trotter
      if result[verifier]['nodelist']:
1787 5c0527ed Guido Trotter
        for failed in result[verifier]['nodelist']:
1788 5c0527ed Guido Trotter
          feedback_fn("ssh/hostname verification failed %s -> %s" %
1789 5c0527ed Guido Trotter
                      (verifier, result[verifier]['nodelist'][failed]))
1790 5c0527ed Guido Trotter
        raise errors.OpExecError("ssh/hostname verification failed.")
1791 ff98055b Iustin Pop
1792 a8083063 Iustin Pop
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1793 a8083063 Iustin Pop
    # including the node just added
1794 880478f8 Iustin Pop
    myself = self.cfg.GetNodeInfo(self.sstore.GetMasterNode())
1795 102b115b Michael Hanselmann
    dist_nodes = self.cfg.GetNodeList()
1796 102b115b Michael Hanselmann
    if not self.op.readd:
1797 102b115b Michael Hanselmann
      dist_nodes.append(node)
1798 a8083063 Iustin Pop
    if myself.name in dist_nodes:
1799 a8083063 Iustin Pop
      dist_nodes.remove(myself.name)
1800 a8083063 Iustin Pop
1801 a8083063 Iustin Pop
    logger.Debug("Copying hosts and known_hosts to all nodes")
1802 107711b0 Michael Hanselmann
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
1803 a8083063 Iustin Pop
      result = rpc.call_upload_file(dist_nodes, fname)
1804 a8083063 Iustin Pop
      for to_node in dist_nodes:
1805 a8083063 Iustin Pop
        if not result[to_node]:
1806 a8083063 Iustin Pop
          logger.Error("copy of file %s to node %s failed" %
1807 a8083063 Iustin Pop
                       (fname, to_node))
1808 a8083063 Iustin Pop
1809 3d1e7706 Guido Trotter
    to_copy = self.sstore.GetFileList()
1810 2a6469d5 Alexander Schreiber
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
1811 2a6469d5 Alexander Schreiber
      to_copy.append(constants.VNC_PASSWORD_FILE)
1812 a8083063 Iustin Pop
    for fname in to_copy:
1813 b5602d15 Guido Trotter
      result = rpc.call_upload_file([node], fname)
1814 b5602d15 Guido Trotter
      if not result[node]:
1815 a8083063 Iustin Pop
        logger.Error("could not copy file %s to node %s" % (fname, node))
1816 a8083063 Iustin Pop
1817 d8470559 Michael Hanselmann
    if self.op.readd:
1818 d8470559 Michael Hanselmann
      self.context.ReaddNode(new_node)
1819 d8470559 Michael Hanselmann
    else:
1820 d8470559 Michael Hanselmann
      self.context.AddNode(new_node)
1821 a8083063 Iustin Pop
1822 a8083063 Iustin Pop
1823 a8083063 Iustin Pop
class LUQueryClusterInfo(NoHooksLU):
1824 a8083063 Iustin Pop
  """Query cluster configuration.
1825 a8083063 Iustin Pop

1826 a8083063 Iustin Pop
  """
1827 a8083063 Iustin Pop
  _OP_REQP = []
1828 59322403 Iustin Pop
  REQ_MASTER = False
1829 642339cf Guido Trotter
  REQ_BGL = False
1830 642339cf Guido Trotter
1831 642339cf Guido Trotter
  def ExpandNames(self):
1832 642339cf Guido Trotter
    self.needed_locks = {}
1833 a8083063 Iustin Pop
1834 a8083063 Iustin Pop
  def CheckPrereq(self):
1835 a8083063 Iustin Pop
    """No prerequsites needed for this LU.
1836 a8083063 Iustin Pop

1837 a8083063 Iustin Pop
    """
1838 a8083063 Iustin Pop
    pass
1839 a8083063 Iustin Pop
1840 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1841 a8083063 Iustin Pop
    """Return cluster config.
1842 a8083063 Iustin Pop

1843 a8083063 Iustin Pop
    """
1844 a8083063 Iustin Pop
    result = {
1845 5fcdc80d Iustin Pop
      "name": self.sstore.GetClusterName(),
1846 a8083063 Iustin Pop
      "software_version": constants.RELEASE_VERSION,
1847 a8083063 Iustin Pop
      "protocol_version": constants.PROTOCOL_VERSION,
1848 a8083063 Iustin Pop
      "config_version": constants.CONFIG_VERSION,
1849 a8083063 Iustin Pop
      "os_api_version": constants.OS_API_VERSION,
1850 a8083063 Iustin Pop
      "export_version": constants.EXPORT_VERSION,
1851 880478f8 Iustin Pop
      "master": self.sstore.GetMasterNode(),
1852 a8083063 Iustin Pop
      "architecture": (platform.architecture()[0], platform.machine()),
1853 8a12ce45 Iustin Pop
      "hypervisor_type": self.sstore.GetHypervisorType(),
1854 a8083063 Iustin Pop
      }
1855 a8083063 Iustin Pop
1856 a8083063 Iustin Pop
    return result
1857 a8083063 Iustin Pop
1858 a8083063 Iustin Pop
1859 a8083063 Iustin Pop
class LUDumpClusterConfig(NoHooksLU):
1860 a8083063 Iustin Pop
  """Return a text-representation of the cluster-config.
1861 a8083063 Iustin Pop

1862 a8083063 Iustin Pop
  """
1863 a8083063 Iustin Pop
  _OP_REQP = []
1864 642339cf Guido Trotter
  REQ_BGL = False
1865 642339cf Guido Trotter
1866 642339cf Guido Trotter
  def ExpandNames(self):
1867 642339cf Guido Trotter
    self.needed_locks = {}
1868 a8083063 Iustin Pop
1869 a8083063 Iustin Pop
  def CheckPrereq(self):
1870 a8083063 Iustin Pop
    """No prerequisites.
1871 a8083063 Iustin Pop

1872 a8083063 Iustin Pop
    """
1873 a8083063 Iustin Pop
    pass
1874 a8083063 Iustin Pop
1875 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1876 a8083063 Iustin Pop
    """Dump a representation of the cluster config to the standard output.
1877 a8083063 Iustin Pop

1878 a8083063 Iustin Pop
    """
1879 a8083063 Iustin Pop
    return self.cfg.DumpConfig()
1880 a8083063 Iustin Pop
1881 a8083063 Iustin Pop
1882 a8083063 Iustin Pop
class LUActivateInstanceDisks(NoHooksLU):
1883 a8083063 Iustin Pop
  """Bring up an instance's disks.
1884 a8083063 Iustin Pop

1885 a8083063 Iustin Pop
  """
1886 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
1887 f22a8ba3 Guido Trotter
  REQ_BGL = False
1888 f22a8ba3 Guido Trotter
1889 f22a8ba3 Guido Trotter
  def ExpandNames(self):
1890 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
1891 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
1892 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1893 f22a8ba3 Guido Trotter
1894 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
1895 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
1896 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
1897 a8083063 Iustin Pop
1898 a8083063 Iustin Pop
  def CheckPrereq(self):
1899 a8083063 Iustin Pop
    """Check prerequisites.
1900 a8083063 Iustin Pop

1901 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
1902 a8083063 Iustin Pop

1903 a8083063 Iustin Pop
    """
1904 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
1905 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
1906 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
1907 a8083063 Iustin Pop
1908 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1909 a8083063 Iustin Pop
    """Activate the disks.
1910 a8083063 Iustin Pop

1911 a8083063 Iustin Pop
    """
1912 a8083063 Iustin Pop
    disks_ok, disks_info = _AssembleInstanceDisks(self.instance, self.cfg)
1913 a8083063 Iustin Pop
    if not disks_ok:
1914 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot activate block devices")
1915 a8083063 Iustin Pop
1916 a8083063 Iustin Pop
    return disks_info
1917 a8083063 Iustin Pop
1918 a8083063 Iustin Pop
1919 a8083063 Iustin Pop
def _AssembleInstanceDisks(instance, cfg, ignore_secondaries=False):
1920 a8083063 Iustin Pop
  """Prepare the block devices for an instance.
1921 a8083063 Iustin Pop

1922 a8083063 Iustin Pop
  This sets up the block devices on all nodes.
1923 a8083063 Iustin Pop

1924 a8083063 Iustin Pop
  Args:
1925 a8083063 Iustin Pop
    instance: a ganeti.objects.Instance object
1926 a8083063 Iustin Pop
    ignore_secondaries: if true, errors on secondary nodes won't result
1927 a8083063 Iustin Pop
                        in an error return from the function
1928 a8083063 Iustin Pop

1929 a8083063 Iustin Pop
  Returns:
1930 a8083063 Iustin Pop
    false if the operation failed
1931 a8083063 Iustin Pop
    list of (host, instance_visible_name, node_visible_name) if the operation
1932 a8083063 Iustin Pop
         suceeded with the mapping from node devices to instance devices
1933 a8083063 Iustin Pop
  """
1934 a8083063 Iustin Pop
  device_info = []
1935 a8083063 Iustin Pop
  disks_ok = True
1936 fdbd668d Iustin Pop
  iname = instance.name
1937 fdbd668d Iustin Pop
  # With the two passes mechanism we try to reduce the window of
1938 fdbd668d Iustin Pop
  # opportunity for the race condition of switching DRBD to primary
1939 fdbd668d Iustin Pop
  # before handshaking occured, but we do not eliminate it
1940 fdbd668d Iustin Pop
1941 fdbd668d Iustin Pop
  # The proper fix would be to wait (with some limits) until the
1942 fdbd668d Iustin Pop
  # connection has been made and drbd transitions from WFConnection
1943 fdbd668d Iustin Pop
  # into any other network-connected state (Connected, SyncTarget,
1944 fdbd668d Iustin Pop
  # SyncSource, etc.)
1945 fdbd668d Iustin Pop
1946 fdbd668d Iustin Pop
  # 1st pass, assemble on all nodes in secondary mode
1947 a8083063 Iustin Pop
  for inst_disk in instance.disks:
1948 a8083063 Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1949 a8083063 Iustin Pop
      cfg.SetDiskID(node_disk, node)
1950 fdbd668d Iustin Pop
      result = rpc.call_blockdev_assemble(node, node_disk, iname, False)
1951 a8083063 Iustin Pop
      if not result:
1952 f4bc1f2c Michael Hanselmann
        logger.Error("could not prepare block device %s on node %s"
1953 fdbd668d Iustin Pop
                     " (is_primary=False, pass=1)" % (inst_disk.iv_name, node))
1954 fdbd668d Iustin Pop
        if not ignore_secondaries:
1955 a8083063 Iustin Pop
          disks_ok = False
1956 fdbd668d Iustin Pop
1957 fdbd668d Iustin Pop
  # FIXME: race condition on drbd migration to primary
1958 fdbd668d Iustin Pop
1959 fdbd668d Iustin Pop
  # 2nd pass, do only the primary node
1960 fdbd668d Iustin Pop
  for inst_disk in instance.disks:
1961 fdbd668d Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1962 fdbd668d Iustin Pop
      if node != instance.primary_node:
1963 fdbd668d Iustin Pop
        continue
1964 fdbd668d Iustin Pop
      cfg.SetDiskID(node_disk, node)
1965 fdbd668d Iustin Pop
      result = rpc.call_blockdev_assemble(node, node_disk, iname, True)
1966 fdbd668d Iustin Pop
      if not result:
1967 fdbd668d Iustin Pop
        logger.Error("could not prepare block device %s on node %s"
1968 fdbd668d Iustin Pop
                     " (is_primary=True, pass=2)" % (inst_disk.iv_name, node))
1969 fdbd668d Iustin Pop
        disks_ok = False
1970 fdbd668d Iustin Pop
    device_info.append((instance.primary_node, inst_disk.iv_name, result))
1971 a8083063 Iustin Pop
1972 b352ab5b Iustin Pop
  # leave the disks configured for the primary node
1973 b352ab5b Iustin Pop
  # this is a workaround that would be fixed better by
1974 b352ab5b Iustin Pop
  # improving the logical/physical id handling
1975 b352ab5b Iustin Pop
  for disk in instance.disks:
1976 b352ab5b Iustin Pop
    cfg.SetDiskID(disk, instance.primary_node)
1977 b352ab5b Iustin Pop
1978 a8083063 Iustin Pop
  return disks_ok, device_info
1979 a8083063 Iustin Pop
1980 a8083063 Iustin Pop
1981 fe7b0351 Michael Hanselmann
def _StartInstanceDisks(cfg, instance, force):
1982 3ecf6786 Iustin Pop
  """Start the disks of an instance.
1983 3ecf6786 Iustin Pop

1984 3ecf6786 Iustin Pop
  """
1985 fe7b0351 Michael Hanselmann
  disks_ok, dummy = _AssembleInstanceDisks(instance, cfg,
1986 fe7b0351 Michael Hanselmann
                                           ignore_secondaries=force)
1987 fe7b0351 Michael Hanselmann
  if not disks_ok:
1988 fe7b0351 Michael Hanselmann
    _ShutdownInstanceDisks(instance, cfg)
1989 fe7b0351 Michael Hanselmann
    if force is not None and not force:
1990 fe7b0351 Michael Hanselmann
      logger.Error("If the message above refers to a secondary node,"
1991 fe7b0351 Michael Hanselmann
                   " you can retry the operation using '--force'.")
1992 3ecf6786 Iustin Pop
    raise errors.OpExecError("Disk consistency error")
1993 fe7b0351 Michael Hanselmann
1994 fe7b0351 Michael Hanselmann
1995 a8083063 Iustin Pop
class LUDeactivateInstanceDisks(NoHooksLU):
1996 a8083063 Iustin Pop
  """Shutdown an instance's disks.
1997 a8083063 Iustin Pop

1998 a8083063 Iustin Pop
  """
1999 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2000 f22a8ba3 Guido Trotter
  REQ_BGL = False
2001 f22a8ba3 Guido Trotter
2002 f22a8ba3 Guido Trotter
  def ExpandNames(self):
2003 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
2004 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2005 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2006 f22a8ba3 Guido Trotter
2007 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
2008 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
2009 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
2010 a8083063 Iustin Pop
2011 a8083063 Iustin Pop
  def CheckPrereq(self):
2012 a8083063 Iustin Pop
    """Check prerequisites.
2013 a8083063 Iustin Pop

2014 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2015 a8083063 Iustin Pop

2016 a8083063 Iustin Pop
    """
2017 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2018 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
2019 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2020 a8083063 Iustin Pop
2021 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2022 a8083063 Iustin Pop
    """Deactivate the disks
2023 a8083063 Iustin Pop

2024 a8083063 Iustin Pop
    """
2025 a8083063 Iustin Pop
    instance = self.instance
2026 155d6c75 Guido Trotter
    _SafeShutdownInstanceDisks(instance, self.cfg)
2027 a8083063 Iustin Pop
2028 a8083063 Iustin Pop
2029 155d6c75 Guido Trotter
def _SafeShutdownInstanceDisks(instance, cfg):
2030 155d6c75 Guido Trotter
  """Shutdown block devices of an instance.
2031 155d6c75 Guido Trotter

2032 155d6c75 Guido Trotter
  This function checks if an instance is running, before calling
2033 155d6c75 Guido Trotter
  _ShutdownInstanceDisks.
2034 155d6c75 Guido Trotter

2035 155d6c75 Guido Trotter
  """
2036 155d6c75 Guido Trotter
  ins_l = rpc.call_instance_list([instance.primary_node])
2037 155d6c75 Guido Trotter
  ins_l = ins_l[instance.primary_node]
2038 155d6c75 Guido Trotter
  if not type(ins_l) is list:
2039 155d6c75 Guido Trotter
    raise errors.OpExecError("Can't contact node '%s'" %
2040 155d6c75 Guido Trotter
                             instance.primary_node)
2041 155d6c75 Guido Trotter
2042 155d6c75 Guido Trotter
  if instance.name in ins_l:
2043 155d6c75 Guido Trotter
    raise errors.OpExecError("Instance is running, can't shutdown"
2044 155d6c75 Guido Trotter
                             " block devices.")
2045 155d6c75 Guido Trotter
2046 155d6c75 Guido Trotter
  _ShutdownInstanceDisks(instance, cfg)
2047 a8083063 Iustin Pop
2048 a8083063 Iustin Pop
2049 a8083063 Iustin Pop
def _ShutdownInstanceDisks(instance, cfg, ignore_primary=False):
2050 a8083063 Iustin Pop
  """Shutdown block devices of an instance.
2051 a8083063 Iustin Pop

2052 a8083063 Iustin Pop
  This does the shutdown on all nodes of the instance.
2053 a8083063 Iustin Pop

2054 a8083063 Iustin Pop
  If the ignore_primary is false, errors on the primary node are
2055 a8083063 Iustin Pop
  ignored.
2056 a8083063 Iustin Pop

2057 a8083063 Iustin Pop
  """
2058 a8083063 Iustin Pop
  result = True
2059 a8083063 Iustin Pop
  for disk in instance.disks:
2060 a8083063 Iustin Pop
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2061 a8083063 Iustin Pop
      cfg.SetDiskID(top_disk, node)
2062 a8083063 Iustin Pop
      if not rpc.call_blockdev_shutdown(node, top_disk):
2063 a8083063 Iustin Pop
        logger.Error("could not shutdown block device %s on node %s" %
2064 a8083063 Iustin Pop
                     (disk.iv_name, node))
2065 a8083063 Iustin Pop
        if not ignore_primary or node != instance.primary_node:
2066 a8083063 Iustin Pop
          result = False
2067 a8083063 Iustin Pop
  return result
2068 a8083063 Iustin Pop
2069 a8083063 Iustin Pop
2070 d4f16fd9 Iustin Pop
def _CheckNodeFreeMemory(cfg, node, reason, requested):
2071 d4f16fd9 Iustin Pop
  """Checks if a node has enough free memory.
2072 d4f16fd9 Iustin Pop

2073 d4f16fd9 Iustin Pop
  This function check if a given node has the needed amount of free
2074 d4f16fd9 Iustin Pop
  memory. In case the node has less memory or we cannot get the
2075 d4f16fd9 Iustin Pop
  information from the node, this function raise an OpPrereqError
2076 d4f16fd9 Iustin Pop
  exception.
2077 d4f16fd9 Iustin Pop

2078 d4f16fd9 Iustin Pop
  Args:
2079 d4f16fd9 Iustin Pop
    - cfg: a ConfigWriter instance
2080 d4f16fd9 Iustin Pop
    - node: the node name
2081 d4f16fd9 Iustin Pop
    - reason: string to use in the error message
2082 d4f16fd9 Iustin Pop
    - requested: the amount of memory in MiB
2083 d4f16fd9 Iustin Pop

2084 d4f16fd9 Iustin Pop
  """
2085 d4f16fd9 Iustin Pop
  nodeinfo = rpc.call_node_info([node], cfg.GetVGName())
2086 d4f16fd9 Iustin Pop
  if not nodeinfo or not isinstance(nodeinfo, dict):
2087 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Could not contact node %s for resource"
2088 d4f16fd9 Iustin Pop
                             " information" % (node,))
2089 d4f16fd9 Iustin Pop
2090 d4f16fd9 Iustin Pop
  free_mem = nodeinfo[node].get('memory_free')
2091 d4f16fd9 Iustin Pop
  if not isinstance(free_mem, int):
2092 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2093 d4f16fd9 Iustin Pop
                             " was '%s'" % (node, free_mem))
2094 d4f16fd9 Iustin Pop
  if requested > free_mem:
2095 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2096 d4f16fd9 Iustin Pop
                             " needed %s MiB, available %s MiB" %
2097 d4f16fd9 Iustin Pop
                             (node, reason, requested, free_mem))
2098 d4f16fd9 Iustin Pop
2099 d4f16fd9 Iustin Pop
2100 a8083063 Iustin Pop
class LUStartupInstance(LogicalUnit):
2101 a8083063 Iustin Pop
  """Starts an instance.
2102 a8083063 Iustin Pop

2103 a8083063 Iustin Pop
  """
2104 a8083063 Iustin Pop
  HPATH = "instance-start"
2105 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2106 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "force"]
2107 e873317a Guido Trotter
  REQ_BGL = False
2108 e873317a Guido Trotter
2109 e873317a Guido Trotter
  def ExpandNames(self):
2110 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2111 e873317a Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2112 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2113 e873317a Guido Trotter
2114 e873317a Guido Trotter
  def DeclareLocks(self, level):
2115 e873317a Guido Trotter
    if level == locking.LEVEL_NODE:
2116 e873317a Guido Trotter
      self._LockInstancesNodes()
2117 a8083063 Iustin Pop
2118 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2119 a8083063 Iustin Pop
    """Build hooks env.
2120 a8083063 Iustin Pop

2121 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2122 a8083063 Iustin Pop

2123 a8083063 Iustin Pop
    """
2124 a8083063 Iustin Pop
    env = {
2125 a8083063 Iustin Pop
      "FORCE": self.op.force,
2126 a8083063 Iustin Pop
      }
2127 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2128 880478f8 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2129 a8083063 Iustin Pop
          list(self.instance.secondary_nodes))
2130 a8083063 Iustin Pop
    return env, nl, nl
2131 a8083063 Iustin Pop
2132 a8083063 Iustin Pop
  def CheckPrereq(self):
2133 a8083063 Iustin Pop
    """Check prerequisites.
2134 a8083063 Iustin Pop

2135 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2136 a8083063 Iustin Pop

2137 a8083063 Iustin Pop
    """
2138 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2139 e873317a Guido Trotter
    assert self.instance is not None, \
2140 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2141 a8083063 Iustin Pop
2142 a8083063 Iustin Pop
    # check bridges existance
2143 bf6929a2 Alexander Schreiber
    _CheckInstanceBridgesExist(instance)
2144 a8083063 Iustin Pop
2145 d4f16fd9 Iustin Pop
    _CheckNodeFreeMemory(self.cfg, instance.primary_node,
2146 d4f16fd9 Iustin Pop
                         "starting instance %s" % instance.name,
2147 d4f16fd9 Iustin Pop
                         instance.memory)
2148 d4f16fd9 Iustin Pop
2149 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2150 a8083063 Iustin Pop
    """Start the instance.
2151 a8083063 Iustin Pop

2152 a8083063 Iustin Pop
    """
2153 a8083063 Iustin Pop
    instance = self.instance
2154 a8083063 Iustin Pop
    force = self.op.force
2155 a8083063 Iustin Pop
    extra_args = getattr(self.op, "extra_args", "")
2156 a8083063 Iustin Pop
2157 fe482621 Iustin Pop
    self.cfg.MarkInstanceUp(instance.name)
2158 fe482621 Iustin Pop
2159 a8083063 Iustin Pop
    node_current = instance.primary_node
2160 a8083063 Iustin Pop
2161 fe7b0351 Michael Hanselmann
    _StartInstanceDisks(self.cfg, instance, force)
2162 a8083063 Iustin Pop
2163 a8083063 Iustin Pop
    if not rpc.call_instance_start(node_current, instance, extra_args):
2164 a8083063 Iustin Pop
      _ShutdownInstanceDisks(instance, self.cfg)
2165 3ecf6786 Iustin Pop
      raise errors.OpExecError("Could not start instance")
2166 a8083063 Iustin Pop
2167 a8083063 Iustin Pop
2168 bf6929a2 Alexander Schreiber
class LURebootInstance(LogicalUnit):
2169 bf6929a2 Alexander Schreiber
  """Reboot an instance.
2170 bf6929a2 Alexander Schreiber

2171 bf6929a2 Alexander Schreiber
  """
2172 bf6929a2 Alexander Schreiber
  HPATH = "instance-reboot"
2173 bf6929a2 Alexander Schreiber
  HTYPE = constants.HTYPE_INSTANCE
2174 bf6929a2 Alexander Schreiber
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2175 e873317a Guido Trotter
  REQ_BGL = False
2176 e873317a Guido Trotter
2177 e873317a Guido Trotter
  def ExpandNames(self):
2178 0fcc5db3 Guido Trotter
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2179 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
2180 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL]:
2181 0fcc5db3 Guido Trotter
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2182 0fcc5db3 Guido Trotter
                                  (constants.INSTANCE_REBOOT_SOFT,
2183 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
2184 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL))
2185 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2186 e873317a Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2187 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2188 e873317a Guido Trotter
2189 e873317a Guido Trotter
  def DeclareLocks(self, level):
2190 e873317a Guido Trotter
    if level == locking.LEVEL_NODE:
2191 849da276 Guido Trotter
      primary_only = not constants.INSTANCE_REBOOT_FULL
2192 849da276 Guido Trotter
      self._LockInstancesNodes(primary_only=primary_only)
2193 bf6929a2 Alexander Schreiber
2194 bf6929a2 Alexander Schreiber
  def BuildHooksEnv(self):
2195 bf6929a2 Alexander Schreiber
    """Build hooks env.
2196 bf6929a2 Alexander Schreiber

2197 bf6929a2 Alexander Schreiber
    This runs on master, primary and secondary nodes of the instance.
2198 bf6929a2 Alexander Schreiber

2199 bf6929a2 Alexander Schreiber
    """
2200 bf6929a2 Alexander Schreiber
    env = {
2201 bf6929a2 Alexander Schreiber
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2202 bf6929a2 Alexander Schreiber
      }
2203 bf6929a2 Alexander Schreiber
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2204 bf6929a2 Alexander Schreiber
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2205 bf6929a2 Alexander Schreiber
          list(self.instance.secondary_nodes))
2206 bf6929a2 Alexander Schreiber
    return env, nl, nl
2207 bf6929a2 Alexander Schreiber
2208 bf6929a2 Alexander Schreiber
  def CheckPrereq(self):
2209 bf6929a2 Alexander Schreiber
    """Check prerequisites.
2210 bf6929a2 Alexander Schreiber

2211 bf6929a2 Alexander Schreiber
    This checks that the instance is in the cluster.
2212 bf6929a2 Alexander Schreiber

2213 bf6929a2 Alexander Schreiber
    """
2214 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2215 e873317a Guido Trotter
    assert self.instance is not None, \
2216 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2217 bf6929a2 Alexander Schreiber
2218 bf6929a2 Alexander Schreiber
    # check bridges existance
2219 bf6929a2 Alexander Schreiber
    _CheckInstanceBridgesExist(instance)
2220 bf6929a2 Alexander Schreiber
2221 bf6929a2 Alexander Schreiber
  def Exec(self, feedback_fn):
2222 bf6929a2 Alexander Schreiber
    """Reboot the instance.
2223 bf6929a2 Alexander Schreiber

2224 bf6929a2 Alexander Schreiber
    """
2225 bf6929a2 Alexander Schreiber
    instance = self.instance
2226 bf6929a2 Alexander Schreiber
    ignore_secondaries = self.op.ignore_secondaries
2227 bf6929a2 Alexander Schreiber
    reboot_type = self.op.reboot_type
2228 bf6929a2 Alexander Schreiber
    extra_args = getattr(self.op, "extra_args", "")
2229 bf6929a2 Alexander Schreiber
2230 bf6929a2 Alexander Schreiber
    node_current = instance.primary_node
2231 bf6929a2 Alexander Schreiber
2232 bf6929a2 Alexander Schreiber
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2233 bf6929a2 Alexander Schreiber
                       constants.INSTANCE_REBOOT_HARD]:
2234 bf6929a2 Alexander Schreiber
      if not rpc.call_instance_reboot(node_current, instance,
2235 bf6929a2 Alexander Schreiber
                                      reboot_type, extra_args):
2236 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("Could not reboot instance")
2237 bf6929a2 Alexander Schreiber
    else:
2238 bf6929a2 Alexander Schreiber
      if not rpc.call_instance_shutdown(node_current, instance):
2239 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("could not shutdown instance for full reboot")
2240 bf6929a2 Alexander Schreiber
      _ShutdownInstanceDisks(instance, self.cfg)
2241 bf6929a2 Alexander Schreiber
      _StartInstanceDisks(self.cfg, instance, ignore_secondaries)
2242 bf6929a2 Alexander Schreiber
      if not rpc.call_instance_start(node_current, instance, extra_args):
2243 bf6929a2 Alexander Schreiber
        _ShutdownInstanceDisks(instance, self.cfg)
2244 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("Could not start instance for full reboot")
2245 bf6929a2 Alexander Schreiber
2246 bf6929a2 Alexander Schreiber
    self.cfg.MarkInstanceUp(instance.name)
2247 bf6929a2 Alexander Schreiber
2248 bf6929a2 Alexander Schreiber
2249 a8083063 Iustin Pop
class LUShutdownInstance(LogicalUnit):
2250 a8083063 Iustin Pop
  """Shutdown an instance.
2251 a8083063 Iustin Pop

2252 a8083063 Iustin Pop
  """
2253 a8083063 Iustin Pop
  HPATH = "instance-stop"
2254 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2255 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2256 e873317a Guido Trotter
  REQ_BGL = False
2257 e873317a Guido Trotter
2258 e873317a Guido Trotter
  def ExpandNames(self):
2259 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2260 e873317a Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2261 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2262 e873317a Guido Trotter
2263 e873317a Guido Trotter
  def DeclareLocks(self, level):
2264 e873317a Guido Trotter
    if level == locking.LEVEL_NODE:
2265 e873317a Guido Trotter
      self._LockInstancesNodes()
2266 a8083063 Iustin Pop
2267 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2268 a8083063 Iustin Pop
    """Build hooks env.
2269 a8083063 Iustin Pop

2270 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2271 a8083063 Iustin Pop

2272 a8083063 Iustin Pop
    """
2273 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance)
2274 880478f8 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2275 a8083063 Iustin Pop
          list(self.instance.secondary_nodes))
2276 a8083063 Iustin Pop
    return env, nl, nl
2277 a8083063 Iustin Pop
2278 a8083063 Iustin Pop
  def CheckPrereq(self):
2279 a8083063 Iustin Pop
    """Check prerequisites.
2280 a8083063 Iustin Pop

2281 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2282 a8083063 Iustin Pop

2283 a8083063 Iustin Pop
    """
2284 e873317a Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2285 e873317a Guido Trotter
    assert self.instance is not None, \
2286 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2287 a8083063 Iustin Pop
2288 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2289 a8083063 Iustin Pop
    """Shutdown the instance.
2290 a8083063 Iustin Pop

2291 a8083063 Iustin Pop
    """
2292 a8083063 Iustin Pop
    instance = self.instance
2293 a8083063 Iustin Pop
    node_current = instance.primary_node
2294 fe482621 Iustin Pop
    self.cfg.MarkInstanceDown(instance.name)
2295 a8083063 Iustin Pop
    if not rpc.call_instance_shutdown(node_current, instance):
2296 a8083063 Iustin Pop
      logger.Error("could not shutdown instance")
2297 a8083063 Iustin Pop
2298 a8083063 Iustin Pop
    _ShutdownInstanceDisks(instance, self.cfg)
2299 a8083063 Iustin Pop
2300 a8083063 Iustin Pop
2301 fe7b0351 Michael Hanselmann
class LUReinstallInstance(LogicalUnit):
2302 fe7b0351 Michael Hanselmann
  """Reinstall an instance.
2303 fe7b0351 Michael Hanselmann

2304 fe7b0351 Michael Hanselmann
  """
2305 fe7b0351 Michael Hanselmann
  HPATH = "instance-reinstall"
2306 fe7b0351 Michael Hanselmann
  HTYPE = constants.HTYPE_INSTANCE
2307 fe7b0351 Michael Hanselmann
  _OP_REQP = ["instance_name"]
2308 4e0b4d2d Guido Trotter
  REQ_BGL = False
2309 4e0b4d2d Guido Trotter
2310 4e0b4d2d Guido Trotter
  def ExpandNames(self):
2311 4e0b4d2d Guido Trotter
    self._ExpandAndLockInstance()
2312 4e0b4d2d Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2313 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2314 4e0b4d2d Guido Trotter
2315 4e0b4d2d Guido Trotter
  def DeclareLocks(self, level):
2316 4e0b4d2d Guido Trotter
    if level == locking.LEVEL_NODE:
2317 4e0b4d2d Guido Trotter
      self._LockInstancesNodes()
2318 fe7b0351 Michael Hanselmann
2319 fe7b0351 Michael Hanselmann
  def BuildHooksEnv(self):
2320 fe7b0351 Michael Hanselmann
    """Build hooks env.
2321 fe7b0351 Michael Hanselmann

2322 fe7b0351 Michael Hanselmann
    This runs on master, primary and secondary nodes of the instance.
2323 fe7b0351 Michael Hanselmann

2324 fe7b0351 Michael Hanselmann
    """
2325 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance)
2326 fe7b0351 Michael Hanselmann
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2327 fe7b0351 Michael Hanselmann
          list(self.instance.secondary_nodes))
2328 fe7b0351 Michael Hanselmann
    return env, nl, nl
2329 fe7b0351 Michael Hanselmann
2330 fe7b0351 Michael Hanselmann
  def CheckPrereq(self):
2331 fe7b0351 Michael Hanselmann
    """Check prerequisites.
2332 fe7b0351 Michael Hanselmann

2333 fe7b0351 Michael Hanselmann
    This checks that the instance is in the cluster and is not running.
2334 fe7b0351 Michael Hanselmann

2335 fe7b0351 Michael Hanselmann
    """
2336 4e0b4d2d Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2337 4e0b4d2d Guido Trotter
    assert instance is not None, \
2338 4e0b4d2d Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2339 4e0b4d2d Guido Trotter
2340 fe7b0351 Michael Hanselmann
    if instance.disk_template == constants.DT_DISKLESS:
2341 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2342 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2343 fe7b0351 Michael Hanselmann
    if instance.status != "down":
2344 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2345 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2346 fe7b0351 Michael Hanselmann
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2347 fe7b0351 Michael Hanselmann
    if remote_info:
2348 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2349 3ecf6786 Iustin Pop
                                 (self.op.instance_name,
2350 3ecf6786 Iustin Pop
                                  instance.primary_node))
2351 d0834de3 Michael Hanselmann
2352 d0834de3 Michael Hanselmann
    self.op.os_type = getattr(self.op, "os_type", None)
2353 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2354 d0834de3 Michael Hanselmann
      # OS verification
2355 d0834de3 Michael Hanselmann
      pnode = self.cfg.GetNodeInfo(
2356 d0834de3 Michael Hanselmann
        self.cfg.ExpandNodeName(instance.primary_node))
2357 d0834de3 Michael Hanselmann
      if pnode is None:
2358 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2359 3ecf6786 Iustin Pop
                                   self.op.pnode)
2360 00fe9e38 Guido Trotter
      os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
2361 dfa96ded Guido Trotter
      if not os_obj:
2362 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2363 3ecf6786 Iustin Pop
                                   " primary node"  % self.op.os_type)
2364 d0834de3 Michael Hanselmann
2365 fe7b0351 Michael Hanselmann
    self.instance = instance
2366 fe7b0351 Michael Hanselmann
2367 fe7b0351 Michael Hanselmann
  def Exec(self, feedback_fn):
2368 fe7b0351 Michael Hanselmann
    """Reinstall the instance.
2369 fe7b0351 Michael Hanselmann

2370 fe7b0351 Michael Hanselmann
    """
2371 fe7b0351 Michael Hanselmann
    inst = self.instance
2372 fe7b0351 Michael Hanselmann
2373 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2374 d0834de3 Michael Hanselmann
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2375 d0834de3 Michael Hanselmann
      inst.os = self.op.os_type
2376 d0834de3 Michael Hanselmann
      self.cfg.AddInstance(inst)
2377 d0834de3 Michael Hanselmann
2378 fe7b0351 Michael Hanselmann
    _StartInstanceDisks(self.cfg, inst, None)
2379 fe7b0351 Michael Hanselmann
    try:
2380 fe7b0351 Michael Hanselmann
      feedback_fn("Running the instance OS create scripts...")
2381 fe7b0351 Michael Hanselmann
      if not rpc.call_instance_os_add(inst.primary_node, inst, "sda", "sdb"):
2382 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Could not install OS for instance %s"
2383 f4bc1f2c Michael Hanselmann
                                 " on node %s" %
2384 3ecf6786 Iustin Pop
                                 (inst.name, inst.primary_node))
2385 fe7b0351 Michael Hanselmann
    finally:
2386 fe7b0351 Michael Hanselmann
      _ShutdownInstanceDisks(inst, self.cfg)
2387 fe7b0351 Michael Hanselmann
2388 fe7b0351 Michael Hanselmann
2389 decd5f45 Iustin Pop
class LURenameInstance(LogicalUnit):
2390 decd5f45 Iustin Pop
  """Rename an instance.
2391 decd5f45 Iustin Pop

2392 decd5f45 Iustin Pop
  """
2393 decd5f45 Iustin Pop
  HPATH = "instance-rename"
2394 decd5f45 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2395 decd5f45 Iustin Pop
  _OP_REQP = ["instance_name", "new_name"]
2396 decd5f45 Iustin Pop
2397 decd5f45 Iustin Pop
  def BuildHooksEnv(self):
2398 decd5f45 Iustin Pop
    """Build hooks env.
2399 decd5f45 Iustin Pop

2400 decd5f45 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2401 decd5f45 Iustin Pop

2402 decd5f45 Iustin Pop
    """
2403 decd5f45 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self.instance)
2404 decd5f45 Iustin Pop
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2405 decd5f45 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2406 decd5f45 Iustin Pop
          list(self.instance.secondary_nodes))
2407 decd5f45 Iustin Pop
    return env, nl, nl
2408 decd5f45 Iustin Pop
2409 decd5f45 Iustin Pop
  def CheckPrereq(self):
2410 decd5f45 Iustin Pop
    """Check prerequisites.
2411 decd5f45 Iustin Pop

2412 decd5f45 Iustin Pop
    This checks that the instance is in the cluster and is not running.
2413 decd5f45 Iustin Pop

2414 decd5f45 Iustin Pop
    """
2415 decd5f45 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2416 decd5f45 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2417 decd5f45 Iustin Pop
    if instance is None:
2418 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2419 decd5f45 Iustin Pop
                                 self.op.instance_name)
2420 decd5f45 Iustin Pop
    if instance.status != "down":
2421 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2422 decd5f45 Iustin Pop
                                 self.op.instance_name)
2423 decd5f45 Iustin Pop
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2424 decd5f45 Iustin Pop
    if remote_info:
2425 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2426 decd5f45 Iustin Pop
                                 (self.op.instance_name,
2427 decd5f45 Iustin Pop
                                  instance.primary_node))
2428 decd5f45 Iustin Pop
    self.instance = instance
2429 decd5f45 Iustin Pop
2430 decd5f45 Iustin Pop
    # new name verification
2431 89e1fc26 Iustin Pop
    name_info = utils.HostInfo(self.op.new_name)
2432 decd5f45 Iustin Pop
2433 89e1fc26 Iustin Pop
    self.op.new_name = new_name = name_info.name
2434 7bde3275 Guido Trotter
    instance_list = self.cfg.GetInstanceList()
2435 7bde3275 Guido Trotter
    if new_name in instance_list:
2436 7bde3275 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2437 c09f363f Manuel Franceschini
                                 new_name)
2438 7bde3275 Guido Trotter
2439 decd5f45 Iustin Pop
    if not getattr(self.op, "ignore_ip", False):
2440 937f983d Guido Trotter
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2441 decd5f45 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2442 89e1fc26 Iustin Pop
                                   (name_info.ip, new_name))
2443 decd5f45 Iustin Pop
2444 decd5f45 Iustin Pop
2445 decd5f45 Iustin Pop
  def Exec(self, feedback_fn):
2446 decd5f45 Iustin Pop
    """Reinstall the instance.
2447 decd5f45 Iustin Pop

2448 decd5f45 Iustin Pop
    """
2449 decd5f45 Iustin Pop
    inst = self.instance
2450 decd5f45 Iustin Pop
    old_name = inst.name
2451 decd5f45 Iustin Pop
2452 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2453 b23c4333 Manuel Franceschini
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2454 b23c4333 Manuel Franceschini
2455 decd5f45 Iustin Pop
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2456 74b5913f Guido Trotter
    # Change the instance lock. This is definitely safe while we hold the BGL
2457 74b5913f Guido Trotter
    self.context.glm.remove(locking.LEVEL_INSTANCE, inst.name)
2458 74b5913f Guido Trotter
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2459 decd5f45 Iustin Pop
2460 decd5f45 Iustin Pop
    # re-read the instance from the configuration after rename
2461 decd5f45 Iustin Pop
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2462 decd5f45 Iustin Pop
2463 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2464 b23c4333 Manuel Franceschini
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2465 b23c4333 Manuel Franceschini
      result = rpc.call_file_storage_dir_rename(inst.primary_node,
2466 b23c4333 Manuel Franceschini
                                                old_file_storage_dir,
2467 b23c4333 Manuel Franceschini
                                                new_file_storage_dir)
2468 b23c4333 Manuel Franceschini
2469 b23c4333 Manuel Franceschini
      if not result:
2470 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2471 b23c4333 Manuel Franceschini
                                 " directory '%s' to '%s' (but the instance"
2472 b23c4333 Manuel Franceschini
                                 " has been renamed in Ganeti)" % (
2473 b23c4333 Manuel Franceschini
                                 inst.primary_node, old_file_storage_dir,
2474 b23c4333 Manuel Franceschini
                                 new_file_storage_dir))
2475 b23c4333 Manuel Franceschini
2476 b23c4333 Manuel Franceschini
      if not result[0]:
2477 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2478 b23c4333 Manuel Franceschini
                                 " (but the instance has been renamed in"
2479 b23c4333 Manuel Franceschini
                                 " Ganeti)" % (old_file_storage_dir,
2480 b23c4333 Manuel Franceschini
                                               new_file_storage_dir))
2481 b23c4333 Manuel Franceschini
2482 decd5f45 Iustin Pop
    _StartInstanceDisks(self.cfg, inst, None)
2483 decd5f45 Iustin Pop
    try:
2484 decd5f45 Iustin Pop
      if not rpc.call_instance_run_rename(inst.primary_node, inst, old_name,
2485 decd5f45 Iustin Pop
                                          "sda", "sdb"):
2486 6291574d Alexander Schreiber
        msg = ("Could not run OS rename script for instance %s on node %s"
2487 6291574d Alexander Schreiber
               " (but the instance has been renamed in Ganeti)" %
2488 decd5f45 Iustin Pop
               (inst.name, inst.primary_node))
2489 decd5f45 Iustin Pop
        logger.Error(msg)
2490 decd5f45 Iustin Pop
    finally:
2491 decd5f45 Iustin Pop
      _ShutdownInstanceDisks(inst, self.cfg)
2492 decd5f45 Iustin Pop
2493 decd5f45 Iustin Pop
2494 a8083063 Iustin Pop
class LURemoveInstance(LogicalUnit):
2495 a8083063 Iustin Pop
  """Remove an instance.
2496 a8083063 Iustin Pop

2497 a8083063 Iustin Pop
  """
2498 a8083063 Iustin Pop
  HPATH = "instance-remove"
2499 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2500 5c54b832 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_failures"]
2501 cf472233 Guido Trotter
  REQ_BGL = False
2502 cf472233 Guido Trotter
2503 cf472233 Guido Trotter
  def ExpandNames(self):
2504 cf472233 Guido Trotter
    self._ExpandAndLockInstance()
2505 cf472233 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2506 cf472233 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2507 cf472233 Guido Trotter
2508 cf472233 Guido Trotter
  def DeclareLocks(self, level):
2509 cf472233 Guido Trotter
    if level == locking.LEVEL_NODE:
2510 cf472233 Guido Trotter
      self._LockInstancesNodes()
2511 a8083063 Iustin Pop
2512 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2513 a8083063 Iustin Pop
    """Build hooks env.
2514 a8083063 Iustin Pop

2515 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2516 a8083063 Iustin Pop

2517 a8083063 Iustin Pop
    """
2518 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance)
2519 1d67656e Iustin Pop
    nl = [self.sstore.GetMasterNode()]
2520 a8083063 Iustin Pop
    return env, nl, nl
2521 a8083063 Iustin Pop
2522 a8083063 Iustin Pop
  def CheckPrereq(self):
2523 a8083063 Iustin Pop
    """Check prerequisites.
2524 a8083063 Iustin Pop

2525 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2526 a8083063 Iustin Pop

2527 a8083063 Iustin Pop
    """
2528 cf472233 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2529 cf472233 Guido Trotter
    assert self.instance is not None, \
2530 cf472233 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2531 a8083063 Iustin Pop
2532 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2533 a8083063 Iustin Pop
    """Remove the instance.
2534 a8083063 Iustin Pop

2535 a8083063 Iustin Pop
    """
2536 a8083063 Iustin Pop
    instance = self.instance
2537 a8083063 Iustin Pop
    logger.Info("shutting down instance %s on node %s" %
2538 a8083063 Iustin Pop
                (instance.name, instance.primary_node))
2539 a8083063 Iustin Pop
2540 a8083063 Iustin Pop
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
2541 1d67656e Iustin Pop
      if self.op.ignore_failures:
2542 1d67656e Iustin Pop
        feedback_fn("Warning: can't shutdown instance")
2543 1d67656e Iustin Pop
      else:
2544 1d67656e Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2545 1d67656e Iustin Pop
                                 (instance.name, instance.primary_node))
2546 a8083063 Iustin Pop
2547 a8083063 Iustin Pop
    logger.Info("removing block devices for instance %s" % instance.name)
2548 a8083063 Iustin Pop
2549 1d67656e Iustin Pop
    if not _RemoveDisks(instance, self.cfg):
2550 1d67656e Iustin Pop
      if self.op.ignore_failures:
2551 1d67656e Iustin Pop
        feedback_fn("Warning: can't remove instance's disks")
2552 1d67656e Iustin Pop
      else:
2553 1d67656e Iustin Pop
        raise errors.OpExecError("Can't remove instance's disks")
2554 a8083063 Iustin Pop
2555 a8083063 Iustin Pop
    logger.Info("removing instance %s out of cluster config" % instance.name)
2556 a8083063 Iustin Pop
2557 a8083063 Iustin Pop
    self.cfg.RemoveInstance(instance.name)
2558 cf472233 Guido Trotter
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
2559 a8083063 Iustin Pop
2560 a8083063 Iustin Pop
2561 a8083063 Iustin Pop
class LUQueryInstances(NoHooksLU):
2562 a8083063 Iustin Pop
  """Logical unit for querying instances.
2563 a8083063 Iustin Pop

2564 a8083063 Iustin Pop
  """
2565 069dcc86 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
2566 7eb9d8f7 Guido Trotter
  REQ_BGL = False
2567 a8083063 Iustin Pop
2568 7eb9d8f7 Guido Trotter
  def ExpandNames(self):
2569 d8052456 Iustin Pop
    self.dynamic_fields = frozenset(["oper_state", "oper_ram", "status"])
2570 57a2fb91 Iustin Pop
    self.static_fields = frozenset([
2571 57a2fb91 Iustin Pop
      "name", "os", "pnode", "snodes",
2572 57a2fb91 Iustin Pop
      "admin_state", "admin_ram",
2573 57a2fb91 Iustin Pop
      "disk_template", "ip", "mac", "bridge",
2574 57a2fb91 Iustin Pop
      "sda_size", "sdb_size", "vcpus", "tags",
2575 57a2fb91 Iustin Pop
      "network_port", "kernel_path", "initrd_path",
2576 57a2fb91 Iustin Pop
      "hvm_boot_order", "hvm_acpi", "hvm_pae",
2577 57a2fb91 Iustin Pop
      "hvm_cdrom_image_path", "hvm_nic_type",
2578 57a2fb91 Iustin Pop
      "hvm_disk_type", "vnc_bind_address",
2579 57a2fb91 Iustin Pop
      ])
2580 57a2fb91 Iustin Pop
    _CheckOutputFields(static=self.static_fields,
2581 dcb93971 Michael Hanselmann
                       dynamic=self.dynamic_fields,
2582 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
2583 a8083063 Iustin Pop
2584 7eb9d8f7 Guido Trotter
    self.needed_locks = {}
2585 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_INSTANCE] = 1
2586 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
2587 7eb9d8f7 Guido Trotter
2588 57a2fb91 Iustin Pop
    if self.op.names:
2589 57a2fb91 Iustin Pop
      self.wanted = _GetWantedInstances(self, self.op.names)
2590 7eb9d8f7 Guido Trotter
    else:
2591 57a2fb91 Iustin Pop
      self.wanted = locking.ALL_SET
2592 7eb9d8f7 Guido Trotter
2593 57a2fb91 Iustin Pop
    self.do_locking = not self.static_fields.issuperset(self.op.output_fields)
2594 57a2fb91 Iustin Pop
    if self.do_locking:
2595 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
2596 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = []
2597 57a2fb91 Iustin Pop
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2598 7eb9d8f7 Guido Trotter
2599 7eb9d8f7 Guido Trotter
  def DeclareLocks(self, level):
2600 57a2fb91 Iustin Pop
    if level == locking.LEVEL_NODE and self.do_locking:
2601 7eb9d8f7 Guido Trotter
      self._LockInstancesNodes()
2602 7eb9d8f7 Guido Trotter
2603 7eb9d8f7 Guido Trotter
  def CheckPrereq(self):
2604 7eb9d8f7 Guido Trotter
    """Check prerequisites.
2605 7eb9d8f7 Guido Trotter

2606 7eb9d8f7 Guido Trotter
    """
2607 57a2fb91 Iustin Pop
    pass
2608 069dcc86 Iustin Pop
2609 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2610 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
2611 a8083063 Iustin Pop

2612 a8083063 Iustin Pop
    """
2613 57a2fb91 Iustin Pop
    all_info = self.cfg.GetAllInstancesInfo()
2614 57a2fb91 Iustin Pop
    if self.do_locking:
2615 57a2fb91 Iustin Pop
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2616 3fa93523 Guido Trotter
    elif self.wanted != locking.ALL_SET:
2617 3fa93523 Guido Trotter
      instance_names = self.wanted
2618 3fa93523 Guido Trotter
      missing = set(instance_names).difference(all_info.keys())
2619 3fa93523 Guido Trotter
      if missing:
2620 3fa93523 Guido Trotter
        raise self.OpExecError(
2621 3fa93523 Guido Trotter
          "Some instances were removed before retrieving their data: %s"
2622 3fa93523 Guido Trotter
          % missing)
2623 57a2fb91 Iustin Pop
    else:
2624 57a2fb91 Iustin Pop
      instance_names = all_info.keys()
2625 57a2fb91 Iustin Pop
    instance_list = [all_info[iname] for iname in instance_names]
2626 a8083063 Iustin Pop
2627 a8083063 Iustin Pop
    # begin data gathering
2628 a8083063 Iustin Pop
2629 a8083063 Iustin Pop
    nodes = frozenset([inst.primary_node for inst in instance_list])
2630 a8083063 Iustin Pop
2631 a8083063 Iustin Pop
    bad_nodes = []
2632 a8083063 Iustin Pop
    if self.dynamic_fields.intersection(self.op.output_fields):
2633 a8083063 Iustin Pop
      live_data = {}
2634 a8083063 Iustin Pop
      node_data = rpc.call_all_instances_info(nodes)
2635 a8083063 Iustin Pop
      for name in nodes:
2636 a8083063 Iustin Pop
        result = node_data[name]
2637 a8083063 Iustin Pop
        if result:
2638 a8083063 Iustin Pop
          live_data.update(result)
2639 a8083063 Iustin Pop
        elif result == False:
2640 a8083063 Iustin Pop
          bad_nodes.append(name)
2641 a8083063 Iustin Pop
        # else no instance is alive
2642 a8083063 Iustin Pop
    else:
2643 a8083063 Iustin Pop
      live_data = dict([(name, {}) for name in instance_names])
2644 a8083063 Iustin Pop
2645 a8083063 Iustin Pop
    # end data gathering
2646 a8083063 Iustin Pop
2647 a8083063 Iustin Pop
    output = []
2648 a8083063 Iustin Pop
    for instance in instance_list:
2649 a8083063 Iustin Pop
      iout = []
2650 a8083063 Iustin Pop
      for field in self.op.output_fields:
2651 a8083063 Iustin Pop
        if field == "name":
2652 a8083063 Iustin Pop
          val = instance.name
2653 a8083063 Iustin Pop
        elif field == "os":
2654 a8083063 Iustin Pop
          val = instance.os
2655 a8083063 Iustin Pop
        elif field == "pnode":
2656 a8083063 Iustin Pop
          val = instance.primary_node
2657 a8083063 Iustin Pop
        elif field == "snodes":
2658 8a23d2d3 Iustin Pop
          val = list(instance.secondary_nodes)
2659 a8083063 Iustin Pop
        elif field == "admin_state":
2660 8a23d2d3 Iustin Pop
          val = (instance.status != "down")
2661 a8083063 Iustin Pop
        elif field == "oper_state":
2662 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
2663 8a23d2d3 Iustin Pop
            val = None
2664 a8083063 Iustin Pop
          else:
2665 8a23d2d3 Iustin Pop
            val = bool(live_data.get(instance.name))
2666 d8052456 Iustin Pop
        elif field == "status":
2667 d8052456 Iustin Pop
          if instance.primary_node in bad_nodes:
2668 d8052456 Iustin Pop
            val = "ERROR_nodedown"
2669 d8052456 Iustin Pop
          else:
2670 d8052456 Iustin Pop
            running = bool(live_data.get(instance.name))
2671 d8052456 Iustin Pop
            if running:
2672 d8052456 Iustin Pop
              if instance.status != "down":
2673 d8052456 Iustin Pop
                val = "running"
2674 d8052456 Iustin Pop
              else:
2675 d8052456 Iustin Pop
                val = "ERROR_up"
2676 d8052456 Iustin Pop
            else:
2677 d8052456 Iustin Pop
              if instance.status != "down":
2678 d8052456 Iustin Pop
                val = "ERROR_down"
2679 d8052456 Iustin Pop
              else:
2680 d8052456 Iustin Pop
                val = "ADMIN_down"
2681 a8083063 Iustin Pop
        elif field == "admin_ram":
2682 a8083063 Iustin Pop
          val = instance.memory
2683 a8083063 Iustin Pop
        elif field == "oper_ram":
2684 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
2685 8a23d2d3 Iustin Pop
            val = None
2686 a8083063 Iustin Pop
          elif instance.name in live_data:
2687 a8083063 Iustin Pop
            val = live_data[instance.name].get("memory", "?")
2688 a8083063 Iustin Pop
          else:
2689 a8083063 Iustin Pop
            val = "-"
2690 a8083063 Iustin Pop
        elif field == "disk_template":
2691 a8083063 Iustin Pop
          val = instance.disk_template
2692 a8083063 Iustin Pop
        elif field == "ip":
2693 a8083063 Iustin Pop
          val = instance.nics[0].ip
2694 a8083063 Iustin Pop
        elif field == "bridge":
2695 a8083063 Iustin Pop
          val = instance.nics[0].bridge
2696 a8083063 Iustin Pop
        elif field == "mac":
2697 a8083063 Iustin Pop
          val = instance.nics[0].mac
2698 644eeef9 Iustin Pop
        elif field == "sda_size" or field == "sdb_size":
2699 644eeef9 Iustin Pop
          disk = instance.FindDisk(field[:3])
2700 644eeef9 Iustin Pop
          if disk is None:
2701 8a23d2d3 Iustin Pop
            val = None
2702 644eeef9 Iustin Pop
          else:
2703 644eeef9 Iustin Pop
            val = disk.size
2704 d6d415e8 Iustin Pop
        elif field == "vcpus":
2705 d6d415e8 Iustin Pop
          val = instance.vcpus
2706 130a6a6f Iustin Pop
        elif field == "tags":
2707 130a6a6f Iustin Pop
          val = list(instance.GetTags())
2708 3fb1e1c5 Alexander Schreiber
        elif field in ("network_port", "kernel_path", "initrd_path",
2709 3fb1e1c5 Alexander Schreiber
                       "hvm_boot_order", "hvm_acpi", "hvm_pae",
2710 3fb1e1c5 Alexander Schreiber
                       "hvm_cdrom_image_path", "hvm_nic_type",
2711 3fb1e1c5 Alexander Schreiber
                       "hvm_disk_type", "vnc_bind_address"):
2712 3fb1e1c5 Alexander Schreiber
          val = getattr(instance, field, None)
2713 3fb1e1c5 Alexander Schreiber
          if val is not None:
2714 3fb1e1c5 Alexander Schreiber
            pass
2715 3fb1e1c5 Alexander Schreiber
          elif field in ("hvm_nic_type", "hvm_disk_type",
2716 3fb1e1c5 Alexander Schreiber
                         "kernel_path", "initrd_path"):
2717 3fb1e1c5 Alexander Schreiber
            val = "default"
2718 3fb1e1c5 Alexander Schreiber
          else:
2719 3fb1e1c5 Alexander Schreiber
            val = "-"
2720 a8083063 Iustin Pop
        else:
2721 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
2722 a8083063 Iustin Pop
        iout.append(val)
2723 a8083063 Iustin Pop
      output.append(iout)
2724 a8083063 Iustin Pop
2725 a8083063 Iustin Pop
    return output
2726 a8083063 Iustin Pop
2727 a8083063 Iustin Pop
2728 a8083063 Iustin Pop
class LUFailoverInstance(LogicalUnit):
2729 a8083063 Iustin Pop
  """Failover an instance.
2730 a8083063 Iustin Pop

2731 a8083063 Iustin Pop
  """
2732 a8083063 Iustin Pop
  HPATH = "instance-failover"
2733 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2734 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_consistency"]
2735 c9e5c064 Guido Trotter
  REQ_BGL = False
2736 c9e5c064 Guido Trotter
2737 c9e5c064 Guido Trotter
  def ExpandNames(self):
2738 c9e5c064 Guido Trotter
    self._ExpandAndLockInstance()
2739 c9e5c064 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2740 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2741 c9e5c064 Guido Trotter
2742 c9e5c064 Guido Trotter
  def DeclareLocks(self, level):
2743 c9e5c064 Guido Trotter
    if level == locking.LEVEL_NODE:
2744 c9e5c064 Guido Trotter
      self._LockInstancesNodes()
2745 a8083063 Iustin Pop
2746 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2747 a8083063 Iustin Pop
    """Build hooks env.
2748 a8083063 Iustin Pop

2749 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2750 a8083063 Iustin Pop

2751 a8083063 Iustin Pop
    """
2752 a8083063 Iustin Pop
    env = {
2753 a8083063 Iustin Pop
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2754 a8083063 Iustin Pop
      }
2755 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2756 880478f8 Iustin Pop
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2757 a8083063 Iustin Pop
    return env, nl, nl
2758 a8083063 Iustin Pop
2759 a8083063 Iustin Pop
  def CheckPrereq(self):
2760 a8083063 Iustin Pop
    """Check prerequisites.
2761 a8083063 Iustin Pop

2762 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2763 a8083063 Iustin Pop

2764 a8083063 Iustin Pop
    """
2765 c9e5c064 Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2766 c9e5c064 Guido Trotter
    assert self.instance is not None, \
2767 c9e5c064 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2768 a8083063 Iustin Pop
2769 a1f445d3 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
2770 2a710df1 Michael Hanselmann
      raise errors.OpPrereqError("Instance's disk layout is not"
2771 a1f445d3 Iustin Pop
                                 " network mirrored, cannot failover.")
2772 2a710df1 Michael Hanselmann
2773 2a710df1 Michael Hanselmann
    secondary_nodes = instance.secondary_nodes
2774 2a710df1 Michael Hanselmann
    if not secondary_nodes:
2775 2a710df1 Michael Hanselmann
      raise errors.ProgrammerError("no secondary node but using "
2776 abdf0113 Iustin Pop
                                   "a mirrored disk template")
2777 2a710df1 Michael Hanselmann
2778 2a710df1 Michael Hanselmann
    target_node = secondary_nodes[0]
2779 d4f16fd9 Iustin Pop
    # check memory requirements on the secondary node
2780 d4f16fd9 Iustin Pop
    _CheckNodeFreeMemory(self.cfg, target_node, "failing over instance %s" %
2781 d4f16fd9 Iustin Pop
                         instance.name, instance.memory)
2782 3a7c308e Guido Trotter
2783 a8083063 Iustin Pop
    # check bridge existance
2784 a8083063 Iustin Pop
    brlist = [nic.bridge for nic in instance.nics]
2785 50ff9a7a Iustin Pop
    if not rpc.call_bridges_exist(target_node, brlist):
2786 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("One or more target bridges %s does not"
2787 3ecf6786 Iustin Pop
                                 " exist on destination node '%s'" %
2788 50ff9a7a Iustin Pop
                                 (brlist, target_node))
2789 a8083063 Iustin Pop
2790 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2791 a8083063 Iustin Pop
    """Failover an instance.
2792 a8083063 Iustin Pop

2793 a8083063 Iustin Pop
    The failover is done by shutting it down on its present node and
2794 a8083063 Iustin Pop
    starting it on the secondary.
2795 a8083063 Iustin Pop

2796 a8083063 Iustin Pop
    """
2797 a8083063 Iustin Pop
    instance = self.instance
2798 a8083063 Iustin Pop
2799 a8083063 Iustin Pop
    source_node = instance.primary_node
2800 a8083063 Iustin Pop
    target_node = instance.secondary_nodes[0]
2801 a8083063 Iustin Pop
2802 a8083063 Iustin Pop
    feedback_fn("* checking disk consistency between source and target")
2803 a8083063 Iustin Pop
    for dev in instance.disks:
2804 abdf0113 Iustin Pop
      # for drbd, these are drbd over lvm
2805 a8083063 Iustin Pop
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2806 a0aaa0d0 Guido Trotter
        if instance.status == "up" and not self.op.ignore_consistency:
2807 3ecf6786 Iustin Pop
          raise errors.OpExecError("Disk %s is degraded on target node,"
2808 3ecf6786 Iustin Pop
                                   " aborting failover." % dev.iv_name)
2809 a8083063 Iustin Pop
2810 a8083063 Iustin Pop
    feedback_fn("* shutting down instance on source node")
2811 a8083063 Iustin Pop
    logger.Info("Shutting down instance %s on node %s" %
2812 a8083063 Iustin Pop
                (instance.name, source_node))
2813 a8083063 Iustin Pop
2814 a8083063 Iustin Pop
    if not rpc.call_instance_shutdown(source_node, instance):
2815 24a40d57 Iustin Pop
      if self.op.ignore_consistency:
2816 24a40d57 Iustin Pop
        logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2817 24a40d57 Iustin Pop
                     " anyway. Please make sure node %s is down"  %
2818 24a40d57 Iustin Pop
                     (instance.name, source_node, source_node))
2819 24a40d57 Iustin Pop
      else:
2820 24a40d57 Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2821 24a40d57 Iustin Pop
                                 (instance.name, source_node))
2822 a8083063 Iustin Pop
2823 a8083063 Iustin Pop
    feedback_fn("* deactivating the instance's disks on source node")
2824 a8083063 Iustin Pop
    if not _ShutdownInstanceDisks(instance, self.cfg, ignore_primary=True):
2825 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't shut down the instance's disks.")
2826 a8083063 Iustin Pop
2827 a8083063 Iustin Pop
    instance.primary_node = target_node
2828 a8083063 Iustin Pop
    # distribute new instance config to the other nodes
2829 b6102dab Guido Trotter
    self.cfg.Update(instance)
2830 a8083063 Iustin Pop
2831 12a0cfbe Guido Trotter
    # Only start the instance if it's marked as up
2832 12a0cfbe Guido Trotter
    if instance.status == "up":
2833 12a0cfbe Guido Trotter
      feedback_fn("* activating the instance's disks on target node")
2834 12a0cfbe Guido Trotter
      logger.Info("Starting instance %s on node %s" %
2835 12a0cfbe Guido Trotter
                  (instance.name, target_node))
2836 12a0cfbe Guido Trotter
2837 12a0cfbe Guido Trotter
      disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2838 12a0cfbe Guido Trotter
                                               ignore_secondaries=True)
2839 12a0cfbe Guido Trotter
      if not disks_ok:
2840 12a0cfbe Guido Trotter
        _ShutdownInstanceDisks(instance, self.cfg)
2841 12a0cfbe Guido Trotter
        raise errors.OpExecError("Can't activate the instance's disks")
2842 a8083063 Iustin Pop
2843 12a0cfbe Guido Trotter
      feedback_fn("* starting the instance on the target node")
2844 12a0cfbe Guido Trotter
      if not rpc.call_instance_start(target_node, instance, None):
2845 12a0cfbe Guido Trotter
        _ShutdownInstanceDisks(instance, self.cfg)
2846 12a0cfbe Guido Trotter
        raise errors.OpExecError("Could not start instance %s on node %s." %
2847 12a0cfbe Guido Trotter
                                 (instance.name, target_node))
2848 a8083063 Iustin Pop
2849 a8083063 Iustin Pop
2850 3f78eef2 Iustin Pop
def _CreateBlockDevOnPrimary(cfg, node, instance, device, info):
2851 a8083063 Iustin Pop
  """Create a tree of block devices on the primary node.
2852 a8083063 Iustin Pop

2853 a8083063 Iustin Pop
  This always creates all devices.
2854 a8083063 Iustin Pop

2855 a8083063 Iustin Pop
  """
2856 a8083063 Iustin Pop
  if device.children:
2857 a8083063 Iustin Pop
    for child in device.children:
2858 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnPrimary(cfg, node, instance, child, info):
2859 a8083063 Iustin Pop
        return False
2860 a8083063 Iustin Pop
2861 a8083063 Iustin Pop
  cfg.SetDiskID(device, node)
2862 3f78eef2 Iustin Pop
  new_id = rpc.call_blockdev_create(node, device, device.size,
2863 3f78eef2 Iustin Pop
                                    instance.name, True, info)
2864 a8083063 Iustin Pop
  if not new_id:
2865 a8083063 Iustin Pop
    return False
2866 a8083063 Iustin Pop
  if device.physical_id is None:
2867 a8083063 Iustin Pop
    device.physical_id = new_id
2868 a8083063 Iustin Pop
  return True
2869 a8083063 Iustin Pop
2870 a8083063 Iustin Pop
2871 3f78eef2 Iustin Pop
def _CreateBlockDevOnSecondary(cfg, node, instance, device, force, info):
2872 a8083063 Iustin Pop
  """Create a tree of block devices on a secondary node.
2873 a8083063 Iustin Pop

2874 a8083063 Iustin Pop
  If this device type has to be created on secondaries, create it and
2875 a8083063 Iustin Pop
  all its children.
2876 a8083063 Iustin Pop

2877 a8083063 Iustin Pop
  If not, just recurse to children keeping the same 'force' value.
2878 a8083063 Iustin Pop

2879 a8083063 Iustin Pop
  """
2880 a8083063 Iustin Pop
  if device.CreateOnSecondary():
2881 a8083063 Iustin Pop
    force = True
2882 a8083063 Iustin Pop
  if device.children:
2883 a8083063 Iustin Pop
    for child in device.children:
2884 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnSecondary(cfg, node, instance,
2885 3f78eef2 Iustin Pop
                                        child, force, info):
2886 a8083063 Iustin Pop
        return False
2887 a8083063 Iustin Pop
2888 a8083063 Iustin Pop
  if not force:
2889 a8083063 Iustin Pop
    return True
2890 a8083063 Iustin Pop
  cfg.SetDiskID(device, node)
2891 3f78eef2 Iustin Pop
  new_id = rpc.call_blockdev_create(node, device, device.size,
2892 3f78eef2 Iustin Pop
                                    instance.name, False, info)
2893 a8083063 Iustin Pop
  if not new_id:
2894 a8083063 Iustin Pop
    return False
2895 a8083063 Iustin Pop
  if device.physical_id is None:
2896 a8083063 Iustin Pop
    device.physical_id = new_id
2897 a8083063 Iustin Pop
  return True
2898 a8083063 Iustin Pop
2899 a8083063 Iustin Pop
2900 923b1523 Iustin Pop
def _GenerateUniqueNames(cfg, exts):
2901 923b1523 Iustin Pop
  """Generate a suitable LV name.
2902 923b1523 Iustin Pop

2903 923b1523 Iustin Pop
  This will generate a logical volume name for the given instance.
2904 923b1523 Iustin Pop

2905 923b1523 Iustin Pop
  """
2906 923b1523 Iustin Pop
  results = []
2907 923b1523 Iustin Pop
  for val in exts:
2908 923b1523 Iustin Pop
    new_id = cfg.GenerateUniqueID()
2909 923b1523 Iustin Pop
    results.append("%s%s" % (new_id, val))
2910 923b1523 Iustin Pop
  return results
2911 923b1523 Iustin Pop
2912 923b1523 Iustin Pop
2913 ffa1c0dc Iustin Pop
def _GenerateDRBD8Branch(cfg, primary, secondary, size, names, iv_name,
2914 ffa1c0dc Iustin Pop
                         p_minor, s_minor):
2915 a1f445d3 Iustin Pop
  """Generate a drbd8 device complete with its children.
2916 a1f445d3 Iustin Pop

2917 a1f445d3 Iustin Pop
  """
2918 a1f445d3 Iustin Pop
  port = cfg.AllocatePort()
2919 a1f445d3 Iustin Pop
  vgname = cfg.GetVGName()
2920 a1f445d3 Iustin Pop
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2921 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[0]))
2922 a1f445d3 Iustin Pop
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2923 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[1]))
2924 a1f445d3 Iustin Pop
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
2925 ffa1c0dc Iustin Pop
                          logical_id=(primary, secondary, port,
2926 ffa1c0dc Iustin Pop
                                      p_minor, s_minor),
2927 ffa1c0dc Iustin Pop
                          children=[dev_data, dev_meta],
2928 a1f445d3 Iustin Pop
                          iv_name=iv_name)
2929 a1f445d3 Iustin Pop
  return drbd_dev
2930 a1f445d3 Iustin Pop
2931 7c0d6283 Michael Hanselmann
2932 923b1523 Iustin Pop
def _GenerateDiskTemplate(cfg, template_name,
2933 a8083063 Iustin Pop
                          instance_name, primary_node,
2934 0f1a06e3 Manuel Franceschini
                          secondary_nodes, disk_sz, swap_sz,
2935 0f1a06e3 Manuel Franceschini
                          file_storage_dir, file_driver):
2936 a8083063 Iustin Pop
  """Generate the entire disk layout for a given template type.
2937 a8083063 Iustin Pop

2938 a8083063 Iustin Pop
  """
2939 a8083063 Iustin Pop
  #TODO: compute space requirements
2940 a8083063 Iustin Pop
2941 923b1523 Iustin Pop
  vgname = cfg.GetVGName()
2942 3517d9b9 Manuel Franceschini
  if template_name == constants.DT_DISKLESS:
2943 a8083063 Iustin Pop
    disks = []
2944 3517d9b9 Manuel Franceschini
  elif template_name == constants.DT_PLAIN:
2945 a8083063 Iustin Pop
    if len(secondary_nodes) != 0:
2946 a8083063 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
2947 923b1523 Iustin Pop
2948 923b1523 Iustin Pop
    names = _GenerateUniqueNames(cfg, [".sda", ".sdb"])
2949 fe96220b Iustin Pop
    sda_dev = objects.Disk(dev_type=constants.LD_LV, size=disk_sz,
2950 923b1523 Iustin Pop
                           logical_id=(vgname, names[0]),
2951 a8083063 Iustin Pop
                           iv_name = "sda")
2952 fe96220b Iustin Pop
    sdb_dev = objects.Disk(dev_type=constants.LD_LV, size=swap_sz,
2953 923b1523 Iustin Pop
                           logical_id=(vgname, names[1]),
2954 a8083063 Iustin Pop
                           iv_name = "sdb")
2955 a8083063 Iustin Pop
    disks = [sda_dev, sdb_dev]
2956 a1f445d3 Iustin Pop
  elif template_name == constants.DT_DRBD8:
2957 a1f445d3 Iustin Pop
    if len(secondary_nodes) != 1:
2958 a1f445d3 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
2959 a1f445d3 Iustin Pop
    remote_node = secondary_nodes[0]
2960 ffa1c0dc Iustin Pop
    (minor_pa, minor_pb,
2961 ffa1c0dc Iustin Pop
     minor_sa, minor_sb) = [None, None, None, None]
2962 ffa1c0dc Iustin Pop
2963 a1f445d3 Iustin Pop
    names = _GenerateUniqueNames(cfg, [".sda_data", ".sda_meta",
2964 a1f445d3 Iustin Pop
                                       ".sdb_data", ".sdb_meta"])
2965 a1f445d3 Iustin Pop
    drbd_sda_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2966 ffa1c0dc Iustin Pop
                                        disk_sz, names[0:2], "sda",
2967 ffa1c0dc Iustin Pop
                                        minor_pa, minor_sa)
2968 a1f445d3 Iustin Pop
    drbd_sdb_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2969 ffa1c0dc Iustin Pop
                                        swap_sz, names[2:4], "sdb",
2970 ffa1c0dc Iustin Pop
                                        minor_pb, minor_sb)
2971 a1f445d3 Iustin Pop
    disks = [drbd_sda_dev, drbd_sdb_dev]
2972 0f1a06e3 Manuel Franceschini
  elif template_name == constants.DT_FILE:
2973 0f1a06e3 Manuel Franceschini
    if len(secondary_nodes) != 0:
2974 0f1a06e3 Manuel Franceschini
      raise errors.ProgrammerError("Wrong template configuration")
2975 0f1a06e3 Manuel Franceschini
2976 0f1a06e3 Manuel Franceschini
    file_sda_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk_sz,
2977 0f1a06e3 Manuel Franceschini
                                iv_name="sda", logical_id=(file_driver,
2978 0f1a06e3 Manuel Franceschini
                                "%s/sda" % file_storage_dir))
2979 0f1a06e3 Manuel Franceschini
    file_sdb_dev = objects.Disk(dev_type=constants.LD_FILE, size=swap_sz,
2980 0f1a06e3 Manuel Franceschini
                                iv_name="sdb", logical_id=(file_driver,
2981 0f1a06e3 Manuel Franceschini
                                "%s/sdb" % file_storage_dir))
2982 0f1a06e3 Manuel Franceschini
    disks = [file_sda_dev, file_sdb_dev]
2983 a8083063 Iustin Pop
  else:
2984 a8083063 Iustin Pop
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
2985 a8083063 Iustin Pop
  return disks
2986 a8083063 Iustin Pop
2987 a8083063 Iustin Pop
2988 a0c3fea1 Michael Hanselmann
def _GetInstanceInfoText(instance):
2989 3ecf6786 Iustin Pop
  """Compute that text that should be added to the disk's metadata.
2990 3ecf6786 Iustin Pop

2991 3ecf6786 Iustin Pop
  """
2992 a0c3fea1 Michael Hanselmann
  return "originstname+%s" % instance.name
2993 a0c3fea1 Michael Hanselmann
2994 a0c3fea1 Michael Hanselmann
2995 a8083063 Iustin Pop
def _CreateDisks(cfg, instance):
2996 a8083063 Iustin Pop
  """Create all disks for an instance.
2997 a8083063 Iustin Pop

2998 a8083063 Iustin Pop
  This abstracts away some work from AddInstance.
2999 a8083063 Iustin Pop

3000 a8083063 Iustin Pop
  Args:
3001 a8083063 Iustin Pop
    instance: the instance object
3002 a8083063 Iustin Pop

3003 a8083063 Iustin Pop
  Returns:
3004 a8083063 Iustin Pop
    True or False showing the success of the creation process
3005 a8083063 Iustin Pop

3006 a8083063 Iustin Pop
  """
3007 a0c3fea1 Michael Hanselmann
  info = _GetInstanceInfoText(instance)
3008 a0c3fea1 Michael Hanselmann
3009 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3010 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3011 0f1a06e3 Manuel Franceschini
    result = rpc.call_file_storage_dir_create(instance.primary_node,
3012 0f1a06e3 Manuel Franceschini
                                              file_storage_dir)
3013 0f1a06e3 Manuel Franceschini
3014 0f1a06e3 Manuel Franceschini
    if not result:
3015 b62ddbe5 Guido Trotter
      logger.Error("Could not connect to node '%s'" % instance.primary_node)
3016 0f1a06e3 Manuel Franceschini
      return False
3017 0f1a06e3 Manuel Franceschini
3018 0f1a06e3 Manuel Franceschini
    if not result[0]:
3019 0f1a06e3 Manuel Franceschini
      logger.Error("failed to create directory '%s'" % file_storage_dir)
3020 0f1a06e3 Manuel Franceschini
      return False
3021 0f1a06e3 Manuel Franceschini
3022 a8083063 Iustin Pop
  for device in instance.disks:
3023 a8083063 Iustin Pop
    logger.Info("creating volume %s for instance %s" %
3024 1c6e3627 Manuel Franceschini
                (device.iv_name, instance.name))
3025 a8083063 Iustin Pop
    #HARDCODE
3026 a8083063 Iustin Pop
    for secondary_node in instance.secondary_nodes:
3027 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, instance,
3028 3f78eef2 Iustin Pop
                                        device, False, info):
3029 a8083063 Iustin Pop
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
3030 a8083063 Iustin Pop
                     (device.iv_name, device, secondary_node))
3031 a8083063 Iustin Pop
        return False
3032 a8083063 Iustin Pop
    #HARDCODE
3033 3f78eef2 Iustin Pop
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node,
3034 3f78eef2 Iustin Pop
                                    instance, device, info):
3035 a8083063 Iustin Pop
      logger.Error("failed to create volume %s on primary!" %
3036 a8083063 Iustin Pop
                   device.iv_name)
3037 a8083063 Iustin Pop
      return False
3038 1c6e3627 Manuel Franceschini
3039 a8083063 Iustin Pop
  return True
3040 a8083063 Iustin Pop
3041 a8083063 Iustin Pop
3042 a8083063 Iustin Pop
def _RemoveDisks(instance, cfg):
3043 a8083063 Iustin Pop
  """Remove all disks for an instance.
3044 a8083063 Iustin Pop

3045 a8083063 Iustin Pop
  This abstracts away some work from `AddInstance()` and
3046 a8083063 Iustin Pop
  `RemoveInstance()`. Note that in case some of the devices couldn't
3047 1d67656e Iustin Pop
  be removed, the removal will continue with the other ones (compare
3048 a8083063 Iustin Pop
  with `_CreateDisks()`).
3049 a8083063 Iustin Pop

3050 a8083063 Iustin Pop
  Args:
3051 a8083063 Iustin Pop
    instance: the instance object
3052 a8083063 Iustin Pop

3053 a8083063 Iustin Pop
  Returns:
3054 a8083063 Iustin Pop
    True or False showing the success of the removal proces
3055 a8083063 Iustin Pop

3056 a8083063 Iustin Pop
  """
3057 a8083063 Iustin Pop
  logger.Info("removing block devices for instance %s" % instance.name)
3058 a8083063 Iustin Pop
3059 a8083063 Iustin Pop
  result = True
3060 a8083063 Iustin Pop
  for device in instance.disks:
3061 a8083063 Iustin Pop
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3062 a8083063 Iustin Pop
      cfg.SetDiskID(disk, node)
3063 a8083063 Iustin Pop
      if not rpc.call_blockdev_remove(node, disk):
3064 a8083063 Iustin Pop
        logger.Error("could not remove block device %s on node %s,"
3065 a8083063 Iustin Pop
                     " continuing anyway" %
3066 a8083063 Iustin Pop
                     (device.iv_name, node))
3067 a8083063 Iustin Pop
        result = False
3068 0f1a06e3 Manuel Franceschini
3069 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3070 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3071 0f1a06e3 Manuel Franceschini
    if not rpc.call_file_storage_dir_remove(instance.primary_node,
3072 0f1a06e3 Manuel Franceschini
                                            file_storage_dir):
3073 0f1a06e3 Manuel Franceschini
      logger.Error("could not remove directory '%s'" % file_storage_dir)
3074 0f1a06e3 Manuel Franceschini
      result = False
3075 0f1a06e3 Manuel Franceschini
3076 a8083063 Iustin Pop
  return result
3077 a8083063 Iustin Pop
3078 a8083063 Iustin Pop
3079 e2fe6369 Iustin Pop
def _ComputeDiskSize(disk_template, disk_size, swap_size):
3080 e2fe6369 Iustin Pop
  """Compute disk size requirements in the volume group
3081 e2fe6369 Iustin Pop

3082 e2fe6369 Iustin Pop
  This is currently hard-coded for the two-drive layout.
3083 e2fe6369 Iustin Pop

3084 e2fe6369 Iustin Pop
  """
3085 e2fe6369 Iustin Pop
  # Required free disk space as a function of disk and swap space
3086 e2fe6369 Iustin Pop
  req_size_dict = {
3087 e2fe6369 Iustin Pop
    constants.DT_DISKLESS: None,
3088 e2fe6369 Iustin Pop
    constants.DT_PLAIN: disk_size + swap_size,
3089 e2fe6369 Iustin Pop
    # 256 MB are added for drbd metadata, 128MB for each drbd device
3090 e2fe6369 Iustin Pop
    constants.DT_DRBD8: disk_size + swap_size + 256,
3091 e2fe6369 Iustin Pop
    constants.DT_FILE: None,
3092 e2fe6369 Iustin Pop
  }
3093 e2fe6369 Iustin Pop
3094 e2fe6369 Iustin Pop
  if disk_template not in req_size_dict:
3095 e2fe6369 Iustin Pop
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3096 e2fe6369 Iustin Pop
                                 " is unknown" %  disk_template)
3097 e2fe6369 Iustin Pop
3098 e2fe6369 Iustin Pop
  return req_size_dict[disk_template]
3099 e2fe6369 Iustin Pop
3100 e2fe6369 Iustin Pop
3101 a8083063 Iustin Pop
class LUCreateInstance(LogicalUnit):
3102 a8083063 Iustin Pop
  """Create an instance.
3103 a8083063 Iustin Pop

3104 a8083063 Iustin Pop
  """
3105 a8083063 Iustin Pop
  HPATH = "instance-add"
3106 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3107 538475ca Iustin Pop
  _OP_REQP = ["instance_name", "mem_size", "disk_size",
3108 a8083063 Iustin Pop
              "disk_template", "swap_size", "mode", "start", "vcpus",
3109 1862d460 Alexander Schreiber
              "wait_for_sync", "ip_check", "mac"]
3110 7baf741d Guido Trotter
  REQ_BGL = False
3111 7baf741d Guido Trotter
3112 7baf741d Guido Trotter
  def _ExpandNode(self, node):
3113 7baf741d Guido Trotter
    """Expands and checks one node name.
3114 7baf741d Guido Trotter

3115 7baf741d Guido Trotter
    """
3116 7baf741d Guido Trotter
    node_full = self.cfg.ExpandNodeName(node)
3117 7baf741d Guido Trotter
    if node_full is None:
3118 7baf741d Guido Trotter
      raise errors.OpPrereqError("Unknown node %s" % node)
3119 7baf741d Guido Trotter
    return node_full
3120 7baf741d Guido Trotter
3121 7baf741d Guido Trotter
  def ExpandNames(self):
3122 7baf741d Guido Trotter
    """ExpandNames for CreateInstance.
3123 7baf741d Guido Trotter

3124 7baf741d Guido Trotter
    Figure out the right locks for instance creation.
3125 7baf741d Guido Trotter

3126 7baf741d Guido Trotter
    """
3127 7baf741d Guido Trotter
    self.needed_locks = {}
3128 7baf741d Guido Trotter
3129 7baf741d Guido Trotter
    # set optional parameters to none if they don't exist
3130 7baf741d Guido Trotter
    for attr in ["kernel_path", "initrd_path", "pnode", "snode",
3131 7baf741d Guido Trotter
                 "iallocator", "hvm_boot_order", "hvm_acpi", "hvm_pae",
3132 7baf741d Guido Trotter
                 "hvm_cdrom_image_path", "hvm_nic_type", "hvm_disk_type",
3133 7baf741d Guido Trotter
                 "vnc_bind_address"]:
3134 7baf741d Guido Trotter
      if not hasattr(self.op, attr):
3135 7baf741d Guido Trotter
        setattr(self.op, attr, None)
3136 7baf741d Guido Trotter
3137 7baf741d Guido Trotter
    # verify creation mode
3138 7baf741d Guido Trotter
    if self.op.mode not in (constants.INSTANCE_CREATE,
3139 7baf741d Guido Trotter
                            constants.INSTANCE_IMPORT):
3140 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3141 7baf741d Guido Trotter
                                 self.op.mode)
3142 7baf741d Guido Trotter
    # disk template and mirror node verification
3143 7baf741d Guido Trotter
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3144 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid disk template name")
3145 7baf741d Guido Trotter
3146 7baf741d Guido Trotter
    #### instance parameters check
3147 7baf741d Guido Trotter
3148 7baf741d Guido Trotter
    # instance name verification
3149 7baf741d Guido Trotter
    hostname1 = utils.HostInfo(self.op.instance_name)
3150 7baf741d Guido Trotter
    self.op.instance_name = instance_name = hostname1.name
3151 7baf741d Guido Trotter
3152 7baf741d Guido Trotter
    # this is just a preventive check, but someone might still add this
3153 7baf741d Guido Trotter
    # instance in the meantime, and creation will fail at lock-add time
3154 7baf741d Guido Trotter
    if instance_name in self.cfg.GetInstanceList():
3155 7baf741d Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3156 7baf741d Guido Trotter
                                 instance_name)
3157 7baf741d Guido Trotter
3158 7baf741d Guido Trotter
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
3159 7baf741d Guido Trotter
3160 7baf741d Guido Trotter
    # ip validity checks
3161 7baf741d Guido Trotter
    ip = getattr(self.op, "ip", None)
3162 7baf741d Guido Trotter
    if ip is None or ip.lower() == "none":
3163 7baf741d Guido Trotter
      inst_ip = None
3164 7baf741d Guido Trotter
    elif ip.lower() == "auto":
3165 7baf741d Guido Trotter
      inst_ip = hostname1.ip
3166 7baf741d Guido Trotter
    else:
3167 7baf741d Guido Trotter
      if not utils.IsValidIP(ip):
3168 7baf741d Guido Trotter
        raise errors.OpPrereqError("given IP address '%s' doesn't look"
3169 7baf741d Guido Trotter
                                   " like a valid IP" % ip)
3170 7baf741d Guido Trotter
      inst_ip = ip
3171 7baf741d Guido Trotter
    self.inst_ip = self.op.ip = inst_ip
3172 7baf741d Guido Trotter
    # used in CheckPrereq for ip ping check
3173 7baf741d Guido Trotter
    self.check_ip = hostname1.ip
3174 7baf741d Guido Trotter
3175 7baf741d Guido Trotter
    # MAC address verification
3176 7baf741d Guido Trotter
    if self.op.mac != "auto":
3177 7baf741d Guido Trotter
      if not utils.IsValidMac(self.op.mac.lower()):
3178 7baf741d Guido Trotter
        raise errors.OpPrereqError("invalid MAC address specified: %s" %
3179 7baf741d Guido Trotter
                                   self.op.mac)
3180 7baf741d Guido Trotter
3181 7baf741d Guido Trotter
    # boot order verification
3182 7baf741d Guido Trotter
    if self.op.hvm_boot_order is not None:
3183 7baf741d Guido Trotter
      if len(self.op.hvm_boot_order.strip("acdn")) != 0:
3184 7baf741d Guido Trotter
        raise errors.OpPrereqError("invalid boot order specified,"
3185 7baf741d Guido Trotter
                                   " must be one or more of [acdn]")
3186 7baf741d Guido Trotter
    # file storage checks
3187 7baf741d Guido Trotter
    if (self.op.file_driver and
3188 7baf741d Guido Trotter
        not self.op.file_driver in constants.FILE_DRIVER):
3189 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3190 7baf741d Guido Trotter
                                 self.op.file_driver)
3191 7baf741d Guido Trotter
3192 7baf741d Guido Trotter
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3193 7baf741d Guido Trotter
      raise errors.OpPrereqError("File storage directory path not absolute")
3194 7baf741d Guido Trotter
3195 7baf741d Guido Trotter
    ### Node/iallocator related checks
3196 7baf741d Guido Trotter
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3197 7baf741d Guido Trotter
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3198 7baf741d Guido Trotter
                                 " node must be given")
3199 7baf741d Guido Trotter
3200 7baf741d Guido Trotter
    if self.op.iallocator:
3201 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3202 7baf741d Guido Trotter
    else:
3203 7baf741d Guido Trotter
      self.op.pnode = self._ExpandNode(self.op.pnode)
3204 7baf741d Guido Trotter
      nodelist = [self.op.pnode]
3205 7baf741d Guido Trotter
      if self.op.snode is not None:
3206 7baf741d Guido Trotter
        self.op.snode = self._ExpandNode(self.op.snode)
3207 7baf741d Guido Trotter
        nodelist.append(self.op.snode)
3208 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = nodelist
3209 7baf741d Guido Trotter
3210 7baf741d Guido Trotter
    # in case of import lock the source node too
3211 7baf741d Guido Trotter
    if self.op.mode == constants.INSTANCE_IMPORT:
3212 7baf741d Guido Trotter
      src_node = getattr(self.op, "src_node", None)
3213 7baf741d Guido Trotter
      src_path = getattr(self.op, "src_path", None)
3214 7baf741d Guido Trotter
3215 7baf741d Guido Trotter
      if src_node is None or src_path is None:
3216 7baf741d Guido Trotter
        raise errors.OpPrereqError("Importing an instance requires source"
3217 7baf741d Guido Trotter
                                   " node and path options")
3218 7baf741d Guido Trotter
3219 7baf741d Guido Trotter
      if not os.path.isabs(src_path):
3220 7baf741d Guido Trotter
        raise errors.OpPrereqError("The source path must be absolute")
3221 7baf741d Guido Trotter
3222 7baf741d Guido Trotter
      self.op.src_node = src_node = self._ExpandNode(src_node)
3223 7baf741d Guido Trotter
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
3224 7baf741d Guido Trotter
        self.needed_locks[locking.LEVEL_NODE].append(src_node)
3225 7baf741d Guido Trotter
3226 7baf741d Guido Trotter
    else: # INSTANCE_CREATE
3227 7baf741d Guido Trotter
      if getattr(self.op, "os_type", None) is None:
3228 7baf741d Guido Trotter
        raise errors.OpPrereqError("No guest OS specified")
3229 a8083063 Iustin Pop
3230 538475ca Iustin Pop
  def _RunAllocator(self):
3231 538475ca Iustin Pop
    """Run the allocator based on input opcode.
3232 538475ca Iustin Pop

3233 538475ca Iustin Pop
    """
3234 538475ca Iustin Pop
    disks = [{"size": self.op.disk_size, "mode": "w"},
3235 538475ca Iustin Pop
             {"size": self.op.swap_size, "mode": "w"}]
3236 538475ca Iustin Pop
    nics = [{"mac": self.op.mac, "ip": getattr(self.op, "ip", None),
3237 538475ca Iustin Pop
             "bridge": self.op.bridge}]
3238 d1c2dd75 Iustin Pop
    ial = IAllocator(self.cfg, self.sstore,
3239 29859cb7 Iustin Pop
                     mode=constants.IALLOCATOR_MODE_ALLOC,
3240 d1c2dd75 Iustin Pop
                     name=self.op.instance_name,
3241 d1c2dd75 Iustin Pop
                     disk_template=self.op.disk_template,
3242 d1c2dd75 Iustin Pop
                     tags=[],
3243 d1c2dd75 Iustin Pop
                     os=self.op.os_type,
3244 d1c2dd75 Iustin Pop
                     vcpus=self.op.vcpus,
3245 d1c2dd75 Iustin Pop
                     mem_size=self.op.mem_size,
3246 d1c2dd75 Iustin Pop
                     disks=disks,
3247 d1c2dd75 Iustin Pop
                     nics=nics,
3248 29859cb7 Iustin Pop
                     )
3249 d1c2dd75 Iustin Pop
3250 d1c2dd75 Iustin Pop
    ial.Run(self.op.iallocator)
3251 d1c2dd75 Iustin Pop
3252 d1c2dd75 Iustin Pop
    if not ial.success:
3253 538475ca Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
3254 538475ca Iustin Pop
                                 " iallocator '%s': %s" % (self.op.iallocator,
3255 d1c2dd75 Iustin Pop
                                                           ial.info))
3256 27579978 Iustin Pop
    if len(ial.nodes) != ial.required_nodes:
3257 538475ca Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3258 538475ca Iustin Pop
                                 " of nodes (%s), required %s" %
3259 27579978 Iustin Pop
                                 (len(ial.nodes), ial.required_nodes))
3260 d1c2dd75 Iustin Pop
    self.op.pnode = ial.nodes[0]
3261 538475ca Iustin Pop
    logger.ToStdout("Selected nodes for the instance: %s" %
3262 d1c2dd75 Iustin Pop
                    (", ".join(ial.nodes),))
3263 538475ca Iustin Pop
    logger.Info("Selected nodes for instance %s via iallocator %s: %s" %
3264 d1c2dd75 Iustin Pop
                (self.op.instance_name, self.op.iallocator, ial.nodes))
3265 27579978 Iustin Pop
    if ial.required_nodes == 2:
3266 d1c2dd75 Iustin Pop
      self.op.snode = ial.nodes[1]
3267 538475ca Iustin Pop
3268 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3269 a8083063 Iustin Pop
    """Build hooks env.
3270 a8083063 Iustin Pop

3271 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
3272 a8083063 Iustin Pop

3273 a8083063 Iustin Pop
    """
3274 a8083063 Iustin Pop
    env = {
3275 396e1b78 Michael Hanselmann
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
3276 396e1b78 Michael Hanselmann
      "INSTANCE_DISK_SIZE": self.op.disk_size,
3277 396e1b78 Michael Hanselmann
      "INSTANCE_SWAP_SIZE": self.op.swap_size,
3278 a8083063 Iustin Pop
      "INSTANCE_ADD_MODE": self.op.mode,
3279 a8083063 Iustin Pop
      }
3280 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
3281 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_NODE"] = self.op.src_node
3282 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_PATH"] = self.op.src_path
3283 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_IMAGE"] = self.src_image
3284 396e1b78 Michael Hanselmann
3285 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
3286 396e1b78 Michael Hanselmann
      primary_node=self.op.pnode,
3287 396e1b78 Michael Hanselmann
      secondary_nodes=self.secondaries,
3288 396e1b78 Michael Hanselmann
      status=self.instance_status,
3289 ecb215b5 Michael Hanselmann
      os_type=self.op.os_type,
3290 396e1b78 Michael Hanselmann
      memory=self.op.mem_size,
3291 396e1b78 Michael Hanselmann
      vcpus=self.op.vcpus,
3292 c7b27e9e Iustin Pop
      nics=[(self.inst_ip, self.op.bridge, self.op.mac)],
3293 396e1b78 Michael Hanselmann
    ))
3294 a8083063 Iustin Pop
3295 880478f8 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
3296 a8083063 Iustin Pop
          self.secondaries)
3297 a8083063 Iustin Pop
    return env, nl, nl
3298 a8083063 Iustin Pop
3299 a8083063 Iustin Pop
3300 a8083063 Iustin Pop
  def CheckPrereq(self):
3301 a8083063 Iustin Pop
    """Check prerequisites.
3302 a8083063 Iustin Pop

3303 a8083063 Iustin Pop
    """
3304 eedc99de Manuel Franceschini
    if (not self.cfg.GetVGName() and
3305 eedc99de Manuel Franceschini
        self.op.disk_template not in constants.DTS_NOT_LVM):
3306 eedc99de Manuel Franceschini
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3307 eedc99de Manuel Franceschini
                                 " instances")
3308 eedc99de Manuel Franceschini
3309 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
3310 7baf741d Guido Trotter
      src_node = self.op.src_node
3311 7baf741d Guido Trotter
      src_path = self.op.src_path
3312 a8083063 Iustin Pop
3313 a8083063 Iustin Pop
      export_info = rpc.call_export_info(src_node, src_path)
3314 a8083063 Iustin Pop
3315 a8083063 Iustin Pop
      if not export_info:
3316 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3317 a8083063 Iustin Pop
3318 a8083063 Iustin Pop
      if not export_info.has_section(constants.INISECT_EXP):
3319 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Corrupted export config")
3320 a8083063 Iustin Pop
3321 a8083063 Iustin Pop
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3322 a8083063 Iustin Pop
      if (int(ei_version) != constants.EXPORT_VERSION):
3323 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3324 3ecf6786 Iustin Pop
                                   (ei_version, constants.EXPORT_VERSION))
3325 a8083063 Iustin Pop
3326 a8083063 Iustin Pop
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
3327 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Can't import instance with more than"
3328 3ecf6786 Iustin Pop
                                   " one data disk")
3329 a8083063 Iustin Pop
3330 a8083063 Iustin Pop
      # FIXME: are the old os-es, disk sizes, etc. useful?
3331 a8083063 Iustin Pop
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3332 a8083063 Iustin Pop
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
3333 a8083063 Iustin Pop
                                                         'disk0_dump'))
3334 a8083063 Iustin Pop
      self.src_image = diskimage
3335 901a65c1 Iustin Pop
3336 7baf741d Guido Trotter
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
3337 901a65c1 Iustin Pop
3338 901a65c1 Iustin Pop
    if self.op.start and not self.op.ip_check:
3339 901a65c1 Iustin Pop
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3340 901a65c1 Iustin Pop
                                 " adding an instance in start mode")
3341 901a65c1 Iustin Pop
3342 901a65c1 Iustin Pop
    if self.op.ip_check:
3343 7baf741d Guido Trotter
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
3344 901a65c1 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3345 7baf741d Guido Trotter
                                   (self.check_ip, instance_name))
3346 901a65c1 Iustin Pop
3347 901a65c1 Iustin Pop
    # bridge verification
3348 901a65c1 Iustin Pop
    bridge = getattr(self.op, "bridge", None)
3349 901a65c1 Iustin Pop
    if bridge is None:
3350 901a65c1 Iustin Pop
      self.op.bridge = self.cfg.GetDefBridge()
3351 901a65c1 Iustin Pop
    else:
3352 901a65c1 Iustin Pop
      self.op.bridge = bridge
3353 901a65c1 Iustin Pop
3354 538475ca Iustin Pop
    #### allocator run
3355 538475ca Iustin Pop
3356 538475ca Iustin Pop
    if self.op.iallocator is not None:
3357 538475ca Iustin Pop
      self._RunAllocator()
3358 0f1a06e3 Manuel Franceschini
3359 901a65c1 Iustin Pop
    #### node related checks
3360 901a65c1 Iustin Pop
3361 901a65c1 Iustin Pop
    # check primary node
3362 7baf741d Guido Trotter
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
3363 7baf741d Guido Trotter
    assert self.pnode is not None, \
3364 7baf741d Guido Trotter
      "Cannot retrieve locked node %s" % self.op.pnode
3365 901a65c1 Iustin Pop
    self.secondaries = []
3366 901a65c1 Iustin Pop
3367 901a65c1 Iustin Pop
    # mirror node verification
3368 a1f445d3 Iustin Pop
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3369 7baf741d Guido Trotter
      if self.op.snode is None:
3370 a1f445d3 Iustin Pop
        raise errors.OpPrereqError("The networked disk templates need"
3371 3ecf6786 Iustin Pop
                                   " a mirror node")
3372 7baf741d Guido Trotter
      if self.op.snode == pnode.name:
3373 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The secondary node cannot be"
3374 3ecf6786 Iustin Pop
                                   " the primary node.")
3375 7baf741d Guido Trotter
      self.secondaries.append(self.op.snode)
3376 a8083063 Iustin Pop
3377 e2fe6369 Iustin Pop
    req_size = _ComputeDiskSize(self.op.disk_template,
3378 e2fe6369 Iustin Pop
                                self.op.disk_size, self.op.swap_size)
3379 ed1ebc60 Guido Trotter
3380 8d75db10 Iustin Pop
    # Check lv size requirements
3381 8d75db10 Iustin Pop
    if req_size is not None:
3382 8d75db10 Iustin Pop
      nodenames = [pnode.name] + self.secondaries
3383 8d75db10 Iustin Pop
      nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
3384 8d75db10 Iustin Pop
      for node in nodenames:
3385 8d75db10 Iustin Pop
        info = nodeinfo.get(node, None)
3386 8d75db10 Iustin Pop
        if not info:
3387 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Cannot get current information"
3388 3e91897b Iustin Pop
                                     " from node '%s'" % node)
3389 8d75db10 Iustin Pop
        vg_free = info.get('vg_free', None)
3390 8d75db10 Iustin Pop
        if not isinstance(vg_free, int):
3391 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Can't compute free disk space on"
3392 8d75db10 Iustin Pop
                                     " node %s" % node)
3393 8d75db10 Iustin Pop
        if req_size > info['vg_free']:
3394 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Not enough disk space on target node %s."
3395 8d75db10 Iustin Pop
                                     " %d MB available, %d MB required" %
3396 8d75db10 Iustin Pop
                                     (node, info['vg_free'], req_size))
3397 ed1ebc60 Guido Trotter
3398 a8083063 Iustin Pop
    # os verification
3399 00fe9e38 Guido Trotter
    os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
3400 dfa96ded Guido Trotter
    if not os_obj:
3401 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
3402 3ecf6786 Iustin Pop
                                 " primary node"  % self.op.os_type)
3403 a8083063 Iustin Pop
3404 3b6d8c9b Iustin Pop
    if self.op.kernel_path == constants.VALUE_NONE:
3405 3b6d8c9b Iustin Pop
      raise errors.OpPrereqError("Can't set instance kernel to none")
3406 3b6d8c9b Iustin Pop
3407 901a65c1 Iustin Pop
    # bridge check on primary node
3408 a8083063 Iustin Pop
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
3409 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("target bridge '%s' does not exist on"
3410 3ecf6786 Iustin Pop
                                 " destination node '%s'" %
3411 3ecf6786 Iustin Pop
                                 (self.op.bridge, pnode.name))
3412 a8083063 Iustin Pop
3413 49ce1563 Iustin Pop
    # memory check on primary node
3414 49ce1563 Iustin Pop
    if self.op.start:
3415 49ce1563 Iustin Pop
      _CheckNodeFreeMemory(self.cfg, self.pnode.name,
3416 49ce1563 Iustin Pop
                           "creating instance %s" % self.op.instance_name,
3417 49ce1563 Iustin Pop
                           self.op.mem_size)
3418 49ce1563 Iustin Pop
3419 31a853d2 Iustin Pop
    # hvm_cdrom_image_path verification
3420 31a853d2 Iustin Pop
    if self.op.hvm_cdrom_image_path is not None:
3421 7baf741d Guido Trotter
      # FIXME (als): shouldn't these checks happen on the destination node?
3422 31a853d2 Iustin Pop
      if not os.path.isabs(self.op.hvm_cdrom_image_path):
3423 31a853d2 Iustin Pop
        raise errors.OpPrereqError("The path to the HVM CDROM image must"
3424 31a853d2 Iustin Pop
                                   " be an absolute path or None, not %s" %
3425 31a853d2 Iustin Pop
                                   self.op.hvm_cdrom_image_path)
3426 31a853d2 Iustin Pop
      if not os.path.isfile(self.op.hvm_cdrom_image_path):
3427 31a853d2 Iustin Pop
        raise errors.OpPrereqError("The HVM CDROM image must either be a"
3428 31a853d2 Iustin Pop
                                   " regular file or a symlink pointing to"
3429 31a853d2 Iustin Pop
                                   " an existing regular file, not %s" %
3430 31a853d2 Iustin Pop
                                   self.op.hvm_cdrom_image_path)
3431 31a853d2 Iustin Pop
3432 31a853d2 Iustin Pop
    # vnc_bind_address verification
3433 31a853d2 Iustin Pop
    if self.op.vnc_bind_address is not None:
3434 31a853d2 Iustin Pop
      if not utils.IsValidIP(self.op.vnc_bind_address):
3435 31a853d2 Iustin Pop
        raise errors.OpPrereqError("given VNC bind address '%s' doesn't look"
3436 31a853d2 Iustin Pop
                                   " like a valid IP address" %
3437 31a853d2 Iustin Pop
                                   self.op.vnc_bind_address)
3438 31a853d2 Iustin Pop
3439 5397e0b7 Alexander Schreiber
    # Xen HVM device type checks
3440 5397e0b7 Alexander Schreiber
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
3441 5397e0b7 Alexander Schreiber
      if self.op.hvm_nic_type not in constants.HT_HVM_VALID_NIC_TYPES:
3442 5397e0b7 Alexander Schreiber
        raise errors.OpPrereqError("Invalid NIC type %s specified for Xen HVM"
3443 5397e0b7 Alexander Schreiber
                                   " hypervisor" % self.op.hvm_nic_type)
3444 5397e0b7 Alexander Schreiber
      if self.op.hvm_disk_type not in constants.HT_HVM_VALID_DISK_TYPES:
3445 5397e0b7 Alexander Schreiber
        raise errors.OpPrereqError("Invalid disk type %s specified for Xen HVM"
3446 5397e0b7 Alexander Schreiber
                                   " hypervisor" % self.op.hvm_disk_type)
3447 5397e0b7 Alexander Schreiber
3448 a8083063 Iustin Pop
    if self.op.start:
3449 a8083063 Iustin Pop
      self.instance_status = 'up'
3450 a8083063 Iustin Pop
    else:
3451 a8083063 Iustin Pop
      self.instance_status = 'down'
3452 a8083063 Iustin Pop
3453 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3454 a8083063 Iustin Pop
    """Create and add the instance to the cluster.
3455 a8083063 Iustin Pop

3456 a8083063 Iustin Pop
    """
3457 a8083063 Iustin Pop
    instance = self.op.instance_name
3458 a8083063 Iustin Pop
    pnode_name = self.pnode.name
3459 a8083063 Iustin Pop
3460 1862d460 Alexander Schreiber
    if self.op.mac == "auto":
3461 ba4b62cf Iustin Pop
      mac_address = self.cfg.GenerateMAC()
3462 1862d460 Alexander Schreiber
    else:
3463 ba4b62cf Iustin Pop
      mac_address = self.op.mac
3464 1862d460 Alexander Schreiber
3465 1862d460 Alexander Schreiber
    nic = objects.NIC(bridge=self.op.bridge, mac=mac_address)
3466 a8083063 Iustin Pop
    if self.inst_ip is not None:
3467 a8083063 Iustin Pop
      nic.ip = self.inst_ip
3468 a8083063 Iustin Pop
3469 2a6469d5 Alexander Schreiber
    ht_kind = self.sstore.GetHypervisorType()
3470 2a6469d5 Alexander Schreiber
    if ht_kind in constants.HTS_REQ_PORT:
3471 2a6469d5 Alexander Schreiber
      network_port = self.cfg.AllocatePort()
3472 2a6469d5 Alexander Schreiber
    else:
3473 2a6469d5 Alexander Schreiber
      network_port = None
3474 58acb49d Alexander Schreiber
3475 31a853d2 Iustin Pop
    if self.op.vnc_bind_address is None:
3476 31a853d2 Iustin Pop
      self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
3477 31a853d2 Iustin Pop
3478 2c313123 Manuel Franceschini
    # this is needed because os.path.join does not accept None arguments
3479 2c313123 Manuel Franceschini
    if self.op.file_storage_dir is None:
3480 2c313123 Manuel Franceschini
      string_file_storage_dir = ""
3481 2c313123 Manuel Franceschini
    else:
3482 2c313123 Manuel Franceschini
      string_file_storage_dir = self.op.file_storage_dir
3483 2c313123 Manuel Franceschini
3484 0f1a06e3 Manuel Franceschini
    # build the full file storage dir path
3485 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.normpath(os.path.join(
3486 0f1a06e3 Manuel Franceschini
                                        self.sstore.GetFileStorageDir(),
3487 2c313123 Manuel Franceschini
                                        string_file_storage_dir, instance))
3488 0f1a06e3 Manuel Franceschini
3489 0f1a06e3 Manuel Franceschini
3490 923b1523 Iustin Pop
    disks = _GenerateDiskTemplate(self.cfg,
3491 a8083063 Iustin Pop
                                  self.op.disk_template,
3492 a8083063 Iustin Pop
                                  instance, pnode_name,
3493 a8083063 Iustin Pop
                                  self.secondaries, self.op.disk_size,
3494 0f1a06e3 Manuel Franceschini
                                  self.op.swap_size,
3495 0f1a06e3 Manuel Franceschini
                                  file_storage_dir,
3496 0f1a06e3 Manuel Franceschini
                                  self.op.file_driver)
3497 a8083063 Iustin Pop
3498 a8083063 Iustin Pop
    iobj = objects.Instance(name=instance, os=self.op.os_type,
3499 a8083063 Iustin Pop
                            primary_node=pnode_name,
3500 a8083063 Iustin Pop
                            memory=self.op.mem_size,
3501 a8083063 Iustin Pop
                            vcpus=self.op.vcpus,
3502 a8083063 Iustin Pop
                            nics=[nic], disks=disks,
3503 a8083063 Iustin Pop
                            disk_template=self.op.disk_template,
3504 a8083063 Iustin Pop
                            status=self.instance_status,
3505 58acb49d Alexander Schreiber
                            network_port=network_port,
3506 3b6d8c9b Iustin Pop
                            kernel_path=self.op.kernel_path,
3507 3b6d8c9b Iustin Pop
                            initrd_path=self.op.initrd_path,
3508 25c5878d Alexander Schreiber
                            hvm_boot_order=self.op.hvm_boot_order,
3509 31a853d2 Iustin Pop
                            hvm_acpi=self.op.hvm_acpi,
3510 31a853d2 Iustin Pop
                            hvm_pae=self.op.hvm_pae,
3511 31a853d2 Iustin Pop
                            hvm_cdrom_image_path=self.op.hvm_cdrom_image_path,
3512 31a853d2 Iustin Pop
                            vnc_bind_address=self.op.vnc_bind_address,
3513 5397e0b7 Alexander Schreiber
                            hvm_nic_type=self.op.hvm_nic_type,
3514 5397e0b7 Alexander Schreiber
                            hvm_disk_type=self.op.hvm_disk_type,
3515 a8083063 Iustin Pop
                            )
3516 a8083063 Iustin Pop
3517 a8083063 Iustin Pop
    feedback_fn("* creating instance disks...")
3518 a8083063 Iustin Pop
    if not _CreateDisks(self.cfg, iobj):
3519 a8083063 Iustin Pop
      _RemoveDisks(iobj, self.cfg)
3520 3ecf6786 Iustin Pop
      raise errors.OpExecError("Device creation failed, reverting...")
3521 a8083063 Iustin Pop
3522 a8083063 Iustin Pop
    feedback_fn("adding instance %s to cluster config" % instance)
3523 a8083063 Iustin Pop
3524 a8083063 Iustin Pop
    self.cfg.AddInstance(iobj)
3525 7baf741d Guido Trotter
    # Declare that we don't want to remove the instance lock anymore, as we've
3526 7baf741d Guido Trotter
    # added the instance to the config
3527 7baf741d Guido Trotter
    del self.remove_locks[locking.LEVEL_INSTANCE]
3528 a8083063 Iustin Pop
3529 a8083063 Iustin Pop
    if self.op.wait_for_sync:
3530 5bfac263 Iustin Pop
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc)
3531 a1f445d3 Iustin Pop
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
3532 a8083063 Iustin Pop
      # make sure the disks are not degraded (still sync-ing is ok)
3533 a8083063 Iustin Pop
      time.sleep(15)
3534 a8083063 Iustin Pop
      feedback_fn("* checking mirrors status")
3535 5bfac263 Iustin Pop
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc, oneshot=True)
3536 a8083063 Iustin Pop
    else:
3537 a8083063 Iustin Pop
      disk_abort = False
3538 a8083063 Iustin Pop
3539 a8083063 Iustin Pop
    if disk_abort:
3540 a8083063 Iustin Pop
      _RemoveDisks(iobj, self.cfg)
3541 a8083063 Iustin Pop
      self.cfg.RemoveInstance(iobj.name)
3542 7baf741d Guido Trotter
      # Make sure the instance lock gets removed
3543 7baf741d Guido Trotter
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
3544 3ecf6786 Iustin Pop
      raise errors.OpExecError("There are some degraded disks for"
3545 3ecf6786 Iustin Pop
                               " this instance")
3546 a8083063 Iustin Pop
3547 a8083063 Iustin Pop
    feedback_fn("creating os for instance %s on node %s" %
3548 a8083063 Iustin Pop
                (instance, pnode_name))
3549 a8083063 Iustin Pop
3550 a8083063 Iustin Pop
    if iobj.disk_template != constants.DT_DISKLESS:
3551 a8083063 Iustin Pop
      if self.op.mode == constants.INSTANCE_CREATE:
3552 a8083063 Iustin Pop
        feedback_fn("* running the instance OS create scripts...")
3553 a8083063 Iustin Pop
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
3554 3ecf6786 Iustin Pop
          raise errors.OpExecError("could not add os for instance %s"
3555 3ecf6786 Iustin Pop
                                   " on node %s" %
3556 3ecf6786 Iustin Pop
                                   (instance, pnode_name))
3557 a8083063 Iustin Pop
3558 a8083063 Iustin Pop
      elif self.op.mode == constants.INSTANCE_IMPORT:
3559 a8083063 Iustin Pop
        feedback_fn("* running the instance OS import scripts...")
3560 a8083063 Iustin Pop
        src_node = self.op.src_node
3561 a8083063 Iustin Pop
        src_image = self.src_image
3562 a8083063 Iustin Pop
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
3563 a8083063 Iustin Pop
                                                src_node, src_image):
3564 3ecf6786 Iustin Pop
          raise errors.OpExecError("Could not import os for instance"
3565 3ecf6786 Iustin Pop
                                   " %s on node %s" %
3566 3ecf6786 Iustin Pop
                                   (instance, pnode_name))
3567 a8083063 Iustin Pop
      else:
3568 a8083063 Iustin Pop
        # also checked in the prereq part
3569 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
3570 3ecf6786 Iustin Pop
                                     % self.op.mode)
3571 a8083063 Iustin Pop
3572 a8083063 Iustin Pop
    if self.op.start:
3573 a8083063 Iustin Pop
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
3574 a8083063 Iustin Pop
      feedback_fn("* starting instance...")
3575 a8083063 Iustin Pop
      if not rpc.call_instance_start(pnode_name, iobj, None):
3576 3ecf6786 Iustin Pop
        raise errors.OpExecError("Could not start instance")
3577 a8083063 Iustin Pop
3578 a8083063 Iustin Pop
3579 a8083063 Iustin Pop
class LUConnectConsole(NoHooksLU):
3580 a8083063 Iustin Pop
  """Connect to an instance's console.
3581 a8083063 Iustin Pop

3582 a8083063 Iustin Pop
  This is somewhat special in that it returns the command line that
3583 a8083063 Iustin Pop
  you need to run on the master node in order to connect to the
3584 a8083063 Iustin Pop
  console.
3585 a8083063 Iustin Pop

3586 a8083063 Iustin Pop
  """
3587 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
3588 8659b73e Guido Trotter
  REQ_BGL = False
3589 8659b73e Guido Trotter
3590 8659b73e Guido Trotter
  def ExpandNames(self):
3591 8659b73e Guido Trotter
    self._ExpandAndLockInstance()
3592 a8083063 Iustin Pop
3593 a8083063 Iustin Pop
  def CheckPrereq(self):
3594 a8083063 Iustin Pop
    """Check prerequisites.
3595 a8083063 Iustin Pop

3596 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3597 a8083063 Iustin Pop

3598 a8083063 Iustin Pop
    """
3599 8659b73e Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3600 8659b73e Guido Trotter
    assert self.instance is not None, \
3601 8659b73e Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3602 a8083063 Iustin Pop
3603 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3604 a8083063 Iustin Pop
    """Connect to the console of an instance
3605 a8083063 Iustin Pop

3606 a8083063 Iustin Pop
    """
3607 a8083063 Iustin Pop
    instance = self.instance
3608 a8083063 Iustin Pop
    node = instance.primary_node
3609 a8083063 Iustin Pop
3610 a8083063 Iustin Pop
    node_insts = rpc.call_instance_list([node])[node]
3611 a8083063 Iustin Pop
    if node_insts is False:
3612 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't connect to node %s." % node)
3613 a8083063 Iustin Pop
3614 a8083063 Iustin Pop
    if instance.name not in node_insts:
3615 3ecf6786 Iustin Pop
      raise errors.OpExecError("Instance %s is not running." % instance.name)
3616 a8083063 Iustin Pop
3617 a8083063 Iustin Pop
    logger.Debug("connecting to console of %s on %s" % (instance.name, node))
3618 a8083063 Iustin Pop
3619 a8083063 Iustin Pop
    hyper = hypervisor.GetHypervisor()
3620 30989e69 Alexander Schreiber
    console_cmd = hyper.GetShellCommandForConsole(instance)
3621 b047857b Michael Hanselmann
3622 82122173 Iustin Pop
    # build ssh cmdline
3623 0a80a26f Michael Hanselmann
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
3624 a8083063 Iustin Pop
3625 a8083063 Iustin Pop
3626 a8083063 Iustin Pop
class LUReplaceDisks(LogicalUnit):
3627 a8083063 Iustin Pop
  """Replace the disks of an instance.
3628 a8083063 Iustin Pop

3629 a8083063 Iustin Pop
  """
3630 a8083063 Iustin Pop
  HPATH = "mirrors-replace"
3631 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3632 a9e0c397 Iustin Pop
  _OP_REQP = ["instance_name", "mode", "disks"]
3633 efd990e4 Guido Trotter
  REQ_BGL = False
3634 efd990e4 Guido Trotter
3635 efd990e4 Guido Trotter
  def ExpandNames(self):
3636 efd990e4 Guido Trotter
    self._ExpandAndLockInstance()
3637 efd990e4 Guido Trotter
3638 efd990e4 Guido Trotter
    if not hasattr(self.op, "remote_node"):
3639 efd990e4 Guido Trotter
      self.op.remote_node = None
3640 efd990e4 Guido Trotter
3641 efd990e4 Guido Trotter
    ia_name = getattr(self.op, "iallocator", None)
3642 efd990e4 Guido Trotter
    if ia_name is not None:
3643 efd990e4 Guido Trotter
      if self.op.remote_node is not None:
3644 efd990e4 Guido Trotter
        raise errors.OpPrereqError("Give either the iallocator or the new"
3645 efd990e4 Guido Trotter
                                   " secondary, not both")
3646 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3647 efd990e4 Guido Trotter
    elif self.op.remote_node is not None:
3648 efd990e4 Guido Trotter
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
3649 efd990e4 Guido Trotter
      if remote_node is None:
3650 efd990e4 Guido Trotter
        raise errors.OpPrereqError("Node '%s' not known" %
3651 efd990e4 Guido Trotter
                                   self.op.remote_node)
3652 efd990e4 Guido Trotter
      self.op.remote_node = remote_node
3653 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
3654 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
3655 efd990e4 Guido Trotter
    else:
3656 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = []
3657 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3658 efd990e4 Guido Trotter
3659 efd990e4 Guido Trotter
  def DeclareLocks(self, level):
3660 efd990e4 Guido Trotter
    # If we're not already locking all nodes in the set we have to declare the
3661 efd990e4 Guido Trotter
    # instance's primary/secondary nodes.
3662 efd990e4 Guido Trotter
    if (level == locking.LEVEL_NODE and
3663 efd990e4 Guido Trotter
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
3664 efd990e4 Guido Trotter
      self._LockInstancesNodes()
3665 a8083063 Iustin Pop
3666 b6e82a65 Iustin Pop
  def _RunAllocator(self):
3667 b6e82a65 Iustin Pop
    """Compute a new secondary node using an IAllocator.
3668 b6e82a65 Iustin Pop

3669 b6e82a65 Iustin Pop
    """
3670 b6e82a65 Iustin Pop
    ial = IAllocator(self.cfg, self.sstore,
3671 b6e82a65 Iustin Pop
                     mode=constants.IALLOCATOR_MODE_RELOC,
3672 b6e82a65 Iustin Pop
                     name=self.op.instance_name,
3673 b6e82a65 Iustin Pop
                     relocate_from=[self.sec_node])
3674 b6e82a65 Iustin Pop
3675 b6e82a65 Iustin Pop
    ial.Run(self.op.iallocator)
3676 b6e82a65 Iustin Pop
3677 b6e82a65 Iustin Pop
    if not ial.success:
3678 b6e82a65 Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
3679 b6e82a65 Iustin Pop
                                 " iallocator '%s': %s" % (self.op.iallocator,
3680 b6e82a65 Iustin Pop
                                                           ial.info))
3681 b6e82a65 Iustin Pop
    if len(ial.nodes) != ial.required_nodes:
3682 b6e82a65 Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3683 b6e82a65 Iustin Pop
                                 " of nodes (%s), required %s" %
3684 b6e82a65 Iustin Pop
                                 (len(ial.nodes), ial.required_nodes))
3685 b6e82a65 Iustin Pop
    self.op.remote_node = ial.nodes[0]
3686 b6e82a65 Iustin Pop
    logger.ToStdout("Selected new secondary for the instance: %s" %
3687 b6e82a65 Iustin Pop
                    self.op.remote_node)
3688 b6e82a65 Iustin Pop
3689 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3690 a8083063 Iustin Pop
    """Build hooks env.
3691 a8083063 Iustin Pop

3692 a8083063 Iustin Pop
    This runs on the master, the primary and all the secondaries.
3693 a8083063 Iustin Pop

3694 a8083063 Iustin Pop
    """
3695 a8083063 Iustin Pop
    env = {
3696 a9e0c397 Iustin Pop
      "MODE": self.op.mode,
3697 a8083063 Iustin Pop
      "NEW_SECONDARY": self.op.remote_node,
3698 a8083063 Iustin Pop
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3699 a8083063 Iustin Pop
      }
3700 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3701 0834c866 Iustin Pop
    nl = [
3702 0834c866 Iustin Pop
      self.sstore.GetMasterNode(),
3703 0834c866 Iustin Pop
      self.instance.primary_node,
3704 0834c866 Iustin Pop
      ]
3705 0834c866 Iustin Pop
    if self.op.remote_node is not None:
3706 0834c866 Iustin Pop
      nl.append(self.op.remote_node)
3707 a8083063 Iustin Pop
    return env, nl, nl
3708 a8083063 Iustin Pop
3709 a8083063 Iustin Pop
  def CheckPrereq(self):
3710 a8083063 Iustin Pop
    """Check prerequisites.
3711 a8083063 Iustin Pop

3712 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3713 a8083063 Iustin Pop

3714 a8083063 Iustin Pop
    """
3715 efd990e4 Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3716 efd990e4 Guido Trotter
    assert instance is not None, \
3717 efd990e4 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3718 a8083063 Iustin Pop
    self.instance = instance
3719 a8083063 Iustin Pop
3720 a9e0c397 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3721 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout is not"
3722 a9e0c397 Iustin Pop
                                 " network mirrored.")
3723 a8083063 Iustin Pop
3724 a8083063 Iustin Pop
    if len(instance.secondary_nodes) != 1:
3725 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The instance has a strange layout,"
3726 3ecf6786 Iustin Pop
                                 " expected one secondary but found %d" %
3727 3ecf6786 Iustin Pop
                                 len(instance.secondary_nodes))
3728 a8083063 Iustin Pop
3729 a9e0c397 Iustin Pop
    self.sec_node = instance.secondary_nodes[0]
3730 a9e0c397 Iustin Pop
3731 b6e82a65 Iustin Pop
    ia_name = getattr(self.op, "iallocator", None)
3732 b6e82a65 Iustin Pop
    if ia_name is not None:
3733 de8c7666 Guido Trotter
      self._RunAllocator()
3734 b6e82a65 Iustin Pop
3735 b6e82a65 Iustin Pop
    remote_node = self.op.remote_node
3736 a9e0c397 Iustin Pop
    if remote_node is not None:
3737 a9e0c397 Iustin Pop
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
3738 efd990e4 Guido Trotter
      assert self.remote_node_info is not None, \
3739 efd990e4 Guido Trotter
        "Cannot retrieve locked node %s" % remote_node
3740 a9e0c397 Iustin Pop
    else:
3741 a9e0c397 Iustin Pop
      self.remote_node_info = None
3742 a8083063 Iustin Pop
    if remote_node == instance.primary_node:
3743 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The specified node is the primary node of"
3744 3ecf6786 Iustin Pop
                                 " the instance.")
3745 a9e0c397 Iustin Pop
    elif remote_node == self.sec_node:
3746 0834c866 Iustin Pop
      if self.op.mode == constants.REPLACE_DISK_SEC:
3747 0834c866 Iustin Pop
        # this is for DRBD8, where we can't execute the same mode of
3748 0834c866 Iustin Pop
        # replacement as for drbd7 (no different port allocated)
3749 0834c866 Iustin Pop
        raise errors.OpPrereqError("Same secondary given, cannot execute"
3750 0834c866 Iustin Pop
                                   " replacement")
3751 a9e0c397 Iustin Pop
    if instance.disk_template == constants.DT_DRBD8:
3752 7df43a76 Iustin Pop
      if (self.op.mode == constants.REPLACE_DISK_ALL and
3753 7df43a76 Iustin Pop
          remote_node is not None):
3754 7df43a76 Iustin Pop
        # switch to replace secondary mode
3755 7df43a76 Iustin Pop
        self.op.mode = constants.REPLACE_DISK_SEC
3756 7df43a76 Iustin Pop
3757 a9e0c397 Iustin Pop
      if self.op.mode == constants.REPLACE_DISK_ALL:
3758 12c3449a Michael Hanselmann
        raise errors.OpPrereqError("Template 'drbd' only allows primary or"
3759 a9e0c397 Iustin Pop
                                   " secondary disk replacement, not"
3760 a9e0c397 Iustin Pop
                                   " both at once")
3761 a9e0c397 Iustin Pop
      elif self.op.mode == constants.REPLACE_DISK_PRI:
3762 a9e0c397 Iustin Pop
        if remote_node is not None:
3763 12c3449a Michael Hanselmann
          raise errors.OpPrereqError("Template 'drbd' does not allow changing"
3764 a9e0c397 Iustin Pop
                                     " the secondary while doing a primary"
3765 a9e0c397 Iustin Pop
                                     " node disk replacement")
3766 a9e0c397 Iustin Pop
        self.tgt_node = instance.primary_node
3767 cff90b79 Iustin Pop
        self.oth_node = instance.secondary_nodes[0]
3768 a9e0c397 Iustin Pop
      elif self.op.mode == constants.REPLACE_DISK_SEC:
3769 a9e0c397 Iustin Pop
        self.new_node = remote_node # this can be None, in which case
3770 a9e0c397 Iustin Pop
                                    # we don't change the secondary
3771 a9e0c397 Iustin Pop
        self.tgt_node = instance.secondary_nodes[0]
3772 cff90b79 Iustin Pop
        self.oth_node = instance.primary_node
3773 a9e0c397 Iustin Pop
      else:
3774 a9e0c397 Iustin Pop
        raise errors.ProgrammerError("Unhandled disk replace mode")
3775 a9e0c397 Iustin Pop
3776 a9e0c397 Iustin Pop
    for name in self.op.disks:
3777 a9e0c397 Iustin Pop
      if instance.FindDisk(name) is None:
3778 a9e0c397 Iustin Pop
        raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3779 a9e0c397 Iustin Pop
                                   (name, instance.name))
3780 a8083063 Iustin Pop
3781 a9e0c397 Iustin Pop
  def _ExecD8DiskOnly(self, feedback_fn):
3782 a9e0c397 Iustin Pop
    """Replace a disk on the primary or secondary for dbrd8.
3783 a9e0c397 Iustin Pop

3784 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
3785 a9e0c397 Iustin Pop
      - for each disk to be replaced:
3786 a9e0c397 Iustin Pop
        - create new LVs on the target node with unique names
3787 a9e0c397 Iustin Pop
        - detach old LVs from the drbd device
3788 a9e0c397 Iustin Pop
        - rename old LVs to name_replaced.<time_t>
3789 a9e0c397 Iustin Pop
        - rename new LVs to old LVs
3790 a9e0c397 Iustin Pop
        - attach the new LVs (with the old names now) to the drbd device
3791 a9e0c397 Iustin Pop
      - wait for sync across all devices
3792 a9e0c397 Iustin Pop
      - for each modified disk:
3793 a9e0c397 Iustin Pop
        - remove old LVs (which have the name name_replaces.<time_t>)
3794 a9e0c397 Iustin Pop

3795 a9e0c397 Iustin Pop
    Failures are not very well handled.
3796 cff90b79 Iustin Pop

3797 a9e0c397 Iustin Pop
    """
3798 cff90b79 Iustin Pop
    steps_total = 6
3799 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3800 a9e0c397 Iustin Pop
    instance = self.instance
3801 a9e0c397 Iustin Pop
    iv_names = {}
3802 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
3803 a9e0c397 Iustin Pop
    # start of work
3804 a9e0c397 Iustin Pop
    cfg = self.cfg
3805 a9e0c397 Iustin Pop
    tgt_node = self.tgt_node
3806 cff90b79 Iustin Pop
    oth_node = self.oth_node
3807 cff90b79 Iustin Pop
3808 cff90b79 Iustin Pop
    # Step: check device activation
3809 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
3810 cff90b79 Iustin Pop
    info("checking volume groups")
3811 cff90b79 Iustin Pop
    my_vg = cfg.GetVGName()
3812 cff90b79 Iustin Pop
    results = rpc.call_vg_list([oth_node, tgt_node])
3813 cff90b79 Iustin Pop
    if not results:
3814 cff90b79 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
3815 cff90b79 Iustin Pop
    for node in oth_node, tgt_node:
3816 cff90b79 Iustin Pop
      res = results.get(node, False)
3817 cff90b79 Iustin Pop
      if not res or my_vg not in res:
3818 cff90b79 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3819 cff90b79 Iustin Pop
                                 (my_vg, node))
3820 cff90b79 Iustin Pop
    for dev in instance.disks:
3821 cff90b79 Iustin Pop
      if not dev.iv_name in self.op.disks:
3822 cff90b79 Iustin Pop
        continue
3823 cff90b79 Iustin Pop
      for node in tgt_node, oth_node:
3824 cff90b79 Iustin Pop
        info("checking %s on %s" % (dev.iv_name, node))
3825 cff90b79 Iustin Pop
        cfg.SetDiskID(dev, node)
3826 cff90b79 Iustin Pop
        if not rpc.call_blockdev_find(node, dev):
3827 cff90b79 Iustin Pop
          raise errors.OpExecError("Can't find device %s on node %s" %
3828 cff90b79 Iustin Pop
                                   (dev.iv_name, node))
3829 cff90b79 Iustin Pop
3830 cff90b79 Iustin Pop
    # Step: check other node consistency
3831 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
3832 cff90b79 Iustin Pop
    for dev in instance.disks:
3833 cff90b79 Iustin Pop
      if not dev.iv_name in self.op.disks:
3834 cff90b79 Iustin Pop
        continue
3835 cff90b79 Iustin Pop
      info("checking %s consistency on %s" % (dev.iv_name, oth_node))
3836 cff90b79 Iustin Pop
      if not _CheckDiskConsistency(self.cfg, dev, oth_node,
3837 cff90b79 Iustin Pop
                                   oth_node==instance.primary_node):
3838 cff90b79 Iustin Pop
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
3839 cff90b79 Iustin Pop
                                 " to replace disks on this node (%s)" %
3840 cff90b79 Iustin Pop
                                 (oth_node, tgt_node))
3841 cff90b79 Iustin Pop
3842 cff90b79 Iustin Pop
    # Step: create new storage
3843 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
3844 a9e0c397 Iustin Pop
    for dev in instance.disks:
3845 a9e0c397 Iustin Pop
      if not dev.iv_name in self.op.disks:
3846 a9e0c397 Iustin Pop
        continue
3847 a9e0c397 Iustin Pop
      size = dev.size
3848 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, tgt_node)
3849 a9e0c397 Iustin Pop
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3850 a9e0c397 Iustin Pop
      names = _GenerateUniqueNames(cfg, lv_names)
3851 a9e0c397 Iustin Pop
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3852 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[0]))
3853 a9e0c397 Iustin Pop
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3854 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[1]))
3855 a9e0c397 Iustin Pop
      new_lvs = [lv_data, lv_meta]
3856 a9e0c397 Iustin Pop
      old_lvs = dev.children
3857 a9e0c397 Iustin Pop
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
3858 cff90b79 Iustin Pop
      info("creating new local storage on %s for %s" %
3859 cff90b79 Iustin Pop
           (tgt_node, dev.iv_name))
3860 a9e0c397 Iustin Pop
      # since we *always* want to create this LV, we use the
3861 a9e0c397 Iustin Pop
      # _Create...OnPrimary (which forces the creation), even if we
3862 a9e0c397 Iustin Pop
      # are talking about the secondary node
3863 a9e0c397 Iustin Pop
      for new_lv in new_lvs:
3864 3f78eef2 Iustin Pop
        if not _CreateBlockDevOnPrimary(cfg, tgt_node, instance, new_lv,
3865 a9e0c397 Iustin Pop
                                        _GetInstanceInfoText(instance)):
3866 a9e0c397 Iustin Pop
          raise errors.OpExecError("Failed to create new LV named '%s' on"
3867 a9e0c397 Iustin Pop
                                   " node '%s'" %
3868 a9e0c397 Iustin Pop
                                   (new_lv.logical_id[1], tgt_node))
3869 a9e0c397 Iustin Pop
3870 cff90b79 Iustin Pop
    # Step: for each lv, detach+rename*2+attach
3871 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "change drbd configuration")
3872 cff90b79 Iustin Pop
    for dev, old_lvs, new_lvs in iv_names.itervalues():
3873 cff90b79 Iustin Pop
      info("detaching %s drbd from local storage" % dev.iv_name)
3874 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs):
3875 a9e0c397 Iustin Pop
        raise errors.OpExecError("Can't detach drbd from local storage on node"
3876 a9e0c397 Iustin Pop
                                 " %s for device %s" % (tgt_node, dev.iv_name))
3877 cff90b79 Iustin Pop
      #dev.children = []
3878 cff90b79 Iustin Pop
      #cfg.Update(instance)
3879 a9e0c397 Iustin Pop
3880 a9e0c397 Iustin Pop
      # ok, we created the new LVs, so now we know we have the needed
3881 a9e0c397 Iustin Pop
      # storage; as such, we proceed on the target node to rename
3882 a9e0c397 Iustin Pop
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
3883 c99a3cc0 Manuel Franceschini
      # using the assumption that logical_id == physical_id (which in
3884 a9e0c397 Iustin Pop
      # turn is the unique_id on that node)
3885 cff90b79 Iustin Pop
3886 cff90b79 Iustin Pop
      # FIXME(iustin): use a better name for the replaced LVs
3887 a9e0c397 Iustin Pop
      temp_suffix = int(time.time())
3888 a9e0c397 Iustin Pop
      ren_fn = lambda d, suff: (d.physical_id[0],
3889 a9e0c397 Iustin Pop
                                d.physical_id[1] + "_replaced-%s" % suff)
3890 cff90b79 Iustin Pop
      # build the rename list based on what LVs exist on the node
3891 cff90b79 Iustin Pop
      rlist = []
3892 cff90b79 Iustin Pop
      for to_ren in old_lvs:
3893 cff90b79 Iustin Pop
        find_res = rpc.call_blockdev_find(tgt_node, to_ren)
3894 cff90b79 Iustin Pop
        if find_res is not None: # device exists
3895 cff90b79 Iustin Pop
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
3896 cff90b79 Iustin Pop
3897 cff90b79 Iustin Pop
      info("renaming the old LVs on the target node")
3898 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3899 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
3900 a9e0c397 Iustin Pop
      # now we rename the new LVs to the old LVs
3901 cff90b79 Iustin Pop
      info("renaming the new LVs on the target node")
3902 a9e0c397 Iustin Pop
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
3903 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3904 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
3905 cff90b79 Iustin Pop
3906 cff90b79 Iustin Pop
      for old, new in zip(old_lvs, new_lvs):
3907 cff90b79 Iustin Pop
        new.logical_id = old.logical_id
3908 cff90b79 Iustin Pop
        cfg.SetDiskID(new, tgt_node)
3909 a9e0c397 Iustin Pop
3910 cff90b79 Iustin Pop
      for disk in old_lvs:
3911 cff90b79 Iustin Pop
        disk.logical_id = ren_fn(disk, temp_suffix)
3912 cff90b79 Iustin Pop
        cfg.SetDiskID(disk, tgt_node)
3913 a9e0c397 Iustin Pop
3914 a9e0c397 Iustin Pop
      # now that the new lvs have the old name, we can add them to the device
3915 cff90b79 Iustin Pop
      info("adding new mirror component on %s" % tgt_node)
3916 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs):
3917 a9e0c397 Iustin Pop
        for new_lv in new_lvs:
3918 a9e0c397 Iustin Pop
          if not rpc.call_blockdev_remove(tgt_node, new_lv):
3919 79caa9ed Guido Trotter
            warning("Can't rollback device %s", hint="manually cleanup unused"
3920 cff90b79 Iustin Pop
                    " logical volumes")
3921 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't add local storage to drbd")
3922 a9e0c397 Iustin Pop
3923 a9e0c397 Iustin Pop
      dev.children = new_lvs
3924 a9e0c397 Iustin Pop
      cfg.Update(instance)
3925 a9e0c397 Iustin Pop
3926 cff90b79 Iustin Pop
    # Step: wait for sync
3927 a9e0c397 Iustin Pop
3928 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
3929 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
3930 a9e0c397 Iustin Pop
    # return value
3931 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
3932 5bfac263 Iustin Pop
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3933 a9e0c397 Iustin Pop
3934 a9e0c397 Iustin Pop
    # so check manually all the devices
3935 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3936 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, instance.primary_node)
3937 a9e0c397 Iustin Pop
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3938 a9e0c397 Iustin Pop
      if is_degr:
3939 a9e0c397 Iustin Pop
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3940 a9e0c397 Iustin Pop
3941 cff90b79 Iustin Pop
    # Step: remove old storage
3942 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
3943 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3944 cff90b79 Iustin Pop
      info("remove logical volumes for %s" % name)
3945 a9e0c397 Iustin Pop
      for lv in old_lvs:
3946 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, tgt_node)
3947 a9e0c397 Iustin Pop
        if not rpc.call_blockdev_remove(tgt_node, lv):
3948 79caa9ed Guido Trotter
          warning("Can't remove old LV", hint="manually remove unused LVs")
3949 a9e0c397 Iustin Pop
          continue
3950 a9e0c397 Iustin Pop
3951 a9e0c397 Iustin Pop
  def _ExecD8Secondary(self, feedback_fn):
3952 a9e0c397 Iustin Pop
    """Replace the secondary node for drbd8.
3953 a9e0c397 Iustin Pop

3954 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
3955 a9e0c397 Iustin Pop
      - for all disks of the instance:
3956 a9e0c397 Iustin Pop
        - create new LVs on the new node with same names
3957 a9e0c397 Iustin Pop
        - shutdown the drbd device on the old secondary
3958 a9e0c397 Iustin Pop
        - disconnect the drbd network on the primary
3959 a9e0c397 Iustin Pop
        - create the drbd device on the new secondary
3960 a9e0c397 Iustin Pop
        - network attach the drbd on the primary, using an artifice:
3961 a9e0c397 Iustin Pop
          the drbd code for Attach() will connect to the network if it
3962 a9e0c397 Iustin Pop
          finds a device which is connected to the good local disks but
3963 a9e0c397 Iustin Pop
          not network enabled
3964 a9e0c397 Iustin Pop
      - wait for sync across all devices
3965 a9e0c397 Iustin Pop
      - remove all disks from the old secondary
3966 a9e0c397 Iustin Pop

3967 a9e0c397 Iustin Pop
    Failures are not very well handled.
3968 0834c866 Iustin Pop

3969 a9e0c397 Iustin Pop
    """
3970 0834c866 Iustin Pop
    steps_total = 6
3971 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3972 a9e0c397 Iustin Pop
    instance = self.instance
3973 a9e0c397 Iustin Pop
    iv_names = {}
3974 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
3975 a9e0c397 Iustin Pop
    # start of work
3976 a9e0c397 Iustin Pop
    cfg = self.cfg
3977 a9e0c397 Iustin Pop
    old_node = self.tgt_node
3978 a9e0c397 Iustin Pop
    new_node = self.new_node
3979 a9e0c397 Iustin Pop
    pri_node = instance.primary_node
3980 0834c866 Iustin Pop
3981 0834c866 Iustin Pop
    # Step: check device activation
3982 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
3983 0834c866 Iustin Pop
    info("checking volume groups")
3984 0834c866 Iustin Pop
    my_vg = cfg.GetVGName()
3985 0834c866 Iustin Pop
    results = rpc.call_vg_list([pri_node, new_node])
3986 0834c866 Iustin Pop
    if not results:
3987 0834c866 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
3988 0834c866 Iustin Pop
    for node in pri_node, new_node:
3989 0834c866 Iustin Pop
      res = results.get(node, False)
3990 0834c866 Iustin Pop
      if not res or my_vg not in res:
3991 0834c866 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3992 0834c866 Iustin Pop
                                 (my_vg, node))
3993 0834c866 Iustin Pop
    for dev in instance.disks:
3994 0834c866 Iustin Pop
      if not dev.iv_name in self.op.disks:
3995 0834c866 Iustin Pop
        continue
3996 0834c866 Iustin Pop
      info("checking %s on %s" % (dev.iv_name, pri_node))
3997 0834c866 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
3998 0834c866 Iustin Pop
      if not rpc.call_blockdev_find(pri_node, dev):
3999 0834c866 Iustin Pop
        raise errors.OpExecError("Can't find device %s on node %s" %
4000 0834c866 Iustin Pop
                                 (dev.iv_name, pri_node))
4001 0834c866 Iustin Pop
4002 0834c866 Iustin Pop
    # Step: check other node consistency
4003 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
4004 0834c866 Iustin Pop
    for dev in instance.disks:
4005 0834c866 Iustin Pop
      if not dev.iv_name in self.op.disks:
4006 0834c866 Iustin Pop
        continue
4007 0834c866 Iustin Pop
      info("checking %s consistency on %s" % (dev.iv_name, pri_node))
4008 0834c866 Iustin Pop
      if not _CheckDiskConsistency(self.cfg, dev, pri_node, True, ldisk=True):
4009 0834c866 Iustin Pop
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4010 0834c866 Iustin Pop
                                 " unsafe to replace the secondary" %
4011 0834c866 Iustin Pop
                                 pri_node)
4012 0834c866 Iustin Pop
4013 0834c866 Iustin Pop
    # Step: create new storage
4014 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
4015 468b46f9 Iustin Pop
    for dev in instance.disks:
4016 a9e0c397 Iustin Pop
      size = dev.size
4017 0834c866 Iustin Pop
      info("adding new local storage on %s for %s" % (new_node, dev.iv_name))
4018 a9e0c397 Iustin Pop
      # since we *always* want to create this LV, we use the
4019 a9e0c397 Iustin Pop
      # _Create...OnPrimary (which forces the creation), even if we
4020 a9e0c397 Iustin Pop
      # are talking about the secondary node
4021 a9e0c397 Iustin Pop
      for new_lv in dev.children:
4022 3f78eef2 Iustin Pop
        if not _CreateBlockDevOnPrimary(cfg, new_node, instance, new_lv,
4023 a9e0c397 Iustin Pop
                                        _GetInstanceInfoText(instance)):
4024 a9e0c397 Iustin Pop
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4025 a9e0c397 Iustin Pop
                                   " node '%s'" %
4026 a9e0c397 Iustin Pop
                                   (new_lv.logical_id[1], new_node))
4027 a9e0c397 Iustin Pop
4028 0834c866 Iustin Pop
4029 468b46f9 Iustin Pop
    # Step 4: dbrd minors and drbd setups changes
4030 468b46f9 Iustin Pop
    minors = [None for dev in instance.disks]
4031 468b46f9 Iustin Pop
    logging.debug("Allocated minors %s" % (minors,))
4032 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
4033 468b46f9 Iustin Pop
    for dev, new_minor in zip(instance.disks, minors):
4034 0834c866 Iustin Pop
      size = dev.size
4035 0834c866 Iustin Pop
      info("activating a new drbd on %s for %s" % (new_node, dev.iv_name))
4036 a9e0c397 Iustin Pop
      # create new devices on new_node
4037 ffa1c0dc Iustin Pop
      if pri_node == dev.logical_id[0]:
4038 ffa1c0dc Iustin Pop
        new_logical_id = (pri_node, new_node,
4039 ffa1c0dc Iustin Pop
                          dev.logical_id[2], dev.logical_id[3], new_minor)
4040 ffa1c0dc Iustin Pop
      else:
4041 ffa1c0dc Iustin Pop
        new_logical_id = (new_node, pri_node,
4042 ffa1c0dc Iustin Pop
                          dev.logical_id[2], new_minor, dev.logical_id[4])
4043 468b46f9 Iustin Pop
      iv_names[dev.iv_name] = (dev, dev.children, new_logical_id)
4044 a9e0c397 Iustin Pop
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
4045 ffa1c0dc Iustin Pop
                              logical_id=new_logical_id,
4046 a9e0c397 Iustin Pop
                              children=dev.children)
4047 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnSecondary(cfg, new_node, instance,
4048 3f78eef2 Iustin Pop
                                        new_drbd, False,
4049 a9e0c397 Iustin Pop
                                      _GetInstanceInfoText(instance)):
4050 a9e0c397 Iustin Pop
        raise errors.OpExecError("Failed to create new DRBD on"
4051 a9e0c397 Iustin Pop
                                 " node '%s'" % new_node)
4052 a9e0c397 Iustin Pop
4053 0834c866 Iustin Pop
    for dev in instance.disks:
4054 a9e0c397 Iustin Pop
      # we have new devices, shutdown the drbd on the old secondary
4055 0834c866 Iustin Pop
      info("shutting down drbd for %s on old node" % dev.iv_name)
4056 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, old_node)
4057 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_shutdown(old_node, dev):
4058 0834c866 Iustin Pop
        warning("Failed to shutdown drbd for %s on old node" % dev.iv_name,
4059 79caa9ed Guido Trotter
                hint="Please cleanup this device manually as soon as possible")
4060 a9e0c397 Iustin Pop
4061 642445d9 Iustin Pop
    info("detaching primary drbds from the network (=> standalone)")
4062 642445d9 Iustin Pop
    done = 0
4063 642445d9 Iustin Pop
    for dev in instance.disks:
4064 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4065 642445d9 Iustin Pop
      # set the physical (unique in bdev terms) id to None, meaning
4066 642445d9 Iustin Pop
      # detach from network
4067 ffa1c0dc Iustin Pop
      dev.physical_id = (None, None, None, None, dev.physical_id[4])
4068 642445d9 Iustin Pop
      # and 'find' the device, which will 'fix' it to match the
4069 642445d9 Iustin Pop
      # standalone state
4070 642445d9 Iustin Pop
      if rpc.call_blockdev_find(pri_node, dev):
4071 642445d9 Iustin Pop
        done += 1
4072 642445d9 Iustin Pop
      else:
4073 642445d9 Iustin Pop
        warning("Failed to detach drbd %s from network, unusual case" %
4074 642445d9 Iustin Pop
                dev.iv_name)
4075 642445d9 Iustin Pop
4076 642445d9 Iustin Pop
    if not done:
4077 642445d9 Iustin Pop
      # no detaches succeeded (very unlikely)
4078 642445d9 Iustin Pop
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
4079 642445d9 Iustin Pop
4080 642445d9 Iustin Pop
    # if we managed to detach at least one, we update all the disks of
4081 642445d9 Iustin Pop
    # the instance to point to the new secondary
4082 642445d9 Iustin Pop
    info("updating instance configuration")
4083 468b46f9 Iustin Pop
    for dev, _, new_logical_id in iv_names.itervalues():
4084 468b46f9 Iustin Pop
      dev.logical_id = new_logical_id
4085 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4086 642445d9 Iustin Pop
    cfg.Update(instance)
4087 a9e0c397 Iustin Pop
4088 642445d9 Iustin Pop
    # and now perform the drbd attach
4089 642445d9 Iustin Pop
    info("attaching primary drbds to new secondary (standalone => connected)")
4090 642445d9 Iustin Pop
    failures = []
4091 642445d9 Iustin Pop
    for dev in instance.disks:
4092 642445d9 Iustin Pop
      info("attaching primary drbd for %s to new secondary node" % dev.iv_name)
4093 642445d9 Iustin Pop
      # since the attach is smart, it's enough to 'find' the device,
4094 642445d9 Iustin Pop
      # it will automatically activate the network, if the physical_id
4095 642445d9 Iustin Pop
      # is correct
4096 642445d9 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4097 ffa1c0dc Iustin Pop
      logging.debug("Disk to attach: %s", dev)
4098 642445d9 Iustin Pop
      if not rpc.call_blockdev_find(pri_node, dev):
4099 642445d9 Iustin Pop
        warning("can't attach drbd %s to new secondary!" % dev.iv_name,
4100 642445d9 Iustin Pop
                "please do a gnt-instance info to see the status of disks")
4101 a9e0c397 Iustin Pop
4102 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
4103 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
4104 a9e0c397 Iustin Pop
    # return value
4105 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
4106 5bfac263 Iustin Pop
    _WaitForSync(cfg, instance, self.proc, unlock=True)
4107 a9e0c397 Iustin Pop
4108 a9e0c397 Iustin Pop
    # so check manually all the devices
4109 ffa1c0dc Iustin Pop
    for name, (dev, old_lvs, _) in iv_names.iteritems():
4110 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4111 a9e0c397 Iustin Pop
      is_degr = rpc.call_blockdev_find(pri_node, dev)[5]
4112 a9e0c397 Iustin Pop
      if is_degr:
4113 a9e0c397 Iustin Pop
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4114 a9e0c397 Iustin Pop
4115 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
4116 ffa1c0dc Iustin Pop
    for name, (dev, old_lvs, _) in iv_names.iteritems():
4117 0834c866 Iustin Pop
      info("remove logical volumes for %s" % name)
4118 a9e0c397 Iustin Pop
      for lv in old_lvs:
4119 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, old_node)
4120 a9e0c397 Iustin Pop
        if not rpc.call_blockdev_remove(old_node, lv):
4121 0834c866 Iustin Pop
          warning("Can't remove LV on old secondary",
4122 79caa9ed Guido Trotter
                  hint="Cleanup stale volumes by hand")
4123 a9e0c397 Iustin Pop
4124 a9e0c397 Iustin Pop
  def Exec(self, feedback_fn):
4125 a9e0c397 Iustin Pop
    """Execute disk replacement.
4126 a9e0c397 Iustin Pop

4127 a9e0c397 Iustin Pop
    This dispatches the disk replacement to the appropriate handler.
4128 a9e0c397 Iustin Pop

4129 a9e0c397 Iustin Pop
    """
4130 a9e0c397 Iustin Pop
    instance = self.instance
4131 22985314 Guido Trotter
4132 22985314 Guido Trotter
    # Activate the instance disks if we're replacing them on a down instance
4133 22985314 Guido Trotter
    if instance.status == "down":
4134 023e3296 Guido Trotter
      _StartInstanceDisks(self.cfg, instance, True)
4135 22985314 Guido Trotter
4136 abdf0113 Iustin Pop
    if instance.disk_template == constants.DT_DRBD8:
4137 a9e0c397 Iustin Pop
      if self.op.remote_node is None:
4138 a9e0c397 Iustin Pop
        fn = self._ExecD8DiskOnly
4139 a9e0c397 Iustin Pop
      else:
4140 a9e0c397 Iustin Pop
        fn = self._ExecD8Secondary
4141 a9e0c397 Iustin Pop
    else:
4142 a9e0c397 Iustin Pop
      raise errors.ProgrammerError("Unhandled disk replacement case")
4143 22985314 Guido Trotter
4144 22985314 Guido Trotter
    ret = fn(feedback_fn)
4145 22985314 Guido Trotter
4146 22985314 Guido Trotter
    # Deactivate the instance disks if we're replacing them on a down instance
4147 22985314 Guido Trotter
    if instance.status == "down":
4148 023e3296 Guido Trotter
      _SafeShutdownInstanceDisks(instance, self.cfg)
4149 22985314 Guido Trotter
4150 22985314 Guido Trotter
    return ret
4151 a9e0c397 Iustin Pop
4152 a8083063 Iustin Pop
4153 8729e0d7 Iustin Pop
class LUGrowDisk(LogicalUnit):
4154 8729e0d7 Iustin Pop
  """Grow a disk of an instance.
4155 8729e0d7 Iustin Pop

4156 8729e0d7 Iustin Pop
  """
4157 8729e0d7 Iustin Pop
  HPATH = "disk-grow"
4158 8729e0d7 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4159 8729e0d7 Iustin Pop
  _OP_REQP = ["instance_name", "disk", "amount"]
4160 31e63dbf Guido Trotter
  REQ_BGL = False
4161 31e63dbf Guido Trotter
4162 31e63dbf Guido Trotter
  def ExpandNames(self):
4163 31e63dbf Guido Trotter
    self._ExpandAndLockInstance()
4164 31e63dbf Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
4165 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4166 31e63dbf Guido Trotter
4167 31e63dbf Guido Trotter
  def DeclareLocks(self, level):
4168 31e63dbf Guido Trotter
    if level == locking.LEVEL_NODE:
4169 31e63dbf Guido Trotter
      self._LockInstancesNodes()
4170 8729e0d7 Iustin Pop
4171 8729e0d7 Iustin Pop
  def BuildHooksEnv(self):
4172 8729e0d7 Iustin Pop
    """Build hooks env.
4173 8729e0d7 Iustin Pop

4174 8729e0d7 Iustin Pop
    This runs on the master, the primary and all the secondaries.
4175 8729e0d7 Iustin Pop

4176 8729e0d7 Iustin Pop
    """
4177 8729e0d7 Iustin Pop
    env = {
4178 8729e0d7 Iustin Pop
      "DISK": self.op.disk,
4179 8729e0d7 Iustin Pop
      "AMOUNT": self.op.amount,
4180 8729e0d7 Iustin Pop
      }
4181 8729e0d7 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self.instance))
4182 8729e0d7 Iustin Pop
    nl = [
4183 8729e0d7 Iustin Pop
      self.sstore.GetMasterNode(),
4184 8729e0d7 Iustin Pop
      self.instance.primary_node,
4185 8729e0d7 Iustin Pop
      ]
4186 8729e0d7 Iustin Pop
    return env, nl, nl
4187 8729e0d7 Iustin Pop
4188 8729e0d7 Iustin Pop
  def CheckPrereq(self):
4189 8729e0d7 Iustin Pop
    """Check prerequisites.
4190 8729e0d7 Iustin Pop

4191 8729e0d7 Iustin Pop
    This checks that the instance is in the cluster.
4192 8729e0d7 Iustin Pop

4193 8729e0d7 Iustin Pop
    """
4194 31e63dbf Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4195 31e63dbf Guido Trotter
    assert instance is not None, \
4196 31e63dbf Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4197 31e63dbf Guido Trotter
4198 8729e0d7 Iustin Pop
    self.instance = instance
4199 8729e0d7 Iustin Pop
4200 8729e0d7 Iustin Pop
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
4201 8729e0d7 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout does not support"
4202 8729e0d7 Iustin Pop
                                 " growing.")
4203 8729e0d7 Iustin Pop
4204 8729e0d7 Iustin Pop
    if instance.FindDisk(self.op.disk) is None:
4205 8729e0d7 Iustin Pop
      raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
4206 c7cdfc90 Iustin Pop
                                 (self.op.disk, instance.name))
4207 8729e0d7 Iustin Pop
4208 8729e0d7 Iustin Pop
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
4209 8729e0d7 Iustin Pop
    nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
4210 8729e0d7 Iustin Pop
    for node in nodenames:
4211 8729e0d7 Iustin Pop
      info = nodeinfo.get(node, None)
4212 8729e0d7 Iustin Pop
      if not info:
4213 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Cannot get current information"
4214 8729e0d7 Iustin Pop
                                   " from node '%s'" % node)
4215 8729e0d7 Iustin Pop
      vg_free = info.get('vg_free', None)
4216 8729e0d7 Iustin Pop
      if not isinstance(vg_free, int):
4217 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Can't compute free disk space on"
4218 8729e0d7 Iustin Pop
                                   " node %s" % node)
4219 8729e0d7 Iustin Pop
      if self.op.amount > info['vg_free']:
4220 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
4221 8729e0d7 Iustin Pop
                                   " %d MiB available, %d MiB required" %
4222 8729e0d7 Iustin Pop
                                   (node, info['vg_free'], self.op.amount))
4223 8729e0d7 Iustin Pop
4224 8729e0d7 Iustin Pop
  def Exec(self, feedback_fn):
4225 8729e0d7 Iustin Pop
    """Execute disk grow.
4226 8729e0d7 Iustin Pop

4227 8729e0d7 Iustin Pop
    """
4228 8729e0d7 Iustin Pop
    instance = self.instance
4229 8729e0d7 Iustin Pop
    disk = instance.FindDisk(self.op.disk)
4230 8729e0d7 Iustin Pop
    for node in (instance.secondary_nodes + (instance.primary_node,)):
4231 8729e0d7 Iustin Pop
      self.cfg.SetDiskID(disk, node)
4232 8729e0d7 Iustin Pop
      result = rpc.call_blockdev_grow(node, disk, self.op.amount)
4233 86de84dd Guido Trotter
      if not result or not isinstance(result, (list, tuple)) or len(result) != 2:
4234 8729e0d7 Iustin Pop
        raise errors.OpExecError("grow request failed to node %s" % node)
4235 8729e0d7 Iustin Pop
      elif not result[0]:
4236 8729e0d7 Iustin Pop
        raise errors.OpExecError("grow request failed to node %s: %s" %
4237 8729e0d7 Iustin Pop
                                 (node, result[1]))
4238 8729e0d7 Iustin Pop
    disk.RecordGrow(self.op.amount)
4239 8729e0d7 Iustin Pop
    self.cfg.Update(instance)
4240 8729e0d7 Iustin Pop
    return
4241 8729e0d7 Iustin Pop
4242 8729e0d7 Iustin Pop
4243 a8083063 Iustin Pop
class LUQueryInstanceData(NoHooksLU):
4244 a8083063 Iustin Pop
  """Query runtime instance data.
4245 a8083063 Iustin Pop

4246 a8083063 Iustin Pop
  """
4247 a8083063 Iustin Pop
  _OP_REQP = ["instances"]
4248 a987fa48 Guido Trotter
  REQ_BGL = False
4249 a987fa48 Guido Trotter
  def ExpandNames(self):
4250 a987fa48 Guido Trotter
    self.needed_locks = {}
4251 a987fa48 Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
4252 a987fa48 Guido Trotter
4253 a987fa48 Guido Trotter
    if not isinstance(self.op.instances, list):
4254 a987fa48 Guido Trotter
      raise errors.OpPrereqError("Invalid argument type 'instances'")
4255 a987fa48 Guido Trotter
4256 a987fa48 Guido Trotter
    if self.op.instances:
4257 a987fa48 Guido Trotter
      self.wanted_names = []
4258 a987fa48 Guido Trotter
      for name in self.op.instances:
4259 a987fa48 Guido Trotter
        full_name = self.cfg.ExpandInstanceName(name)
4260 a987fa48 Guido Trotter
        if full_name is None:
4261 a987fa48 Guido Trotter
          raise errors.OpPrereqError("Instance '%s' not known" %
4262 a987fa48 Guido Trotter
                                     self.op.instance_name)
4263 a987fa48 Guido Trotter
        self.wanted_names.append(full_name)
4264 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
4265 a987fa48 Guido Trotter
    else:
4266 a987fa48 Guido Trotter
      self.wanted_names = None
4267 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4268 a987fa48 Guido Trotter
4269 a987fa48 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
4270 a987fa48 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4271 a987fa48 Guido Trotter
4272 a987fa48 Guido Trotter
  def DeclareLocks(self, level):
4273 a987fa48 Guido Trotter
    if level == locking.LEVEL_NODE:
4274 a987fa48 Guido Trotter
      self._LockInstancesNodes()
4275 a8083063 Iustin Pop
4276 a8083063 Iustin Pop
  def CheckPrereq(self):
4277 a8083063 Iustin Pop
    """Check prerequisites.
4278 a8083063 Iustin Pop

4279 a8083063 Iustin Pop
    This only checks the optional instance list against the existing names.
4280 a8083063 Iustin Pop

4281 a8083063 Iustin Pop
    """
4282 a987fa48 Guido Trotter
    if self.wanted_names is None:
4283 a987fa48 Guido Trotter
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4284 a8083063 Iustin Pop
4285 a987fa48 Guido Trotter
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4286 a987fa48 Guido Trotter
                             in self.wanted_names]
4287 a987fa48 Guido Trotter
    return
4288 a8083063 Iustin Pop
4289 a8083063 Iustin Pop
  def _ComputeDiskStatus(self, instance, snode, dev):
4290 a8083063 Iustin Pop
    """Compute block device status.
4291 a8083063 Iustin Pop

4292 a8083063 Iustin Pop
    """
4293 a8083063 Iustin Pop
    self.cfg.SetDiskID(dev, instance.primary_node)
4294 a8083063 Iustin Pop
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
4295 a1f445d3 Iustin Pop
    if dev.dev_type in constants.LDS_DRBD:
4296 a8083063 Iustin Pop
      # we change the snode then (otherwise we use the one passed in)
4297 a8083063 Iustin Pop
      if dev.logical_id[0] == instance.primary_node:
4298 a8083063 Iustin Pop
        snode = dev.logical_id[1]
4299 a8083063 Iustin Pop
      else:
4300 a8083063 Iustin Pop
        snode = dev.logical_id[0]
4301 a8083063 Iustin Pop
4302 a8083063 Iustin Pop
    if snode:
4303 a8083063 Iustin Pop
      self.cfg.SetDiskID(dev, snode)
4304 a8083063 Iustin Pop
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
4305 a8083063 Iustin Pop
    else:
4306 a8083063 Iustin Pop
      dev_sstatus = None
4307 a8083063 Iustin Pop
4308 a8083063 Iustin Pop
    if dev.children:
4309 a8083063 Iustin Pop
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4310 a8083063 Iustin Pop
                      for child in dev.children]
4311 a8083063 Iustin Pop
    else:
4312 a8083063 Iustin Pop
      dev_children = []
4313 a8083063 Iustin Pop
4314 a8083063 Iustin Pop
    data = {
4315 a8083063 Iustin Pop
      "iv_name": dev.iv_name,
4316 a8083063 Iustin Pop
      "dev_type": dev.dev_type,
4317 a8083063 Iustin Pop
      "logical_id": dev.logical_id,
4318 a8083063 Iustin Pop
      "physical_id": dev.physical_id,
4319 a8083063 Iustin Pop
      "pstatus": dev_pstatus,
4320 a8083063 Iustin Pop
      "sstatus": dev_sstatus,
4321 a8083063 Iustin Pop
      "children": dev_children,
4322 a8083063 Iustin Pop
      }
4323 a8083063 Iustin Pop
4324 a8083063 Iustin Pop
    return data
4325 a8083063 Iustin Pop
4326 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4327 a8083063 Iustin Pop
    """Gather and return data"""
4328 a8083063 Iustin Pop
    result = {}
4329 a8083063 Iustin Pop
    for instance in self.wanted_instances:
4330 a8083063 Iustin Pop
      remote_info = rpc.call_instance_info(instance.primary_node,
4331 a8083063 Iustin Pop
                                                instance.name)
4332 a8083063 Iustin Pop
      if remote_info and "state" in remote_info:
4333 a8083063 Iustin Pop
        remote_state = "up"
4334 a8083063 Iustin Pop
      else:
4335 a8083063 Iustin Pop
        remote_state = "down"
4336 a8083063 Iustin Pop
      if instance.status == "down":
4337 a8083063 Iustin Pop
        config_state = "down"
4338 a8083063 Iustin Pop
      else:
4339 a8083063 Iustin Pop
        config_state = "up"
4340 a8083063 Iustin Pop
4341 a8083063 Iustin Pop
      disks = [self._ComputeDiskStatus(instance, None, device)
4342 a8083063 Iustin Pop
               for device in instance.disks]
4343 a8083063 Iustin Pop
4344 a8083063 Iustin Pop
      idict = {
4345 a8083063 Iustin Pop
        "name": instance.name,
4346 a8083063 Iustin Pop
        "config_state": config_state,
4347 a8083063 Iustin Pop
        "run_state": remote_state,
4348 a8083063 Iustin Pop
        "pnode": instance.primary_node,
4349 a8083063 Iustin Pop
        "snodes": instance.secondary_nodes,
4350 a8083063 Iustin Pop
        "os": instance.os,
4351 a8083063 Iustin Pop
        "memory": instance.memory,
4352 a8083063 Iustin Pop
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
4353 a8083063 Iustin Pop
        "disks": disks,
4354 f55ff7ec Iustin Pop
        "vcpus": instance.vcpus,
4355 a8083063 Iustin Pop
        }
4356 a8083063 Iustin Pop
4357 a8340917 Iustin Pop
      htkind = self.sstore.GetHypervisorType()
4358 a8340917 Iustin Pop
      if htkind == constants.HT_XEN_PVM30:
4359 a8340917 Iustin Pop
        idict["kernel_path"] = instance.kernel_path
4360 a8340917 Iustin Pop
        idict["initrd_path"] = instance.initrd_path
4361 a8340917 Iustin Pop
4362 a8340917 Iustin Pop
      if htkind == constants.HT_XEN_HVM31:
4363 a8340917 Iustin Pop
        idict["hvm_boot_order"] = instance.hvm_boot_order
4364 a8340917 Iustin Pop
        idict["hvm_acpi"] = instance.hvm_acpi
4365 a8340917 Iustin Pop
        idict["hvm_pae"] = instance.hvm_pae
4366 a8340917 Iustin Pop
        idict["hvm_cdrom_image_path"] = instance.hvm_cdrom_image_path
4367 5397e0b7 Alexander Schreiber
        idict["hvm_nic_type"] = instance.hvm_nic_type
4368 5397e0b7 Alexander Schreiber
        idict["hvm_disk_type"] = instance.hvm_disk_type
4369 a8340917 Iustin Pop
4370 a8340917 Iustin Pop
      if htkind in constants.HTS_REQ_PORT:
4371 d0c11cf7 Alexander Schreiber
        if instance.vnc_bind_address is None:
4372 d0c11cf7 Alexander Schreiber
          vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4373 d0c11cf7 Alexander Schreiber
        else:
4374 d0c11cf7 Alexander Schreiber
          vnc_bind_address = instance.vnc_bind_address
4375 34b6ab97 Alexander Schreiber
        if instance.network_port is None:
4376 34b6ab97 Alexander Schreiber
          vnc_console_port = None
4377 d0c11cf7 Alexander Schreiber
        elif vnc_bind_address == constants.BIND_ADDRESS_GLOBAL:
4378 a4273aba Alexander Schreiber
          vnc_console_port = "%s:%s" % (instance.primary_node,
4379 34b6ab97 Alexander Schreiber
                                       instance.network_port)
4380 d0c11cf7 Alexander Schreiber
        elif vnc_bind_address == constants.LOCALHOST_IP_ADDRESS:
4381 d0c11cf7 Alexander Schreiber
          vnc_console_port = "%s:%s on node %s" % (vnc_bind_address,
4382 a4273aba Alexander Schreiber
                                                   instance.network_port,
4383 a4273aba Alexander Schreiber
                                                   instance.primary_node)
4384 34b6ab97 Alexander Schreiber
        else:
4385 34b6ab97 Alexander Schreiber
          vnc_console_port = "%s:%s" % (instance.vnc_bind_address,
4386 34b6ab97 Alexander Schreiber
                                        instance.network_port)
4387 34b6ab97 Alexander Schreiber
        idict["vnc_console_port"] = vnc_console_port
4388 d0c11cf7 Alexander Schreiber
        idict["vnc_bind_address"] = vnc_bind_address
4389 a8340917 Iustin Pop
        idict["network_port"] = instance.network_port
4390 a8340917 Iustin Pop
4391 a8083063 Iustin Pop
      result[instance.name] = idict
4392 a8083063 Iustin Pop
4393 a8083063 Iustin Pop
    return result
4394 a8083063 Iustin Pop
4395 a8083063 Iustin Pop
4396 7767bbf5 Manuel Franceschini
class LUSetInstanceParams(LogicalUnit):
4397 a8083063 Iustin Pop
  """Modifies an instances's parameters.
4398 a8083063 Iustin Pop

4399 a8083063 Iustin Pop
  """
4400 a8083063 Iustin Pop
  HPATH = "instance-modify"
4401 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4402 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
4403 1a5c7281 Guido Trotter
  REQ_BGL = False
4404 1a5c7281 Guido Trotter
4405 1a5c7281 Guido Trotter
  def ExpandNames(self):
4406 1a5c7281 Guido Trotter
    self._ExpandAndLockInstance()
4407 a8083063 Iustin Pop
4408 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4409 a8083063 Iustin Pop
    """Build hooks env.
4410 a8083063 Iustin Pop

4411 a8083063 Iustin Pop
    This runs on the master, primary and secondaries.
4412 a8083063 Iustin Pop

4413 a8083063 Iustin Pop
    """
4414 396e1b78 Michael Hanselmann
    args = dict()
4415 a8083063 Iustin Pop
    if self.mem:
4416 396e1b78 Michael Hanselmann
      args['memory'] = self.mem
4417 a8083063 Iustin Pop
    if self.vcpus:
4418 396e1b78 Michael Hanselmann
      args['vcpus'] = self.vcpus
4419 ef756965 Iustin Pop
    if self.do_ip or self.do_bridge or self.mac:
4420 396e1b78 Michael Hanselmann
      if self.do_ip:
4421 396e1b78 Michael Hanselmann
        ip = self.ip
4422 396e1b78 Michael Hanselmann
      else:
4423 396e1b78 Michael Hanselmann
        ip = self.instance.nics[0].ip
4424 396e1b78 Michael Hanselmann
      if self.bridge:
4425 396e1b78 Michael Hanselmann
        bridge = self.bridge
4426 396e1b78 Michael Hanselmann
      else:
4427 396e1b78 Michael Hanselmann
        bridge = self.instance.nics[0].bridge
4428 ef756965 Iustin Pop
      if self.mac:
4429 ef756965 Iustin Pop
        mac = self.mac
4430 ef756965 Iustin Pop
      else:
4431 ef756965 Iustin Pop
        mac = self.instance.nics[0].mac
4432 ef756965 Iustin Pop
      args['nics'] = [(ip, bridge, mac)]
4433 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance, override=args)
4434 880478f8 Iustin Pop
    nl = [self.sstore.GetMasterNode(),
4435 a8083063 Iustin Pop
          self.instance.primary_node] + list(self.instance.secondary_nodes)
4436 a8083063 Iustin Pop
    return env, nl, nl
4437 a8083063 Iustin Pop
4438 a8083063 Iustin Pop
  def CheckPrereq(self):
4439 a8083063 Iustin Pop
    """Check prerequisites.
4440 a8083063 Iustin Pop

4441 a8083063 Iustin Pop
    This only checks the instance list against the existing names.
4442 a8083063 Iustin Pop

4443 a8083063 Iustin Pop
    """
4444 1a5c7281 Guido Trotter
    # FIXME: all the parameters could be checked before, in ExpandNames, or in
4445 1a5c7281 Guido Trotter
    # a separate CheckArguments function, if we implement one, so the operation
4446 1a5c7281 Guido Trotter
    # can be aborted without waiting for any lock, should it have an error...
4447 a8083063 Iustin Pop
    self.mem = getattr(self.op, "mem", None)
4448 a8083063 Iustin Pop
    self.vcpus = getattr(self.op, "vcpus", None)
4449 a8083063 Iustin Pop
    self.ip = getattr(self.op, "ip", None)
4450 1862d460 Alexander Schreiber
    self.mac = getattr(self.op, "mac", None)
4451 a8083063 Iustin Pop
    self.bridge = getattr(self.op, "bridge", None)
4452 973d7867 Iustin Pop
    self.kernel_path = getattr(self.op, "kernel_path", None)
4453 973d7867 Iustin Pop
    self.initrd_path = getattr(self.op, "initrd_path", None)
4454 25c5878d Alexander Schreiber
    self.hvm_boot_order = getattr(self.op, "hvm_boot_order", None)
4455 31a853d2 Iustin Pop
    self.hvm_acpi = getattr(self.op, "hvm_acpi", None)
4456 31a853d2 Iustin Pop
    self.hvm_pae = getattr(self.op, "hvm_pae", None)
4457 5397e0b7 Alexander Schreiber
    self.hvm_nic_type = getattr(self.op, "hvm_nic_type", None)
4458 5397e0b7 Alexander Schreiber
    self.hvm_disk_type = getattr(self.op, "hvm_disk_type", None)
4459 31a853d2 Iustin Pop
    self.hvm_cdrom_image_path = getattr(self.op, "hvm_cdrom_image_path", None)
4460 31a853d2 Iustin Pop
    self.vnc_bind_address = getattr(self.op, "vnc_bind_address", None)
4461 4300c4b6 Guido Trotter
    self.force = getattr(self.op, "force", None)
4462 31a853d2 Iustin Pop
    all_parms = [self.mem, self.vcpus, self.ip, self.bridge, self.mac,
4463 31a853d2 Iustin Pop
                 self.kernel_path, self.initrd_path, self.hvm_boot_order,
4464 31a853d2 Iustin Pop
                 self.hvm_acpi, self.hvm_pae, self.hvm_cdrom_image_path,
4465 5397e0b7 Alexander Schreiber
                 self.vnc_bind_address, self.hvm_nic_type, self.hvm_disk_type]
4466 31a853d2 Iustin Pop
    if all_parms.count(None) == len(all_parms):
4467 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("No changes submitted")
4468 a8083063 Iustin Pop
    if self.mem is not None:
4469 a8083063 Iustin Pop
      try:
4470 a8083063 Iustin Pop
        self.mem = int(self.mem)
4471 a8083063 Iustin Pop
      except ValueError, err:
4472 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid memory size: %s" % str(err))
4473 a8083063 Iustin Pop
    if self.vcpus is not None:
4474 a8083063 Iustin Pop
      try:
4475 a8083063 Iustin Pop
        self.vcpus = int(self.vcpus)
4476 a8083063 Iustin Pop
      except ValueError, err:
4477 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid vcpus number: %s" % str(err))
4478 a8083063 Iustin Pop
    if self.ip is not None:
4479 a8083063 Iustin Pop
      self.do_ip = True
4480 a8083063 Iustin Pop
      if self.ip.lower() == "none":
4481 a8083063 Iustin Pop
        self.ip = None
4482 a8083063 Iustin Pop
      else:
4483 a8083063 Iustin Pop
        if not utils.IsValidIP(self.ip):
4484 3ecf6786 Iustin Pop
          raise errors.OpPrereqError("Invalid IP address '%s'." % self.ip)
4485 a8083063 Iustin Pop
    else:
4486 a8083063 Iustin Pop
      self.do_ip = False
4487 ecb215b5 Michael Hanselmann
    self.do_bridge = (self.bridge is not None)
4488 1862d460 Alexander Schreiber
    if self.mac is not None:
4489 1862d460 Alexander Schreiber
      if self.cfg.IsMacInUse(self.mac):
4490 1862d460 Alexander Schreiber
        raise errors.OpPrereqError('MAC address %s already in use in cluster' %
4491 1862d460 Alexander Schreiber
                                   self.mac)
4492 1862d460 Alexander Schreiber
      if not utils.IsValidMac(self.mac):
4493 1862d460 Alexander Schreiber
        raise errors.OpPrereqError('Invalid MAC address %s' % self.mac)
4494 a8083063 Iustin Pop
4495 973d7867 Iustin Pop
    if self.kernel_path is not None:
4496 973d7867 Iustin Pop
      self.do_kernel_path = True
4497 973d7867 Iustin Pop
      if self.kernel_path == constants.VALUE_NONE:
4498 973d7867 Iustin Pop
        raise errors.OpPrereqError("Can't set instance to no kernel")
4499 973d7867 Iustin Pop
4500 973d7867 Iustin Pop
      if self.kernel_path != constants.VALUE_DEFAULT:
4501 973d7867 Iustin Pop
        if not os.path.isabs(self.kernel_path):
4502 ba4b62cf Iustin Pop
          raise errors.OpPrereqError("The kernel path must be an absolute"
4503 973d7867 Iustin Pop
                                    " filename")
4504 8cafeb26 Iustin Pop
    else:
4505 8cafeb26 Iustin Pop
      self.do_kernel_path = False
4506 973d7867 Iustin Pop
4507 973d7867 Iustin Pop
    if self.initrd_path is not None:
4508 973d7867 Iustin Pop
      self.do_initrd_path = True
4509 973d7867 Iustin Pop
      if self.initrd_path not in (constants.VALUE_NONE,
4510 973d7867 Iustin Pop
                                  constants.VALUE_DEFAULT):
4511 2bc22872 Iustin Pop
        if not os.path.isabs(self.initrd_path):
4512 ba4b62cf Iustin Pop
          raise errors.OpPrereqError("The initrd path must be an absolute"
4513 973d7867 Iustin Pop
                                    " filename")
4514 8cafeb26 Iustin Pop
    else:
4515 8cafeb26 Iustin Pop
      self.do_initrd_path = False
4516 973d7867 Iustin Pop
4517 25c5878d Alexander Schreiber
    # boot order verification
4518 25c5878d Alexander Schreiber
    if self.hvm_boot_order is not None:
4519 25c5878d Alexander Schreiber
      if self.hvm_boot_order != constants.VALUE_DEFAULT:
4520 25c5878d Alexander Schreiber
        if len(self.hvm_boot_order.strip("acdn")) != 0:
4521 25c5878d Alexander Schreiber
          raise errors.OpPrereqError("invalid boot order specified,"
4522 25c5878d Alexander Schreiber
                                     " must be one or more of [acdn]"
4523 25c5878d Alexander Schreiber
                                     " or 'default'")
4524 25c5878d Alexander Schreiber
4525 31a853d2 Iustin Pop
    # hvm_cdrom_image_path verification
4526 31a853d2 Iustin Pop
    if self.op.hvm_cdrom_image_path is not None:
4527 3fc175f0 Alexander Schreiber
      if not (os.path.isabs(self.op.hvm_cdrom_image_path) or
4528 3fc175f0 Alexander Schreiber
              self.op.hvm_cdrom_image_path.lower() == "none"):
4529 31a853d2 Iustin Pop
        raise errors.OpPrereqError("The path to the HVM CDROM image must"
4530 31a853d2 Iustin Pop
                                   " be an absolute path or None, not %s" %
4531 31a853d2 Iustin Pop
                                   self.op.hvm_cdrom_image_path)
4532 3fc175f0 Alexander Schreiber
      if not (os.path.isfile(self.op.hvm_cdrom_image_path) or
4533 3fc175f0 Alexander Schreiber
              self.op.hvm_cdrom_image_path.lower() == "none"):
4534 31a853d2 Iustin Pop
        raise errors.OpPrereqError("The HVM CDROM image must either be a"
4535 31a853d2 Iustin Pop
                                   " regular file or a symlink pointing to"
4536 31a853d2 Iustin Pop
                                   " an existing regular file, not %s" %
4537 31a853d2 Iustin Pop
                                   self.op.hvm_cdrom_image_path)
4538 31a853d2 Iustin Pop
4539 31a853d2 Iustin Pop
    # vnc_bind_address verification
4540 31a853d2 Iustin Pop
    if self.op.vnc_bind_address is not None:
4541 31a853d2 Iustin Pop
      if not utils.IsValidIP(self.op.vnc_bind_address):
4542 31a853d2 Iustin Pop
        raise errors.OpPrereqError("given VNC bind address '%s' doesn't look"
4543 31a853d2 Iustin Pop
                                   " like a valid IP address" %
4544 31a853d2 Iustin Pop
                                   self.op.vnc_bind_address)
4545 31a853d2 Iustin Pop
4546 cfefe007 Guido Trotter
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4547 1a5c7281 Guido Trotter
    assert self.instance is not None, \
4548 1a5c7281 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4549 cfefe007 Guido Trotter
    self.warn = []
4550 cfefe007 Guido Trotter
    if self.mem is not None and not self.force:
4551 cfefe007 Guido Trotter
      pnode = self.instance.primary_node
4552 cfefe007 Guido Trotter
      nodelist = [pnode]
4553 cfefe007 Guido Trotter
      nodelist.extend(instance.secondary_nodes)
4554 cfefe007 Guido Trotter
      instance_info = rpc.call_instance_info(pnode, instance.name)
4555 cfefe007 Guido Trotter
      nodeinfo = rpc.call_node_info(nodelist, self.cfg.GetVGName())
4556 cfefe007 Guido Trotter
4557 cfefe007 Guido Trotter
      if pnode not in nodeinfo or not isinstance(nodeinfo[pnode], dict):
4558 cfefe007 Guido Trotter
        # Assume the primary node is unreachable and go ahead
4559 cfefe007 Guido Trotter
        self.warn.append("Can't get info from primary node %s" % pnode)
4560 cfefe007 Guido Trotter
      else:
4561 cfefe007 Guido Trotter
        if instance_info:
4562 cfefe007 Guido Trotter
          current_mem = instance_info['memory']
4563 cfefe007 Guido Trotter
        else:
4564 cfefe007 Guido Trotter
          # Assume instance not running
4565 cfefe007 Guido Trotter
          # (there is a slight race condition here, but it's not very probable,
4566 cfefe007 Guido Trotter
          # and we have no other way to check)
4567 cfefe007 Guido Trotter
          current_mem = 0
4568 cfefe007 Guido Trotter
        miss_mem = self.mem - current_mem - nodeinfo[pnode]['memory_free']
4569 cfefe007 Guido Trotter
        if miss_mem > 0:
4570 cfefe007 Guido Trotter
          raise errors.OpPrereqError("This change will prevent the instance"
4571 cfefe007 Guido Trotter
                                     " from starting, due to %d MB of memory"
4572 cfefe007 Guido Trotter
                                     " missing on its primary node" % miss_mem)
4573 cfefe007 Guido Trotter
4574 cfefe007 Guido Trotter
      for node in instance.secondary_nodes:
4575 cfefe007 Guido Trotter
        if node not in nodeinfo or not isinstance(nodeinfo[node], dict):
4576 cfefe007 Guido Trotter
          self.warn.append("Can't get info from secondary node %s" % node)
4577 cfefe007 Guido Trotter
        elif self.mem > nodeinfo[node]['memory_free']:
4578 cfefe007 Guido Trotter
          self.warn.append("Not enough memory to failover instance to secondary"
4579 cfefe007 Guido Trotter
                           " node %s" % node)
4580 cfefe007 Guido Trotter
4581 5bc84f33 Alexander Schreiber
    # Xen HVM device type checks
4582 5bc84f33 Alexander Schreiber
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
4583 5bc84f33 Alexander Schreiber
      if self.op.hvm_nic_type is not None:
4584 5bc84f33 Alexander Schreiber
        if self.op.hvm_nic_type not in constants.HT_HVM_VALID_NIC_TYPES:
4585 5bc84f33 Alexander Schreiber
          raise errors.OpPrereqError("Invalid NIC type %s specified for Xen"
4586 5bc84f33 Alexander Schreiber
                                     " HVM  hypervisor" % self.op.hvm_nic_type)
4587 5bc84f33 Alexander Schreiber
      if self.op.hvm_disk_type is not None:
4588 5bc84f33 Alexander Schreiber
        if self.op.hvm_disk_type not in constants.HT_HVM_VALID_DISK_TYPES:
4589 5bc84f33 Alexander Schreiber
          raise errors.OpPrereqError("Invalid disk type %s specified for Xen"
4590 5bc84f33 Alexander Schreiber
                                     " HVM hypervisor" % self.op.hvm_disk_type)
4591 5bc84f33 Alexander Schreiber
4592 a8083063 Iustin Pop
    return
4593 a8083063 Iustin Pop
4594 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4595 a8083063 Iustin Pop
    """Modifies an instance.
4596 a8083063 Iustin Pop

4597 a8083063 Iustin Pop
    All parameters take effect only at the next restart of the instance.
4598 a8083063 Iustin Pop
    """
4599 cfefe007 Guido Trotter
    # Process here the warnings from CheckPrereq, as we don't have a
4600 cfefe007 Guido Trotter
    # feedback_fn there.
4601 cfefe007 Guido Trotter
    for warn in self.warn:
4602 cfefe007 Guido Trotter
      feedback_fn("WARNING: %s" % warn)
4603 cfefe007 Guido Trotter
4604 a8083063 Iustin Pop
    result = []
4605 a8083063 Iustin Pop
    instance = self.instance
4606 a8083063 Iustin Pop
    if self.mem:
4607 a8083063 Iustin Pop
      instance.memory = self.mem
4608 a8083063 Iustin Pop
      result.append(("mem", self.mem))
4609 a8083063 Iustin Pop
    if self.vcpus:
4610 a8083063 Iustin Pop
      instance.vcpus = self.vcpus
4611 a8083063 Iustin Pop
      result.append(("vcpus",  self.vcpus))
4612 a8083063 Iustin Pop
    if self.do_ip:
4613 a8083063 Iustin Pop
      instance.nics[0].ip = self.ip
4614 a8083063 Iustin Pop
      result.append(("ip", self.ip))
4615 a8083063 Iustin Pop
    if self.bridge:
4616 a8083063 Iustin Pop
      instance.nics[0].bridge = self.bridge
4617 a8083063 Iustin Pop
      result.append(("bridge", self.bridge))
4618 1862d460 Alexander Schreiber
    if self.mac:
4619 1862d460 Alexander Schreiber
      instance.nics[0].mac = self.mac
4620 1862d460 Alexander Schreiber
      result.append(("mac", self.mac))
4621 973d7867 Iustin Pop
    if self.do_kernel_path:
4622 973d7867 Iustin Pop
      instance.kernel_path = self.kernel_path
4623 973d7867 Iustin Pop
      result.append(("kernel_path", self.kernel_path))
4624 973d7867 Iustin Pop
    if self.do_initrd_path:
4625 973d7867 Iustin Pop
      instance.initrd_path = self.initrd_path
4626 973d7867 Iustin Pop
      result.append(("initrd_path", self.initrd_path))
4627 25c5878d Alexander Schreiber
    if self.hvm_boot_order:
4628 25c5878d Alexander Schreiber
      if self.hvm_boot_order == constants.VALUE_DEFAULT:
4629 25c5878d Alexander Schreiber
        instance.hvm_boot_order = None
4630 25c5878d Alexander Schreiber
      else:
4631 25c5878d Alexander Schreiber
        instance.hvm_boot_order = self.hvm_boot_order
4632 25c5878d Alexander Schreiber
      result.append(("hvm_boot_order", self.hvm_boot_order))
4633 3fc175f0 Alexander Schreiber
    if self.hvm_acpi is not None:
4634 ec1ba002 Iustin Pop
      instance.hvm_acpi = self.hvm_acpi
4635 31a853d2 Iustin Pop
      result.append(("hvm_acpi", self.hvm_acpi))
4636 3fc175f0 Alexander Schreiber
    if self.hvm_pae is not None:
4637 ec1ba002 Iustin Pop
      instance.hvm_pae = self.hvm_pae
4638 31a853d2 Iustin Pop
      result.append(("hvm_pae", self.hvm_pae))
4639 5397e0b7 Alexander Schreiber
    if self.hvm_nic_type is not None:
4640 5397e0b7 Alexander Schreiber
      instance.hvm_nic_type = self.hvm_nic_type
4641 5397e0b7 Alexander Schreiber
      result.append(("hvm_nic_type", self.hvm_nic_type))
4642 5397e0b7 Alexander Schreiber
    if self.hvm_disk_type is not None:
4643 5397e0b7 Alexander Schreiber
      instance.hvm_disk_type = self.hvm_disk_type
4644 5397e0b7 Alexander Schreiber
      result.append(("hvm_disk_type", self.hvm_disk_type))
4645 31a853d2 Iustin Pop
    if self.hvm_cdrom_image_path:
4646 3fc175f0 Alexander Schreiber
      if self.hvm_cdrom_image_path == constants.VALUE_NONE:
4647 3fc175f0 Alexander Schreiber
        instance.hvm_cdrom_image_path = None
4648 3fc175f0 Alexander Schreiber
      else:
4649 3fc175f0 Alexander Schreiber
        instance.hvm_cdrom_image_path = self.hvm_cdrom_image_path
4650 31a853d2 Iustin Pop
      result.append(("hvm_cdrom_image_path", self.hvm_cdrom_image_path))
4651 31a853d2 Iustin Pop
    if self.vnc_bind_address:
4652 31a853d2 Iustin Pop
      instance.vnc_bind_address = self.vnc_bind_address
4653 31a853d2 Iustin Pop
      result.append(("vnc_bind_address", self.vnc_bind_address))
4654 a8083063 Iustin Pop
4655 ea94e1cd Guido Trotter
    self.cfg.Update(instance)
4656 a8083063 Iustin Pop
4657 a8083063 Iustin Pop
    return result
4658 a8083063 Iustin Pop
4659 a8083063 Iustin Pop
4660 a8083063 Iustin Pop
class LUQueryExports(NoHooksLU):
4661 a8083063 Iustin Pop
  """Query the exports list
4662 a8083063 Iustin Pop

4663 a8083063 Iustin Pop
  """
4664 895ecd9c Guido Trotter
  _OP_REQP = ['nodes']
4665 21a15682 Guido Trotter
  REQ_BGL = False
4666 21a15682 Guido Trotter
4667 21a15682 Guido Trotter
  def ExpandNames(self):
4668 21a15682 Guido Trotter
    self.needed_locks = {}
4669 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
4670 21a15682 Guido Trotter
    if not self.op.nodes:
4671 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4672 21a15682 Guido Trotter
    else:
4673 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
4674 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
4675 a8083063 Iustin Pop
4676 a8083063 Iustin Pop
  def CheckPrereq(self):
4677 21a15682 Guido Trotter
    """Check prerequisites.
4678 a8083063 Iustin Pop

4679 a8083063 Iustin Pop
    """
4680 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
4681 a8083063 Iustin Pop
4682 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4683 a8083063 Iustin Pop
    """Compute the list of all the exported system images.
4684 a8083063 Iustin Pop

4685 a8083063 Iustin Pop
    Returns:
4686 a8083063 Iustin Pop
      a dictionary with the structure node->(export-list)
4687 a8083063 Iustin Pop
      where export-list is a list of the instances exported on
4688 a8083063 Iustin Pop
      that node.
4689 a8083063 Iustin Pop

4690 a8083063 Iustin Pop
    """
4691 a7ba5e53 Iustin Pop
    return rpc.call_export_list(self.nodes)
4692 a8083063 Iustin Pop
4693 a8083063 Iustin Pop
4694 a8083063 Iustin Pop
class LUExportInstance(LogicalUnit):
4695 a8083063 Iustin Pop
  """Export an instance to an image in the cluster.
4696 a8083063 Iustin Pop

4697 a8083063 Iustin Pop
  """
4698 a8083063 Iustin Pop
  HPATH = "instance-export"
4699 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4700 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
4701 6657590e Guido Trotter
  REQ_BGL = False
4702 6657590e Guido Trotter
4703 6657590e Guido Trotter
  def ExpandNames(self):
4704 6657590e Guido Trotter
    self._ExpandAndLockInstance()
4705 6657590e Guido Trotter
    # FIXME: lock only instance primary and destination node
4706 6657590e Guido Trotter
    #
4707 6657590e Guido Trotter
    # Sad but true, for now we have do lock all nodes, as we don't know where
4708 6657590e Guido Trotter
    # the previous export might be, and and in this LU we search for it and
4709 6657590e Guido Trotter
    # remove it from its current node. In the future we could fix this by:
4710 6657590e Guido Trotter
    #  - making a tasklet to search (share-lock all), then create the new one,
4711 6657590e Guido Trotter
    #    then one to remove, after
4712 6657590e Guido Trotter
    #  - removing the removal operation altoghether
4713 6657590e Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4714 6657590e Guido Trotter
4715 6657590e Guido Trotter
  def DeclareLocks(self, level):
4716 6657590e Guido Trotter
    """Last minute lock declaration."""
4717 6657590e Guido Trotter
    # All nodes are locked anyway, so nothing to do here.
4718 a8083063 Iustin Pop
4719 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4720 a8083063 Iustin Pop
    """Build hooks env.
4721 a8083063 Iustin Pop

4722 a8083063 Iustin Pop
    This will run on the master, primary node and target node.
4723 a8083063 Iustin Pop

4724 a8083063 Iustin Pop
    """
4725 a8083063 Iustin Pop
    env = {
4726 a8083063 Iustin Pop
      "EXPORT_NODE": self.op.target_node,
4727 a8083063 Iustin Pop
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
4728 a8083063 Iustin Pop
      }
4729 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
4730 880478f8 Iustin Pop
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
4731 a8083063 Iustin Pop
          self.op.target_node]
4732 a8083063 Iustin Pop
    return env, nl, nl
4733 a8083063 Iustin Pop
4734 a8083063 Iustin Pop
  def CheckPrereq(self):
4735 a8083063 Iustin Pop
    """Check prerequisites.
4736 a8083063 Iustin Pop

4737 9ac99fda Guido Trotter
    This checks that the instance and node names are valid.
4738 a8083063 Iustin Pop

4739 a8083063 Iustin Pop
    """
4740 6657590e Guido Trotter
    instance_name = self.op.instance_name
4741 a8083063 Iustin Pop
    self.instance = self.cfg.GetInstanceInfo(instance_name)
4742 6657590e Guido Trotter
    assert self.instance is not None, \
4743 6657590e Guido Trotter
          "Cannot retrieve locked instance %s" % self.op.instance_name
4744 a8083063 Iustin Pop
4745 6657590e Guido Trotter
    self.dst_node = self.cfg.GetNodeInfo(
4746 6657590e Guido Trotter
      self.cfg.ExpandNodeName(self.op.target_node))
4747 a8083063 Iustin Pop
4748 6657590e Guido Trotter
    assert self.dst_node is not None, \
4749 6657590e Guido Trotter
          "Cannot retrieve locked node %s" % self.op.target_node
4750 a8083063 Iustin Pop
4751 b6023d6c Manuel Franceschini
    # instance disk type verification
4752 b6023d6c Manuel Franceschini
    for disk in self.instance.disks:
4753 b6023d6c Manuel Franceschini
      if disk.dev_type == constants.LD_FILE:
4754 b6023d6c Manuel Franceschini
        raise errors.OpPrereqError("Export not supported for instances with"
4755 b6023d6c Manuel Franceschini
                                   " file-based disks")
4756 b6023d6c Manuel Franceschini
4757 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4758 a8083063 Iustin Pop
    """Export an instance to an image in the cluster.
4759 a8083063 Iustin Pop

4760 a8083063 Iustin Pop
    """
4761 a8083063 Iustin Pop
    instance = self.instance
4762 a8083063 Iustin Pop
    dst_node = self.dst_node
4763 a8083063 Iustin Pop
    src_node = instance.primary_node
4764 a8083063 Iustin Pop
    if self.op.shutdown:
4765 fb300fb7 Guido Trotter
      # shutdown the instance, but not the disks
4766 fb300fb7 Guido Trotter
      if not rpc.call_instance_shutdown(src_node, instance):
4767 38206f3c Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
4768 38206f3c Iustin Pop
                                 (instance.name, src_node))
4769 a8083063 Iustin Pop
4770 a8083063 Iustin Pop
    vgname = self.cfg.GetVGName()
4771 a8083063 Iustin Pop
4772 a8083063 Iustin Pop
    snap_disks = []
4773 a8083063 Iustin Pop
4774 a8083063 Iustin Pop
    try:
4775 a8083063 Iustin Pop
      for disk in instance.disks:
4776 a8083063 Iustin Pop
        if disk.iv_name == "sda":
4777 a8083063 Iustin Pop
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
4778 a8083063 Iustin Pop
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
4779 a8083063 Iustin Pop
4780 a8083063 Iustin Pop
          if not new_dev_name:
4781 a8083063 Iustin Pop
            logger.Error("could not snapshot block device %s on node %s" %
4782 a8083063 Iustin Pop
                         (disk.logical_id[1], src_node))
4783 a8083063 Iustin Pop
          else:
4784 fe96220b Iustin Pop
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
4785 a8083063 Iustin Pop
                                      logical_id=(vgname, new_dev_name),
4786 a8083063 Iustin Pop
                                      physical_id=(vgname, new_dev_name),
4787 a8083063 Iustin Pop
                                      iv_name=disk.iv_name)
4788 a8083063 Iustin Pop
            snap_disks.append(new_dev)
4789 a8083063 Iustin Pop
4790 a8083063 Iustin Pop
    finally:
4791 fb300fb7 Guido Trotter
      if self.op.shutdown and instance.status == "up":
4792 fb300fb7 Guido Trotter
        if not rpc.call_instance_start(src_node, instance, None):
4793 fb300fb7 Guido Trotter
          _ShutdownInstanceDisks(instance, self.cfg)
4794 fb300fb7 Guido Trotter
          raise errors.OpExecError("Could not start instance")
4795 a8083063 Iustin Pop
4796 a8083063 Iustin Pop
    # TODO: check for size
4797 a8083063 Iustin Pop
4798 a8083063 Iustin Pop
    for dev in snap_disks:
4799 16687b98 Manuel Franceschini
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name, instance):
4800 16687b98 Manuel Franceschini
        logger.Error("could not export block device %s from node %s to node %s"
4801 16687b98 Manuel Franceschini
                     % (dev.logical_id[1], src_node, dst_node.name))
4802 a8083063 Iustin Pop
      if not rpc.call_blockdev_remove(src_node, dev):
4803 16687b98 Manuel Franceschini
        logger.Error("could not remove snapshot block device %s from node %s" %
4804 16687b98 Manuel Franceschini
                     (dev.logical_id[1], src_node))
4805 a8083063 Iustin Pop
4806 a8083063 Iustin Pop
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
4807 a8083063 Iustin Pop
      logger.Error("could not finalize export for instance %s on node %s" %
4808 a8083063 Iustin Pop
                   (instance.name, dst_node.name))
4809 a8083063 Iustin Pop
4810 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
4811 a8083063 Iustin Pop
    nodelist.remove(dst_node.name)
4812 a8083063 Iustin Pop
4813 a8083063 Iustin Pop
    # on one-node clusters nodelist will be empty after the removal
4814 a8083063 Iustin Pop
    # if we proceed the backup would be removed because OpQueryExports
4815 a8083063 Iustin Pop
    # substitutes an empty list with the full cluster node list.
4816 a8083063 Iustin Pop
    if nodelist:
4817 204f2086 Guido Trotter
      exportlist = rpc.call_export_list(nodelist)
4818 a8083063 Iustin Pop
      for node in exportlist:
4819 a8083063 Iustin Pop
        if instance.name in exportlist[node]:
4820 a8083063 Iustin Pop
          if not rpc.call_export_remove(node, instance.name):
4821 a8083063 Iustin Pop
            logger.Error("could not remove older export for instance %s"
4822 a8083063 Iustin Pop
                         " on node %s" % (instance.name, node))
4823 5c947f38 Iustin Pop
4824 5c947f38 Iustin Pop
4825 9ac99fda Guido Trotter
class LURemoveExport(NoHooksLU):
4826 9ac99fda Guido Trotter
  """Remove exports related to the named instance.
4827 9ac99fda Guido Trotter

4828 9ac99fda Guido Trotter
  """
4829 9ac99fda Guido Trotter
  _OP_REQP = ["instance_name"]
4830 3656b3af Guido Trotter
  REQ_BGL = False
4831 3656b3af Guido Trotter
4832 3656b3af Guido Trotter
  def ExpandNames(self):
4833 3656b3af Guido Trotter
    self.needed_locks = {}
4834 3656b3af Guido Trotter
    # We need all nodes to be locked in order for RemoveExport to work, but we
4835 3656b3af Guido Trotter
    # don't need to lock the instance itself, as nothing will happen to it (and
4836 3656b3af Guido Trotter
    # we can remove exports also for a removed instance)
4837 3656b3af Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4838 9ac99fda Guido Trotter
4839 9ac99fda Guido Trotter
  def CheckPrereq(self):
4840 9ac99fda Guido Trotter
    """Check prerequisites.
4841 9ac99fda Guido Trotter
    """
4842 9ac99fda Guido Trotter
    pass
4843 9ac99fda Guido Trotter
4844 9ac99fda Guido Trotter
  def Exec(self, feedback_fn):
4845 9ac99fda Guido Trotter
    """Remove any export.
4846 9ac99fda Guido Trotter

4847 9ac99fda Guido Trotter
    """
4848 9ac99fda Guido Trotter
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4849 9ac99fda Guido Trotter
    # If the instance was not found we'll try with the name that was passed in.
4850 9ac99fda Guido Trotter
    # This will only work if it was an FQDN, though.
4851 9ac99fda Guido Trotter
    fqdn_warn = False
4852 9ac99fda Guido Trotter
    if not instance_name:
4853 9ac99fda Guido Trotter
      fqdn_warn = True
4854 9ac99fda Guido Trotter
      instance_name = self.op.instance_name
4855 9ac99fda Guido Trotter
4856 3656b3af Guido Trotter
    exportlist = rpc.call_export_list(self.acquired_locks[locking.LEVEL_NODE])
4857 9ac99fda Guido Trotter
    found = False
4858 9ac99fda Guido Trotter
    for node in exportlist:
4859 9ac99fda Guido Trotter
      if instance_name in exportlist[node]:
4860 9ac99fda Guido Trotter
        found = True
4861 9ac99fda Guido Trotter
        if not rpc.call_export_remove(node, instance_name):
4862 9ac99fda Guido Trotter
          logger.Error("could not remove export for instance %s"
4863 9ac99fda Guido Trotter
                       " on node %s" % (instance_name, node))
4864 9ac99fda Guido Trotter
4865 9ac99fda Guido Trotter
    if fqdn_warn and not found:
4866 9ac99fda Guido Trotter
      feedback_fn("Export not found. If trying to remove an export belonging"
4867 9ac99fda Guido Trotter
                  " to a deleted instance please use its Fully Qualified"
4868 9ac99fda Guido Trotter
                  " Domain Name.")
4869 9ac99fda Guido Trotter
4870 9ac99fda Guido Trotter
4871 5c947f38 Iustin Pop
class TagsLU(NoHooksLU):
4872 5c947f38 Iustin Pop
  """Generic tags LU.
4873 5c947f38 Iustin Pop

4874 5c947f38 Iustin Pop
  This is an abstract class which is the parent of all the other tags LUs.
4875 5c947f38 Iustin Pop

4876 5c947f38 Iustin Pop
  """
4877 5c947f38 Iustin Pop
4878 8646adce Guido Trotter
  def ExpandNames(self):
4879 8646adce Guido Trotter
    self.needed_locks = {}
4880 8646adce Guido Trotter
    if self.op.kind == constants.TAG_NODE:
4881 5c947f38 Iustin Pop
      name = self.cfg.ExpandNodeName(self.op.name)
4882 5c947f38 Iustin Pop
      if name is None:
4883 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid node name (%s)" %
4884 3ecf6786 Iustin Pop
                                   (self.op.name,))
4885 5c947f38 Iustin Pop
      self.op.name = name
4886 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = name
4887 5c947f38 Iustin Pop
    elif self.op.kind == constants.TAG_INSTANCE:
4888 8f684e16 Iustin Pop
      name = self.cfg.ExpandInstanceName(self.op.name)
4889 5c947f38 Iustin Pop
      if name is None:
4890 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid instance name (%s)" %
4891 3ecf6786 Iustin Pop
                                   (self.op.name,))
4892 5c947f38 Iustin Pop
      self.op.name = name
4893 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = name
4894 8646adce Guido Trotter
4895 8646adce Guido Trotter
  def CheckPrereq(self):
4896 8646adce Guido Trotter
    """Check prerequisites.
4897 8646adce Guido Trotter

4898 8646adce Guido Trotter
    """
4899 8646adce Guido Trotter
    if self.op.kind == constants.TAG_CLUSTER:
4900 8646adce Guido Trotter
      self.target = self.cfg.GetClusterInfo()
4901 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_NODE:
4902 8646adce Guido Trotter
      self.target = self.cfg.GetNodeInfo(self.op.name)
4903 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_INSTANCE:
4904 8646adce Guido Trotter
      self.target = self.cfg.GetInstanceInfo(self.op.name)
4905 5c947f38 Iustin Pop
    else:
4906 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
4907 3ecf6786 Iustin Pop
                                 str(self.op.kind))
4908 5c947f38 Iustin Pop
4909 5c947f38 Iustin Pop
4910 5c947f38 Iustin Pop
class LUGetTags(TagsLU):
4911 5c947f38 Iustin Pop
  """Returns the tags of a given object.
4912 5c947f38 Iustin Pop

4913 5c947f38 Iustin Pop
  """
4914 5c947f38 Iustin Pop
  _OP_REQP = ["kind", "name"]
4915 8646adce Guido Trotter
  REQ_BGL = False
4916 5c947f38 Iustin Pop
4917 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
4918 5c947f38 Iustin Pop
    """Returns the tag list.
4919 5c947f38 Iustin Pop

4920 5c947f38 Iustin Pop
    """
4921 5d414478 Oleksiy Mishchenko
    return list(self.target.GetTags())
4922 5c947f38 Iustin Pop
4923 5c947f38 Iustin Pop
4924 73415719 Iustin Pop
class LUSearchTags(NoHooksLU):
4925 73415719 Iustin Pop
  """Searches the tags for a given pattern.
4926 73415719 Iustin Pop

4927 73415719 Iustin Pop
  """
4928 73415719 Iustin Pop
  _OP_REQP = ["pattern"]
4929 8646adce Guido Trotter
  REQ_BGL = False
4930 8646adce Guido Trotter
4931 8646adce Guido Trotter
  def ExpandNames(self):
4932 8646adce Guido Trotter
    self.needed_locks = {}
4933 73415719 Iustin Pop
4934 73415719 Iustin Pop
  def CheckPrereq(self):
4935 73415719 Iustin Pop
    """Check prerequisites.
4936 73415719 Iustin Pop

4937 73415719 Iustin Pop
    This checks the pattern passed for validity by compiling it.
4938 73415719 Iustin Pop

4939 73415719 Iustin Pop
    """
4940 73415719 Iustin Pop
    try:
4941 73415719 Iustin Pop
      self.re = re.compile(self.op.pattern)
4942 73415719 Iustin Pop
    except re.error, err:
4943 73415719 Iustin Pop
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
4944 73415719 Iustin Pop
                                 (self.op.pattern, err))
4945 73415719 Iustin Pop
4946 73415719 Iustin Pop
  def Exec(self, feedback_fn):
4947 73415719 Iustin Pop
    """Returns the tag list.
4948 73415719 Iustin Pop

4949 73415719 Iustin Pop
    """
4950 73415719 Iustin Pop
    cfg = self.cfg
4951 73415719 Iustin Pop
    tgts = [("/cluster", cfg.GetClusterInfo())]
4952 8646adce Guido Trotter
    ilist = cfg.GetAllInstancesInfo().values()
4953 73415719 Iustin Pop
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
4954 8646adce Guido Trotter
    nlist = cfg.GetAllNodesInfo().values()
4955 73415719 Iustin Pop
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
4956 73415719 Iustin Pop
    results = []
4957 73415719 Iustin Pop
    for path, target in tgts:
4958 73415719 Iustin Pop
      for tag in target.GetTags():
4959 73415719 Iustin Pop
        if self.re.search(tag):
4960 73415719 Iustin Pop
          results.append((path, tag))
4961 73415719 Iustin Pop
    return results
4962 73415719 Iustin Pop
4963 73415719 Iustin Pop
4964 f27302fa Iustin Pop
class LUAddTags(TagsLU):
4965 5c947f38 Iustin Pop
  """Sets a tag on a given object.
4966 5c947f38 Iustin Pop

4967 5c947f38 Iustin Pop
  """
4968 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
4969 8646adce Guido Trotter
  REQ_BGL = False
4970 5c947f38 Iustin Pop
4971 5c947f38 Iustin Pop
  def CheckPrereq(self):
4972 5c947f38 Iustin Pop
    """Check prerequisites.
4973 5c947f38 Iustin Pop

4974 5c947f38 Iustin Pop
    This checks the type and length of the tag name and value.
4975 5c947f38 Iustin Pop

4976 5c947f38 Iustin Pop
    """
4977 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
4978 f27302fa Iustin Pop
    for tag in self.op.tags:
4979 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
4980 5c947f38 Iustin Pop
4981 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
4982 5c947f38 Iustin Pop
    """Sets the tag.
4983 5c947f38 Iustin Pop

4984 5c947f38 Iustin Pop
    """
4985 5c947f38 Iustin Pop
    try:
4986 f27302fa Iustin Pop
      for tag in self.op.tags:
4987 f27302fa Iustin Pop
        self.target.AddTag(tag)
4988 5c947f38 Iustin Pop
    except errors.TagError, err:
4989 3ecf6786 Iustin Pop
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
4990 5c947f38 Iustin Pop
    try:
4991 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
4992 5c947f38 Iustin Pop
    except errors.ConfigurationError:
4993 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
4994 3ecf6786 Iustin Pop
                                " config file and the operation has been"
4995 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
4996 5c947f38 Iustin Pop
4997 5c947f38 Iustin Pop
4998 f27302fa Iustin Pop
class LUDelTags(TagsLU):
4999 f27302fa Iustin Pop
  """Delete a list of tags from a given object.
5000 5c947f38 Iustin Pop

5001 5c947f38 Iustin Pop
  """
5002 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
5003 8646adce Guido Trotter
  REQ_BGL = False
5004 5c947f38 Iustin Pop
5005 5c947f38 Iustin Pop
  def CheckPrereq(self):
5006 5c947f38 Iustin Pop
    """Check prerequisites.
5007 5c947f38 Iustin Pop

5008 5c947f38 Iustin Pop
    This checks that we have the given tag.
5009 5c947f38 Iustin Pop

5010 5c947f38 Iustin Pop
    """
5011 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
5012 f27302fa Iustin Pop
    for tag in self.op.tags:
5013 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
5014 f27302fa Iustin Pop
    del_tags = frozenset(self.op.tags)
5015 f27302fa Iustin Pop
    cur_tags = self.target.GetTags()
5016 f27302fa Iustin Pop
    if not del_tags <= cur_tags:
5017 f27302fa Iustin Pop
      diff_tags = del_tags - cur_tags
5018 f27302fa Iustin Pop
      diff_names = ["'%s'" % tag for tag in diff_tags]
5019 f27302fa Iustin Pop
      diff_names.sort()
5020 f27302fa Iustin Pop
      raise errors.OpPrereqError("Tag(s) %s not found" %
5021 f27302fa Iustin Pop
                                 (",".join(diff_names)))
5022 5c947f38 Iustin Pop
5023 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
5024 5c947f38 Iustin Pop
    """Remove the tag from the object.
5025 5c947f38 Iustin Pop

5026 5c947f38 Iustin Pop
    """
5027 f27302fa Iustin Pop
    for tag in self.op.tags:
5028 f27302fa Iustin Pop
      self.target.RemoveTag(tag)
5029 5c947f38 Iustin Pop
    try:
5030 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
5031 5c947f38 Iustin Pop
    except errors.ConfigurationError:
5032 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
5033 3ecf6786 Iustin Pop
                                " config file and the operation has been"
5034 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
5035 06009e27 Iustin Pop
5036 0eed6e61 Guido Trotter
5037 06009e27 Iustin Pop
class LUTestDelay(NoHooksLU):
5038 06009e27 Iustin Pop
  """Sleep for a specified amount of time.
5039 06009e27 Iustin Pop

5040 0b097284 Guido Trotter
  This LU sleeps on the master and/or nodes for a specified amount of
5041 06009e27 Iustin Pop
  time.
5042 06009e27 Iustin Pop

5043 06009e27 Iustin Pop
  """
5044 06009e27 Iustin Pop
  _OP_REQP = ["duration", "on_master", "on_nodes"]
5045 fbe9022f Guido Trotter
  REQ_BGL = False
5046 06009e27 Iustin Pop
5047 fbe9022f Guido Trotter
  def ExpandNames(self):
5048 fbe9022f Guido Trotter
    """Expand names and set required locks.
5049 06009e27 Iustin Pop

5050 fbe9022f Guido Trotter
    This expands the node list, if any.
5051 06009e27 Iustin Pop

5052 06009e27 Iustin Pop
    """
5053 fbe9022f Guido Trotter
    self.needed_locks = {}
5054 06009e27 Iustin Pop
    if self.op.on_nodes:
5055 fbe9022f Guido Trotter
      # _GetWantedNodes can be used here, but is not always appropriate to use
5056 fbe9022f Guido Trotter
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
5057 fbe9022f Guido Trotter
      # more information.
5058 06009e27 Iustin Pop
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
5059 fbe9022f Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
5060 fbe9022f Guido Trotter
5061 fbe9022f Guido Trotter
  def CheckPrereq(self):
5062 fbe9022f Guido Trotter
    """Check prerequisites.
5063 fbe9022f Guido Trotter

5064 fbe9022f Guido Trotter
    """
5065 06009e27 Iustin Pop
5066 06009e27 Iustin Pop
  def Exec(self, feedback_fn):
5067 06009e27 Iustin Pop
    """Do the actual sleep.
5068 06009e27 Iustin Pop

5069 06009e27 Iustin Pop
    """
5070 06009e27 Iustin Pop
    if self.op.on_master:
5071 06009e27 Iustin Pop
      if not utils.TestDelay(self.op.duration):
5072 06009e27 Iustin Pop
        raise errors.OpExecError("Error during master delay test")
5073 06009e27 Iustin Pop
    if self.op.on_nodes:
5074 06009e27 Iustin Pop
      result = rpc.call_test_delay(self.op.on_nodes, self.op.duration)
5075 06009e27 Iustin Pop
      if not result:
5076 06009e27 Iustin Pop
        raise errors.OpExecError("Complete failure from rpc call")
5077 06009e27 Iustin Pop
      for node, node_result in result.items():
5078 06009e27 Iustin Pop
        if not node_result:
5079 06009e27 Iustin Pop
          raise errors.OpExecError("Failure during rpc call to node %s,"
5080 06009e27 Iustin Pop
                                   " result: %s" % (node, node_result))
5081 d61df03e Iustin Pop
5082 d61df03e Iustin Pop
5083 d1c2dd75 Iustin Pop
class IAllocator(object):
5084 d1c2dd75 Iustin Pop
  """IAllocator framework.
5085 d61df03e Iustin Pop

5086 d1c2dd75 Iustin Pop
  An IAllocator instance has three sets of attributes:
5087 d1c2dd75 Iustin Pop
    - cfg/sstore that are needed to query the cluster
5088 d1c2dd75 Iustin Pop
    - input data (all members of the _KEYS class attribute are required)
5089 d1c2dd75 Iustin Pop
    - four buffer attributes (in|out_data|text), that represent the
5090 d1c2dd75 Iustin Pop
      input (to the external script) in text and data structure format,
5091 d1c2dd75 Iustin Pop
      and the output from it, again in two formats
5092 d1c2dd75 Iustin Pop
    - the result variables from the script (success, info, nodes) for
5093 d1c2dd75 Iustin Pop
      easy usage
5094 d61df03e Iustin Pop

5095 d61df03e Iustin Pop
  """
5096 29859cb7 Iustin Pop
  _ALLO_KEYS = [
5097 d1c2dd75 Iustin Pop
    "mem_size", "disks", "disk_template",
5098 d1c2dd75 Iustin Pop
    "os", "tags", "nics", "vcpus",
5099 d1c2dd75 Iustin Pop
    ]
5100 29859cb7 Iustin Pop
  _RELO_KEYS = [
5101 29859cb7 Iustin Pop
    "relocate_from",
5102 29859cb7 Iustin Pop
    ]
5103 d1c2dd75 Iustin Pop
5104 29859cb7 Iustin Pop
  def __init__(self, cfg, sstore, mode, name, **kwargs):
5105 d1c2dd75 Iustin Pop
    self.cfg = cfg
5106 d1c2dd75 Iustin Pop
    self.sstore = sstore
5107 d1c2dd75 Iustin Pop
    # init buffer variables
5108 d1c2dd75 Iustin Pop
    self.in_text = self.out_text = self.in_data = self.out_data = None
5109 d1c2dd75 Iustin Pop
    # init all input fields so that pylint is happy
5110 29859cb7 Iustin Pop
    self.mode = mode
5111 29859cb7 Iustin Pop
    self.name = name
5112 d1c2dd75 Iustin Pop
    self.mem_size = self.disks = self.disk_template = None
5113 d1c2dd75 Iustin Pop
    self.os = self.tags = self.nics = self.vcpus = None
5114 29859cb7 Iustin Pop
    self.relocate_from = None
5115 27579978 Iustin Pop
    # computed fields
5116 27579978 Iustin Pop
    self.required_nodes = None
5117 d1c2dd75 Iustin Pop
    # init result fields
5118 d1c2dd75 Iustin Pop
    self.success = self.info = self.nodes = None
5119 29859cb7 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5120 29859cb7 Iustin Pop
      keyset = self._ALLO_KEYS
5121 29859cb7 Iustin Pop
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5122 29859cb7 Iustin Pop
      keyset = self._RELO_KEYS
5123 29859cb7 Iustin Pop
    else:
5124 29859cb7 Iustin Pop
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
5125 29859cb7 Iustin Pop
                                   " IAllocator" % self.mode)
5126 d1c2dd75 Iustin Pop
    for key in kwargs:
5127 29859cb7 Iustin Pop
      if key not in keyset:
5128 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
5129 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
5130 d1c2dd75 Iustin Pop
      setattr(self, key, kwargs[key])
5131 29859cb7 Iustin Pop
    for key in keyset:
5132 d1c2dd75 Iustin Pop
      if key not in kwargs:
5133 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Missing input parameter '%s' to"
5134 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
5135 d1c2dd75 Iustin Pop
    self._BuildInputData()
5136 d1c2dd75 Iustin Pop
5137 d1c2dd75 Iustin Pop
  def _ComputeClusterData(self):
5138 d1c2dd75 Iustin Pop
    """Compute the generic allocator input data.
5139 d1c2dd75 Iustin Pop

5140 d1c2dd75 Iustin Pop
    This is the data that is independent of the actual operation.
5141 d1c2dd75 Iustin Pop

5142 d1c2dd75 Iustin Pop
    """
5143 d1c2dd75 Iustin Pop
    cfg = self.cfg
5144 d1c2dd75 Iustin Pop
    # cluster data
5145 d1c2dd75 Iustin Pop
    data = {
5146 d1c2dd75 Iustin Pop
      "version": 1,
5147 d1c2dd75 Iustin Pop
      "cluster_name": self.sstore.GetClusterName(),
5148 d1c2dd75 Iustin Pop
      "cluster_tags": list(cfg.GetClusterInfo().GetTags()),
5149 6286519f Iustin Pop
      "hypervisor_type": self.sstore.GetHypervisorType(),
5150 d1c2dd75 Iustin Pop
      # we don't have job IDs
5151 d61df03e Iustin Pop
      }
5152 d61df03e Iustin Pop
5153 6286519f Iustin Pop
    i_list = [cfg.GetInstanceInfo(iname) for iname in cfg.GetInstanceList()]
5154 6286519f Iustin Pop
5155 d1c2dd75 Iustin Pop
    # node data
5156 d1c2dd75 Iustin Pop
    node_results = {}
5157 d1c2dd75 Iustin Pop
    node_list = cfg.GetNodeList()
5158 d1c2dd75 Iustin Pop
    node_data = rpc.call_node_info(node_list, cfg.GetVGName())
5159 d1c2dd75 Iustin Pop
    for nname in node_list:
5160 d1c2dd75 Iustin Pop
      ninfo = cfg.GetNodeInfo(nname)
5161 d1c2dd75 Iustin Pop
      if nname not in node_data or not isinstance(node_data[nname], dict):
5162 d1c2dd75 Iustin Pop
        raise errors.OpExecError("Can't get data for node %s" % nname)
5163 d1c2dd75 Iustin Pop
      remote_info = node_data[nname]
5164 b2662e7f Iustin Pop
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
5165 4337cf1b Iustin Pop
                   'vg_size', 'vg_free', 'cpu_total']:
5166 d1c2dd75 Iustin Pop
        if attr not in remote_info:
5167 d1c2dd75 Iustin Pop
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
5168 d1c2dd75 Iustin Pop
                                   (nname, attr))
5169 d1c2dd75 Iustin Pop
        try:
5170 b2662e7f Iustin Pop
          remote_info[attr] = int(remote_info[attr])
5171 d1c2dd75 Iustin Pop
        except ValueError, err:
5172 d1c2dd75 Iustin Pop
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
5173 d1c2dd75 Iustin Pop
                                   " %s" % (nname, attr, str(err)))
5174 6286519f Iustin Pop
      # compute memory used by primary instances
5175 6286519f Iustin Pop
      i_p_mem = i_p_up_mem = 0
5176 6286519f Iustin Pop
      for iinfo in i_list:
5177 6286519f Iustin Pop
        if iinfo.primary_node == nname:
5178 6286519f Iustin Pop
          i_p_mem += iinfo.memory
5179 6286519f Iustin Pop
          if iinfo.status == "up":
5180 6286519f Iustin Pop
            i_p_up_mem += iinfo.memory
5181 6286519f Iustin Pop
5182 b2662e7f Iustin Pop
      # compute memory used by instances
5183 d1c2dd75 Iustin Pop
      pnr = {
5184 d1c2dd75 Iustin Pop
        "tags": list(ninfo.GetTags()),
5185 b2662e7f Iustin Pop
        "total_memory": remote_info['memory_total'],
5186 b2662e7f Iustin Pop
        "reserved_memory": remote_info['memory_dom0'],
5187 b2662e7f Iustin Pop
        "free_memory": remote_info['memory_free'],
5188 6286519f Iustin Pop
        "i_pri_memory": i_p_mem,
5189 6286519f Iustin Pop
        "i_pri_up_memory": i_p_up_mem,
5190 b2662e7f Iustin Pop
        "total_disk": remote_info['vg_size'],
5191 b2662e7f Iustin Pop
        "free_disk": remote_info['vg_free'],
5192 d1c2dd75 Iustin Pop
        "primary_ip": ninfo.primary_ip,
5193 d1c2dd75 Iustin Pop
        "secondary_ip": ninfo.secondary_ip,
5194 4337cf1b Iustin Pop
        "total_cpus": remote_info['cpu_total'],
5195 d1c2dd75 Iustin Pop
        }
5196 d1c2dd75 Iustin Pop
      node_results[nname] = pnr
5197 d1c2dd75 Iustin Pop
    data["nodes"] = node_results
5198 d1c2dd75 Iustin Pop
5199 d1c2dd75 Iustin Pop
    # instance data
5200 d1c2dd75 Iustin Pop
    instance_data = {}
5201 6286519f Iustin Pop
    for iinfo in i_list:
5202 d1c2dd75 Iustin Pop
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
5203 d1c2dd75 Iustin Pop
                  for n in iinfo.nics]
5204 d1c2dd75 Iustin Pop
      pir = {
5205 d1c2dd75 Iustin Pop
        "tags": list(iinfo.GetTags()),
5206 d1c2dd75 Iustin Pop
        "should_run": iinfo.status == "up",
5207 d1c2dd75 Iustin Pop
        "vcpus": iinfo.vcpus,
5208 d1c2dd75 Iustin Pop
        "memory": iinfo.memory,
5209 d1c2dd75 Iustin Pop
        "os": iinfo.os,
5210 d1c2dd75 Iustin Pop
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
5211 d1c2dd75 Iustin Pop
        "nics": nic_data,
5212 d1c2dd75 Iustin Pop
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
5213 d1c2dd75 Iustin Pop
        "disk_template": iinfo.disk_template,
5214 d1c2dd75 Iustin Pop
        }
5215 768f0a80 Iustin Pop
      instance_data[iinfo.name] = pir
5216 d61df03e Iustin Pop
5217 d1c2dd75 Iustin Pop
    data["instances"] = instance_data
5218 d61df03e Iustin Pop
5219 d1c2dd75 Iustin Pop
    self.in_data = data
5220 d61df03e Iustin Pop
5221 d1c2dd75 Iustin Pop
  def _AddNewInstance(self):
5222 d1c2dd75 Iustin Pop
    """Add new instance data to allocator structure.
5223 d61df03e Iustin Pop

5224 d1c2dd75 Iustin Pop
    This in combination with _AllocatorGetClusterData will create the
5225 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
5226 d61df03e Iustin Pop

5227 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
5228 d1c2dd75 Iustin Pop
    done.
5229 d61df03e Iustin Pop

5230 d1c2dd75 Iustin Pop
    """
5231 d1c2dd75 Iustin Pop
    data = self.in_data
5232 d1c2dd75 Iustin Pop
    if len(self.disks) != 2:
5233 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Only two-disk configurations supported")
5234 d1c2dd75 Iustin Pop
5235 d1c2dd75 Iustin Pop
    disk_space = _ComputeDiskSize(self.disk_template,
5236 d1c2dd75 Iustin Pop
                                  self.disks[0]["size"], self.disks[1]["size"])
5237 d1c2dd75 Iustin Pop
5238 27579978 Iustin Pop
    if self.disk_template in constants.DTS_NET_MIRROR:
5239 27579978 Iustin Pop
      self.required_nodes = 2
5240 27579978 Iustin Pop
    else:
5241 27579978 Iustin Pop
      self.required_nodes = 1
5242 d1c2dd75 Iustin Pop
    request = {
5243 d1c2dd75 Iustin Pop
      "type": "allocate",
5244 d1c2dd75 Iustin Pop
      "name": self.name,
5245 d1c2dd75 Iustin Pop
      "disk_template": self.disk_template,
5246 d1c2dd75 Iustin Pop
      "tags": self.tags,
5247 d1c2dd75 Iustin Pop
      "os": self.os,
5248 d1c2dd75 Iustin Pop
      "vcpus": self.vcpus,
5249 d1c2dd75 Iustin Pop
      "memory": self.mem_size,
5250 d1c2dd75 Iustin Pop
      "disks": self.disks,
5251 d1c2dd75 Iustin Pop
      "disk_space_total": disk_space,
5252 d1c2dd75 Iustin Pop
      "nics": self.nics,
5253 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
5254 d1c2dd75 Iustin Pop
      }
5255 d1c2dd75 Iustin Pop
    data["request"] = request
5256 298fe380 Iustin Pop
5257 d1c2dd75 Iustin Pop
  def _AddRelocateInstance(self):
5258 d1c2dd75 Iustin Pop
    """Add relocate instance data to allocator structure.
5259 298fe380 Iustin Pop

5260 d1c2dd75 Iustin Pop
    This in combination with _IAllocatorGetClusterData will create the
5261 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
5262 d61df03e Iustin Pop

5263 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
5264 d1c2dd75 Iustin Pop
    done.
5265 d61df03e Iustin Pop

5266 d1c2dd75 Iustin Pop
    """
5267 27579978 Iustin Pop
    instance = self.cfg.GetInstanceInfo(self.name)
5268 27579978 Iustin Pop
    if instance is None:
5269 27579978 Iustin Pop
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
5270 27579978 Iustin Pop
                                   " IAllocator" % self.name)
5271 27579978 Iustin Pop
5272 27579978 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5273 27579978 Iustin Pop
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
5274 27579978 Iustin Pop
5275 2a139bb0 Iustin Pop
    if len(instance.secondary_nodes) != 1:
5276 2a139bb0 Iustin Pop
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
5277 2a139bb0 Iustin Pop
5278 27579978 Iustin Pop
    self.required_nodes = 1
5279 27579978 Iustin Pop
5280 27579978 Iustin Pop
    disk_space = _ComputeDiskSize(instance.disk_template,
5281 27579978 Iustin Pop
                                  instance.disks[0].size,
5282 27579978 Iustin Pop
                                  instance.disks[1].size)
5283 27579978 Iustin Pop
5284 d1c2dd75 Iustin Pop
    request = {
5285 2a139bb0 Iustin Pop
      "type": "relocate",
5286 d1c2dd75 Iustin Pop
      "name": self.name,
5287 27579978 Iustin Pop
      "disk_space_total": disk_space,
5288 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
5289 29859cb7 Iustin Pop
      "relocate_from": self.relocate_from,
5290 d1c2dd75 Iustin Pop
      }
5291 27579978 Iustin Pop
    self.in_data["request"] = request
5292 d61df03e Iustin Pop
5293 d1c2dd75 Iustin Pop
  def _BuildInputData(self):
5294 d1c2dd75 Iustin Pop
    """Build input data structures.
5295 d61df03e Iustin Pop

5296 d1c2dd75 Iustin Pop
    """
5297 d1c2dd75 Iustin Pop
    self._ComputeClusterData()
5298 d61df03e Iustin Pop
5299 d1c2dd75 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5300 d1c2dd75 Iustin Pop
      self._AddNewInstance()
5301 d1c2dd75 Iustin Pop
    else:
5302 d1c2dd75 Iustin Pop
      self._AddRelocateInstance()
5303 d61df03e Iustin Pop
5304 d1c2dd75 Iustin Pop
    self.in_text = serializer.Dump(self.in_data)
5305 d61df03e Iustin Pop
5306 8d528b7c Iustin Pop
  def Run(self, name, validate=True, call_fn=rpc.call_iallocator_runner):
5307 d1c2dd75 Iustin Pop
    """Run an instance allocator and return the results.
5308 298fe380 Iustin Pop

5309 d1c2dd75 Iustin Pop
    """
5310 d1c2dd75 Iustin Pop
    data = self.in_text
5311 298fe380 Iustin Pop
5312 8d528b7c Iustin Pop
    result = call_fn(self.sstore.GetMasterNode(), name, self.in_text)
5313 298fe380 Iustin Pop
5314 43f5ea7a Guido Trotter
    if not isinstance(result, (list, tuple)) or len(result) != 4:
5315 8d528b7c Iustin Pop
      raise errors.OpExecError("Invalid result from master iallocator runner")
5316 8d528b7c Iustin Pop
5317 8d528b7c Iustin Pop
    rcode, stdout, stderr, fail = result
5318 8d528b7c Iustin Pop
5319 8d528b7c Iustin Pop
    if rcode == constants.IARUN_NOTFOUND:
5320 8d528b7c Iustin Pop
      raise errors.OpExecError("Can't find allocator '%s'" % name)
5321 8d528b7c Iustin Pop
    elif rcode == constants.IARUN_FAILURE:
5322 38206f3c Iustin Pop
      raise errors.OpExecError("Instance allocator call failed: %s,"
5323 38206f3c Iustin Pop
                               " output: %s" % (fail, stdout+stderr))
5324 8d528b7c Iustin Pop
    self.out_text = stdout
5325 d1c2dd75 Iustin Pop
    if validate:
5326 d1c2dd75 Iustin Pop
      self._ValidateResult()
5327 298fe380 Iustin Pop
5328 d1c2dd75 Iustin Pop
  def _ValidateResult(self):
5329 d1c2dd75 Iustin Pop
    """Process the allocator results.
5330 538475ca Iustin Pop

5331 d1c2dd75 Iustin Pop
    This will process and if successful save the result in
5332 d1c2dd75 Iustin Pop
    self.out_data and the other parameters.
5333 538475ca Iustin Pop

5334 d1c2dd75 Iustin Pop
    """
5335 d1c2dd75 Iustin Pop
    try:
5336 d1c2dd75 Iustin Pop
      rdict = serializer.Load(self.out_text)
5337 d1c2dd75 Iustin Pop
    except Exception, err:
5338 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
5339 d1c2dd75 Iustin Pop
5340 d1c2dd75 Iustin Pop
    if not isinstance(rdict, dict):
5341 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
5342 538475ca Iustin Pop
5343 d1c2dd75 Iustin Pop
    for key in "success", "info", "nodes":
5344 d1c2dd75 Iustin Pop
      if key not in rdict:
5345 d1c2dd75 Iustin Pop
        raise errors.OpExecError("Can't parse iallocator results:"
5346 d1c2dd75 Iustin Pop
                                 " missing key '%s'" % key)
5347 d1c2dd75 Iustin Pop
      setattr(self, key, rdict[key])
5348 538475ca Iustin Pop
5349 d1c2dd75 Iustin Pop
    if not isinstance(rdict["nodes"], list):
5350 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
5351 d1c2dd75 Iustin Pop
                               " is not a list")
5352 d1c2dd75 Iustin Pop
    self.out_data = rdict
5353 538475ca Iustin Pop
5354 538475ca Iustin Pop
5355 d61df03e Iustin Pop
class LUTestAllocator(NoHooksLU):
5356 d61df03e Iustin Pop
  """Run allocator tests.
5357 d61df03e Iustin Pop

5358 d61df03e Iustin Pop
  This LU runs the allocator tests
5359 d61df03e Iustin Pop

5360 d61df03e Iustin Pop
  """
5361 d61df03e Iustin Pop
  _OP_REQP = ["direction", "mode", "name"]
5362 d61df03e Iustin Pop
5363 d61df03e Iustin Pop
  def CheckPrereq(self):
5364 d61df03e Iustin Pop
    """Check prerequisites.
5365 d61df03e Iustin Pop

5366 d61df03e Iustin Pop
    This checks the opcode parameters depending on the director and mode test.
5367 d61df03e Iustin Pop

5368 d61df03e Iustin Pop
    """
5369 298fe380 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5370 d61df03e Iustin Pop
      for attr in ["name", "mem_size", "disks", "disk_template",
5371 d61df03e Iustin Pop
                   "os", "tags", "nics", "vcpus"]:
5372 d61df03e Iustin Pop
        if not hasattr(self.op, attr):
5373 d61df03e Iustin Pop
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
5374 d61df03e Iustin Pop
                                     attr)
5375 d61df03e Iustin Pop
      iname = self.cfg.ExpandInstanceName(self.op.name)
5376 d61df03e Iustin Pop
      if iname is not None:
5377 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
5378 d61df03e Iustin Pop
                                   iname)
5379 d61df03e Iustin Pop
      if not isinstance(self.op.nics, list):
5380 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'nics'")
5381 d61df03e Iustin Pop
      for row in self.op.nics:
5382 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
5383 d61df03e Iustin Pop
            "mac" not in row or
5384 d61df03e Iustin Pop
            "ip" not in row or
5385 d61df03e Iustin Pop
            "bridge" not in row):
5386 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
5387 d61df03e Iustin Pop
                                     " 'nics' parameter")
5388 d61df03e Iustin Pop
      if not isinstance(self.op.disks, list):
5389 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'disks'")
5390 298fe380 Iustin Pop
      if len(self.op.disks) != 2:
5391 298fe380 Iustin Pop
        raise errors.OpPrereqError("Only two-disk configurations supported")
5392 d61df03e Iustin Pop
      for row in self.op.disks:
5393 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
5394 d61df03e Iustin Pop
            "size" not in row or
5395 d61df03e Iustin Pop
            not isinstance(row["size"], int) or
5396 d61df03e Iustin Pop
            "mode" not in row or
5397 d61df03e Iustin Pop
            row["mode"] not in ['r', 'w']):
5398 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
5399 d61df03e Iustin Pop
                                     " 'disks' parameter")
5400 298fe380 Iustin Pop
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
5401 d61df03e Iustin Pop
      if not hasattr(self.op, "name"):
5402 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
5403 d61df03e Iustin Pop
      fname = self.cfg.ExpandInstanceName(self.op.name)
5404 d61df03e Iustin Pop
      if fname is None:
5405 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
5406 d61df03e Iustin Pop
                                   self.op.name)
5407 d61df03e Iustin Pop
      self.op.name = fname
5408 29859cb7 Iustin Pop
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
5409 d61df03e Iustin Pop
    else:
5410 d61df03e Iustin Pop
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
5411 d61df03e Iustin Pop
                                 self.op.mode)
5412 d61df03e Iustin Pop
5413 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
5414 298fe380 Iustin Pop
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
5415 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing allocator name")
5416 298fe380 Iustin Pop
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
5417 d61df03e Iustin Pop
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
5418 d61df03e Iustin Pop
                                 self.op.direction)
5419 d61df03e Iustin Pop
5420 d61df03e Iustin Pop
  def Exec(self, feedback_fn):
5421 d61df03e Iustin Pop
    """Run the allocator test.
5422 d61df03e Iustin Pop

5423 d61df03e Iustin Pop
    """
5424 29859cb7 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5425 29859cb7 Iustin Pop
      ial = IAllocator(self.cfg, self.sstore,
5426 29859cb7 Iustin Pop
                       mode=self.op.mode,
5427 29859cb7 Iustin Pop
                       name=self.op.name,
5428 29859cb7 Iustin Pop
                       mem_size=self.op.mem_size,
5429 29859cb7 Iustin Pop
                       disks=self.op.disks,
5430 29859cb7 Iustin Pop
                       disk_template=self.op.disk_template,
5431 29859cb7 Iustin Pop
                       os=self.op.os,
5432 29859cb7 Iustin Pop
                       tags=self.op.tags,
5433 29859cb7 Iustin Pop
                       nics=self.op.nics,
5434 29859cb7 Iustin Pop
                       vcpus=self.op.vcpus,
5435 29859cb7 Iustin Pop
                       )
5436 29859cb7 Iustin Pop
    else:
5437 29859cb7 Iustin Pop
      ial = IAllocator(self.cfg, self.sstore,
5438 29859cb7 Iustin Pop
                       mode=self.op.mode,
5439 29859cb7 Iustin Pop
                       name=self.op.name,
5440 29859cb7 Iustin Pop
                       relocate_from=list(self.relocate_from),
5441 29859cb7 Iustin Pop
                       )
5442 d61df03e Iustin Pop
5443 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
5444 d1c2dd75 Iustin Pop
      result = ial.in_text
5445 298fe380 Iustin Pop
    else:
5446 d1c2dd75 Iustin Pop
      ial.Run(self.op.allocator, validate=False)
5447 d1c2dd75 Iustin Pop
      result = ial.out_text
5448 298fe380 Iustin Pop
    return result