Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 47a72f18

History | View | Annotate | Download (309.8 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 c70d2d9b Iustin Pop
# pylint: disable-msg=W0201
25 c70d2d9b Iustin Pop
26 c70d2d9b Iustin Pop
# W0201 since most LU attributes are defined in CheckPrereq or similar
27 c70d2d9b Iustin Pop
# functions
28 a8083063 Iustin Pop
29 a8083063 Iustin Pop
import os
30 a8083063 Iustin Pop
import os.path
31 a8083063 Iustin Pop
import time
32 a8083063 Iustin Pop
import re
33 a8083063 Iustin Pop
import platform
34 ffa1c0dc Iustin Pop
import logging
35 74409b12 Iustin Pop
import copy
36 a8083063 Iustin Pop
37 a8083063 Iustin Pop
from ganeti import ssh
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 8d14b30d Iustin Pop
from ganeti import serializer
45 112f18a5 Iustin Pop
from ganeti import ssconf
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 6fd35c4d Michael Hanselmann
    - implement CheckPrereq (except when tasklets are used)
54 6fd35c4d Michael Hanselmann
    - implement Exec (except when tasklets are used)
55 a8083063 Iustin Pop
    - implement BuildHooksEnv
56 a8083063 Iustin Pop
    - redefine HPATH and HTYPE
57 05f86716 Guido Trotter
    - optionally redefine their run requirements:
58 7e55040e Guido Trotter
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
59 05f86716 Guido Trotter

60 05f86716 Guido Trotter
  Note that all commands require root permissions.
61 a8083063 Iustin Pop

62 20777413 Iustin Pop
  @ivar dry_run_result: the value (if any) that will be returned to the caller
63 20777413 Iustin Pop
      in dry-run mode (signalled by opcode dry_run parameter)
64 20777413 Iustin Pop

65 a8083063 Iustin Pop
  """
66 a8083063 Iustin Pop
  HPATH = None
67 a8083063 Iustin Pop
  HTYPE = None
68 a8083063 Iustin Pop
  _OP_REQP = []
69 7e55040e Guido Trotter
  REQ_BGL = True
70 a8083063 Iustin Pop
71 72737a7f Iustin Pop
  def __init__(self, processor, op, context, rpc):
72 a8083063 Iustin Pop
    """Constructor for LogicalUnit.
73 a8083063 Iustin Pop

74 5bbd3f7f Michael Hanselmann
    This needs to be overridden in derived classes in order to check op
75 a8083063 Iustin Pop
    validity.
76 a8083063 Iustin Pop

77 a8083063 Iustin Pop
    """
78 5bfac263 Iustin Pop
    self.proc = processor
79 a8083063 Iustin Pop
    self.op = op
80 77b657a3 Guido Trotter
    self.cfg = context.cfg
81 77b657a3 Guido Trotter
    self.context = context
82 72737a7f Iustin Pop
    self.rpc = rpc
83 ca2a79e1 Guido Trotter
    # Dicts used to declare locking needs to mcpu
84 d465bdc8 Guido Trotter
    self.needed_locks = None
85 6683bba2 Guido Trotter
    self.acquired_locks = {}
86 c772d142 Michael Hanselmann
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
87 ca2a79e1 Guido Trotter
    self.add_locks = {}
88 ca2a79e1 Guido Trotter
    self.remove_locks = {}
89 c4a2fee1 Guido Trotter
    # Used to force good behavior when calling helper functions
90 c4a2fee1 Guido Trotter
    self.recalculate_locks = {}
91 c92b310a Michael Hanselmann
    self.__ssh = None
92 86d9d3bb Iustin Pop
    # logging
93 fe267188 Iustin Pop
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
94 fe267188 Iustin Pop
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
95 d984846d Iustin Pop
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
96 20777413 Iustin Pop
    # support for dry-run
97 20777413 Iustin Pop
    self.dry_run_result = None
98 c92b310a Michael Hanselmann
99 6fd35c4d Michael Hanselmann
    # Tasklets
100 3a012b41 Michael Hanselmann
    self.tasklets = None
101 6fd35c4d Michael Hanselmann
102 a8083063 Iustin Pop
    for attr_name in self._OP_REQP:
103 a8083063 Iustin Pop
      attr_val = getattr(op, attr_name, None)
104 a8083063 Iustin Pop
      if attr_val is None:
105 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Required parameter '%s' missing" %
106 5c983ee5 Iustin Pop
                                   attr_name, errors.ECODE_INVAL)
107 6fd35c4d Michael Hanselmann
108 4be4691d Iustin Pop
    self.CheckArguments()
109 a8083063 Iustin Pop
110 c92b310a Michael Hanselmann
  def __GetSSH(self):
111 c92b310a Michael Hanselmann
    """Returns the SshRunner object
112 c92b310a Michael Hanselmann

113 c92b310a Michael Hanselmann
    """
114 c92b310a Michael Hanselmann
    if not self.__ssh:
115 6b0469d2 Iustin Pop
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
116 c92b310a Michael Hanselmann
    return self.__ssh
117 c92b310a Michael Hanselmann
118 c92b310a Michael Hanselmann
  ssh = property(fget=__GetSSH)
119 c92b310a Michael Hanselmann
120 4be4691d Iustin Pop
  def CheckArguments(self):
121 4be4691d Iustin Pop
    """Check syntactic validity for the opcode arguments.
122 4be4691d Iustin Pop

123 4be4691d Iustin Pop
    This method is for doing a simple syntactic check and ensure
124 4be4691d Iustin Pop
    validity of opcode parameters, without any cluster-related
125 4be4691d Iustin Pop
    checks. While the same can be accomplished in ExpandNames and/or
126 4be4691d Iustin Pop
    CheckPrereq, doing these separate is better because:
127 4be4691d Iustin Pop

128 4be4691d Iustin Pop
      - ExpandNames is left as as purely a lock-related function
129 5bbd3f7f Michael Hanselmann
      - CheckPrereq is run after we have acquired locks (and possible
130 4be4691d Iustin Pop
        waited for them)
131 4be4691d Iustin Pop

132 4be4691d Iustin Pop
    The function is allowed to change the self.op attribute so that
133 4be4691d Iustin Pop
    later methods can no longer worry about missing parameters.
134 4be4691d Iustin Pop

135 4be4691d Iustin Pop
    """
136 4be4691d Iustin Pop
    pass
137 4be4691d Iustin Pop
138 d465bdc8 Guido Trotter
  def ExpandNames(self):
139 d465bdc8 Guido Trotter
    """Expand names for this LU.
140 d465bdc8 Guido Trotter

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

146 d465bdc8 Guido Trotter
    LUs which implement this method must also populate the self.needed_locks
147 d465bdc8 Guido Trotter
    member, as a dict with lock levels as keys, and a list of needed lock names
148 d465bdc8 Guido Trotter
    as values. Rules:
149 e4376078 Iustin Pop

150 e4376078 Iustin Pop
      - use an empty dict if you don't need any lock
151 e4376078 Iustin Pop
      - if you don't need any lock at a particular level omit that level
152 e4376078 Iustin Pop
      - don't put anything for the BGL level
153 e4376078 Iustin Pop
      - if you want all locks at a level use locking.ALL_SET as a value
154 d465bdc8 Guido Trotter

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

159 6fd35c4d Michael Hanselmann
    This function can also define a list of tasklets, which then will be
160 6fd35c4d Michael Hanselmann
    executed in order instead of the usual LU-level CheckPrereq and Exec
161 6fd35c4d Michael Hanselmann
    functions, if those are not defined by the LU.
162 6fd35c4d Michael Hanselmann

163 e4376078 Iustin Pop
    Examples::
164 e4376078 Iustin Pop

165 e4376078 Iustin Pop
      # Acquire all nodes and one instance
166 e4376078 Iustin Pop
      self.needed_locks = {
167 e4376078 Iustin Pop
        locking.LEVEL_NODE: locking.ALL_SET,
168 e4376078 Iustin Pop
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
169 e4376078 Iustin Pop
      }
170 e4376078 Iustin Pop
      # Acquire just two nodes
171 e4376078 Iustin Pop
      self.needed_locks = {
172 e4376078 Iustin Pop
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
173 e4376078 Iustin Pop
      }
174 e4376078 Iustin Pop
      # Acquire no locks
175 e4376078 Iustin Pop
      self.needed_locks = {} # No, you can't leave it to the default value None
176 d465bdc8 Guido Trotter

177 d465bdc8 Guido Trotter
    """
178 d465bdc8 Guido Trotter
    # The implementation of this method is mandatory only if the new LU is
179 d465bdc8 Guido Trotter
    # concurrent, so that old LUs don't need to be changed all at the same
180 d465bdc8 Guido Trotter
    # time.
181 d465bdc8 Guido Trotter
    if self.REQ_BGL:
182 d465bdc8 Guido Trotter
      self.needed_locks = {} # Exclusive LUs don't need locks.
183 d465bdc8 Guido Trotter
    else:
184 d465bdc8 Guido Trotter
      raise NotImplementedError
185 d465bdc8 Guido Trotter
186 fb8dcb62 Guido Trotter
  def DeclareLocks(self, level):
187 fb8dcb62 Guido Trotter
    """Declare LU locking needs for a level
188 fb8dcb62 Guido Trotter

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

196 fb8dcb62 Guido Trotter
    This function is only called if you have something already set in
197 fb8dcb62 Guido Trotter
    self.needed_locks for the level.
198 fb8dcb62 Guido Trotter

199 fb8dcb62 Guido Trotter
    @param level: Locking level which is going to be locked
200 fb8dcb62 Guido Trotter
    @type level: member of ganeti.locking.LEVELS
201 fb8dcb62 Guido Trotter

202 fb8dcb62 Guido Trotter
    """
203 fb8dcb62 Guido Trotter
204 a8083063 Iustin Pop
  def CheckPrereq(self):
205 a8083063 Iustin Pop
    """Check prerequisites for this LU.
206 a8083063 Iustin Pop

207 a8083063 Iustin Pop
    This method should check that the prerequisites for the execution
208 a8083063 Iustin Pop
    of this LU are fulfilled. It can do internode communication, but
209 a8083063 Iustin Pop
    it should be idempotent - no cluster or system changes are
210 a8083063 Iustin Pop
    allowed.
211 a8083063 Iustin Pop

212 a8083063 Iustin Pop
    The method should raise errors.OpPrereqError in case something is
213 a8083063 Iustin Pop
    not fulfilled. Its return value is ignored.
214 a8083063 Iustin Pop

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

218 a8083063 Iustin Pop
    """
219 3a012b41 Michael Hanselmann
    if self.tasklets is not None:
220 b4a9eb66 Michael Hanselmann
      for (idx, tl) in enumerate(self.tasklets):
221 abae1b2b Michael Hanselmann
        logging.debug("Checking prerequisites for tasklet %s/%s",
222 abae1b2b Michael Hanselmann
                      idx + 1, len(self.tasklets))
223 6fd35c4d Michael Hanselmann
        tl.CheckPrereq()
224 6fd35c4d Michael Hanselmann
    else:
225 6fd35c4d Michael Hanselmann
      raise NotImplementedError
226 a8083063 Iustin Pop
227 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
228 a8083063 Iustin Pop
    """Execute the LU.
229 a8083063 Iustin Pop

230 a8083063 Iustin Pop
    This method should implement the actual work. It should raise
231 a8083063 Iustin Pop
    errors.OpExecError for failures that are somewhat dealt with in
232 a8083063 Iustin Pop
    code, or expected.
233 a8083063 Iustin Pop

234 a8083063 Iustin Pop
    """
235 3a012b41 Michael Hanselmann
    if self.tasklets is not None:
236 b4a9eb66 Michael Hanselmann
      for (idx, tl) in enumerate(self.tasklets):
237 abae1b2b Michael Hanselmann
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
238 6fd35c4d Michael Hanselmann
        tl.Exec(feedback_fn)
239 6fd35c4d Michael Hanselmann
    else:
240 6fd35c4d Michael Hanselmann
      raise NotImplementedError
241 a8083063 Iustin Pop
242 a8083063 Iustin Pop
  def BuildHooksEnv(self):
243 a8083063 Iustin Pop
    """Build hooks environment for this LU.
244 a8083063 Iustin Pop

245 a8083063 Iustin Pop
    This method should return a three-node tuple consisting of: a dict
246 a8083063 Iustin Pop
    containing the environment that will be used for running the
247 a8083063 Iustin Pop
    specific hook for this LU, a list of node names on which the hook
248 a8083063 Iustin Pop
    should run before the execution, and a list of node names on which
249 a8083063 Iustin Pop
    the hook should run after the execution.
250 a8083063 Iustin Pop

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

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

258 a8083063 Iustin Pop
    Note that if the HPATH for a LU class is None, this function will
259 a8083063 Iustin Pop
    not be called.
260 a8083063 Iustin Pop

261 a8083063 Iustin Pop
    """
262 a8083063 Iustin Pop
    raise NotImplementedError
263 a8083063 Iustin Pop
264 1fce5219 Guido Trotter
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
265 1fce5219 Guido Trotter
    """Notify the LU about the results of its hooks.
266 1fce5219 Guido Trotter

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

273 e4376078 Iustin Pop
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
274 e4376078 Iustin Pop
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
275 e4376078 Iustin Pop
    @param hook_results: the results of the multi-node hooks rpc call
276 e4376078 Iustin Pop
    @param feedback_fn: function used send feedback back to the caller
277 e4376078 Iustin Pop
    @param lu_result: the previous Exec result this LU had, or None
278 e4376078 Iustin Pop
        in the PRE phase
279 e4376078 Iustin Pop
    @return: the new Exec result, based on the previous result
280 e4376078 Iustin Pop
        and hook results
281 1fce5219 Guido Trotter

282 1fce5219 Guido Trotter
    """
283 2d54e29c Iustin Pop
    # API must be kept, thus we ignore the unused argument and could
284 2d54e29c Iustin Pop
    # be a function warnings
285 2d54e29c Iustin Pop
    # pylint: disable-msg=W0613,R0201
286 1fce5219 Guido Trotter
    return lu_result
287 1fce5219 Guido Trotter
288 43905206 Guido Trotter
  def _ExpandAndLockInstance(self):
289 43905206 Guido Trotter
    """Helper function to expand and lock an instance.
290 43905206 Guido Trotter

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

297 43905206 Guido Trotter
    """
298 43905206 Guido Trotter
    if self.needed_locks is None:
299 43905206 Guido Trotter
      self.needed_locks = {}
300 43905206 Guido Trotter
    else:
301 43905206 Guido Trotter
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
302 43905206 Guido Trotter
        "_ExpandAndLockInstance called with instance-level locks set"
303 43905206 Guido Trotter
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
304 43905206 Guido Trotter
    if expanded_name is None:
305 43905206 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' not known" %
306 5c983ee5 Iustin Pop
                                 self.op.instance_name, errors.ECODE_NOENT)
307 43905206 Guido Trotter
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
308 43905206 Guido Trotter
    self.op.instance_name = expanded_name
309 43905206 Guido Trotter
310 a82ce292 Guido Trotter
  def _LockInstancesNodes(self, primary_only=False):
311 c4a2fee1 Guido Trotter
    """Helper function to declare instances' nodes for locking.
312 c4a2fee1 Guido Trotter

313 c4a2fee1 Guido Trotter
    This function should be called after locking one or more instances to lock
314 c4a2fee1 Guido Trotter
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
315 c4a2fee1 Guido Trotter
    with all primary or secondary nodes for instances already locked and
316 c4a2fee1 Guido Trotter
    present in self.needed_locks[locking.LEVEL_INSTANCE].
317 c4a2fee1 Guido Trotter

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

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

324 e4376078 Iustin Pop
    If should be called in DeclareLocks in a way similar to::
325 c4a2fee1 Guido Trotter

326 e4376078 Iustin Pop
      if level == locking.LEVEL_NODE:
327 e4376078 Iustin Pop
        self._LockInstancesNodes()
328 c4a2fee1 Guido Trotter

329 a82ce292 Guido Trotter
    @type primary_only: boolean
330 a82ce292 Guido Trotter
    @param primary_only: only lock primary nodes of locked instances
331 a82ce292 Guido Trotter

332 c4a2fee1 Guido Trotter
    """
333 c4a2fee1 Guido Trotter
    assert locking.LEVEL_NODE in self.recalculate_locks, \
334 c4a2fee1 Guido Trotter
      "_LockInstancesNodes helper function called with no nodes to recalculate"
335 c4a2fee1 Guido Trotter
336 c4a2fee1 Guido Trotter
    # TODO: check if we're really been called with the instance locks held
337 c4a2fee1 Guido Trotter
338 c4a2fee1 Guido Trotter
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
339 c4a2fee1 Guido Trotter
    # future we might want to have different behaviors depending on the value
340 c4a2fee1 Guido Trotter
    # of self.recalculate_locks[locking.LEVEL_NODE]
341 c4a2fee1 Guido Trotter
    wanted_nodes = []
342 6683bba2 Guido Trotter
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
343 c4a2fee1 Guido Trotter
      instance = self.context.cfg.GetInstanceInfo(instance_name)
344 c4a2fee1 Guido Trotter
      wanted_nodes.append(instance.primary_node)
345 a82ce292 Guido Trotter
      if not primary_only:
346 a82ce292 Guido Trotter
        wanted_nodes.extend(instance.secondary_nodes)
347 9513b6ab Guido Trotter
348 9513b6ab Guido Trotter
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
349 9513b6ab Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
350 9513b6ab Guido Trotter
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
351 9513b6ab Guido Trotter
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
352 c4a2fee1 Guido Trotter
353 c4a2fee1 Guido Trotter
    del self.recalculate_locks[locking.LEVEL_NODE]
354 c4a2fee1 Guido Trotter
355 a8083063 Iustin Pop
356 fe267188 Iustin Pop
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
357 a8083063 Iustin Pop
  """Simple LU which runs no hooks.
358 a8083063 Iustin Pop

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

362 a8083063 Iustin Pop
  """
363 a8083063 Iustin Pop
  HPATH = None
364 a8083063 Iustin Pop
  HTYPE = None
365 a8083063 Iustin Pop
366 fc8a6b8f Iustin Pop
  def BuildHooksEnv(self):
367 fc8a6b8f Iustin Pop
    """Empty BuildHooksEnv for NoHooksLu.
368 fc8a6b8f Iustin Pop

369 fc8a6b8f Iustin Pop
    This just raises an error.
370 fc8a6b8f Iustin Pop

371 fc8a6b8f Iustin Pop
    """
372 fc8a6b8f Iustin Pop
    assert False, "BuildHooksEnv called for NoHooksLUs"
373 fc8a6b8f Iustin Pop
374 a8083063 Iustin Pop
375 9a6800e1 Michael Hanselmann
class Tasklet:
376 9a6800e1 Michael Hanselmann
  """Tasklet base class.
377 9a6800e1 Michael Hanselmann

378 9a6800e1 Michael Hanselmann
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
379 9a6800e1 Michael Hanselmann
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
380 9a6800e1 Michael Hanselmann
  tasklets know nothing about locks.
381 9a6800e1 Michael Hanselmann

382 9a6800e1 Michael Hanselmann
  Subclasses must follow these rules:
383 9a6800e1 Michael Hanselmann
    - Implement CheckPrereq
384 9a6800e1 Michael Hanselmann
    - Implement Exec
385 9a6800e1 Michael Hanselmann

386 9a6800e1 Michael Hanselmann
  """
387 464243a7 Michael Hanselmann
  def __init__(self, lu):
388 464243a7 Michael Hanselmann
    self.lu = lu
389 464243a7 Michael Hanselmann
390 464243a7 Michael Hanselmann
    # Shortcuts
391 464243a7 Michael Hanselmann
    self.cfg = lu.cfg
392 464243a7 Michael Hanselmann
    self.rpc = lu.rpc
393 464243a7 Michael Hanselmann
394 9a6800e1 Michael Hanselmann
  def CheckPrereq(self):
395 9a6800e1 Michael Hanselmann
    """Check prerequisites for this tasklets.
396 9a6800e1 Michael Hanselmann

397 9a6800e1 Michael Hanselmann
    This method should check whether the prerequisites for the execution of
398 9a6800e1 Michael Hanselmann
    this tasklet are fulfilled. It can do internode communication, but it
399 9a6800e1 Michael Hanselmann
    should be idempotent - no cluster or system changes are allowed.
400 9a6800e1 Michael Hanselmann

401 9a6800e1 Michael Hanselmann
    The method should raise errors.OpPrereqError in case something is not
402 9a6800e1 Michael Hanselmann
    fulfilled. Its return value is ignored.
403 9a6800e1 Michael Hanselmann

404 9a6800e1 Michael Hanselmann
    This method should also update all parameters to their canonical form if it
405 9a6800e1 Michael Hanselmann
    hasn't been done before.
406 9a6800e1 Michael Hanselmann

407 9a6800e1 Michael Hanselmann
    """
408 9a6800e1 Michael Hanselmann
    raise NotImplementedError
409 9a6800e1 Michael Hanselmann
410 9a6800e1 Michael Hanselmann
  def Exec(self, feedback_fn):
411 9a6800e1 Michael Hanselmann
    """Execute the tasklet.
412 9a6800e1 Michael Hanselmann

413 9a6800e1 Michael Hanselmann
    This method should implement the actual work. It should raise
414 9a6800e1 Michael Hanselmann
    errors.OpExecError for failures that are somewhat dealt with in code, or
415 9a6800e1 Michael Hanselmann
    expected.
416 9a6800e1 Michael Hanselmann

417 9a6800e1 Michael Hanselmann
    """
418 9a6800e1 Michael Hanselmann
    raise NotImplementedError
419 9a6800e1 Michael Hanselmann
420 9a6800e1 Michael Hanselmann
421 dcb93971 Michael Hanselmann
def _GetWantedNodes(lu, nodes):
422 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded node names.
423 83120a01 Michael Hanselmann

424 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
425 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
426 e4376078 Iustin Pop
  @type nodes: list
427 e4376078 Iustin Pop
  @param nodes: list of node names or None for all nodes
428 e4376078 Iustin Pop
  @rtype: list
429 e4376078 Iustin Pop
  @return: the list of nodes, sorted
430 e4376078 Iustin Pop
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
431 83120a01 Michael Hanselmann

432 83120a01 Michael Hanselmann
  """
433 3312b702 Iustin Pop
  if not isinstance(nodes, list):
434 5c983ee5 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'nodes'",
435 5c983ee5 Iustin Pop
                               errors.ECODE_INVAL)
436 dcb93971 Michael Hanselmann
437 ea47808a Guido Trotter
  if not nodes:
438 ea47808a Guido Trotter
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
439 ea47808a Guido Trotter
      " non-empty list of nodes whose name is to be expanded.")
440 dcb93971 Michael Hanselmann
441 ea47808a Guido Trotter
  wanted = []
442 ea47808a Guido Trotter
  for name in nodes:
443 ea47808a Guido Trotter
    node = lu.cfg.ExpandNodeName(name)
444 ea47808a Guido Trotter
    if node is None:
445 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("No such node name '%s'" % name,
446 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
447 ea47808a Guido Trotter
    wanted.append(node)
448 dcb93971 Michael Hanselmann
449 a7ba5e53 Iustin Pop
  return utils.NiceSort(wanted)
450 3312b702 Iustin Pop
451 3312b702 Iustin Pop
452 3312b702 Iustin Pop
def _GetWantedInstances(lu, instances):
453 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded instance names.
454 3312b702 Iustin Pop

455 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
456 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
457 e4376078 Iustin Pop
  @type instances: list
458 e4376078 Iustin Pop
  @param instances: list of instance names or None for all instances
459 e4376078 Iustin Pop
  @rtype: list
460 e4376078 Iustin Pop
  @return: the list of instances, sorted
461 e4376078 Iustin Pop
  @raise errors.OpPrereqError: if the instances parameter is wrong type
462 e4376078 Iustin Pop
  @raise errors.OpPrereqError: if any of the passed instances is not found
463 3312b702 Iustin Pop

464 3312b702 Iustin Pop
  """
465 3312b702 Iustin Pop
  if not isinstance(instances, list):
466 5c983ee5 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'instances'",
467 5c983ee5 Iustin Pop
                               errors.ECODE_INVAL)
468 3312b702 Iustin Pop
469 3312b702 Iustin Pop
  if instances:
470 3312b702 Iustin Pop
    wanted = []
471 3312b702 Iustin Pop
472 3312b702 Iustin Pop
    for name in instances:
473 a7ba5e53 Iustin Pop
      instance = lu.cfg.ExpandInstanceName(name)
474 3312b702 Iustin Pop
      if instance is None:
475 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("No such instance name '%s'" % name,
476 5c983ee5 Iustin Pop
                                   errors.ECODE_NOENT)
477 3312b702 Iustin Pop
      wanted.append(instance)
478 3312b702 Iustin Pop
479 3312b702 Iustin Pop
  else:
480 a7f5dc98 Iustin Pop
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
481 a7f5dc98 Iustin Pop
  return wanted
482 dcb93971 Michael Hanselmann
483 dcb93971 Michael Hanselmann
484 dcb93971 Michael Hanselmann
def _CheckOutputFields(static, dynamic, selected):
485 83120a01 Michael Hanselmann
  """Checks whether all selected fields are valid.
486 83120a01 Michael Hanselmann

487 a2d2e1a7 Iustin Pop
  @type static: L{utils.FieldSet}
488 31bf511f Iustin Pop
  @param static: static fields set
489 a2d2e1a7 Iustin Pop
  @type dynamic: L{utils.FieldSet}
490 31bf511f Iustin Pop
  @param dynamic: dynamic fields set
491 83120a01 Michael Hanselmann

492 83120a01 Michael Hanselmann
  """
493 a2d2e1a7 Iustin Pop
  f = utils.FieldSet()
494 31bf511f Iustin Pop
  f.Extend(static)
495 31bf511f Iustin Pop
  f.Extend(dynamic)
496 dcb93971 Michael Hanselmann
497 31bf511f Iustin Pop
  delta = f.NonMatching(selected)
498 31bf511f Iustin Pop
  if delta:
499 3ecf6786 Iustin Pop
    raise errors.OpPrereqError("Unknown output fields selected: %s"
500 5c983ee5 Iustin Pop
                               % ",".join(delta), errors.ECODE_INVAL)
501 dcb93971 Michael Hanselmann
502 dcb93971 Michael Hanselmann
503 a5961235 Iustin Pop
def _CheckBooleanOpField(op, name):
504 a5961235 Iustin Pop
  """Validates boolean opcode parameters.
505 a5961235 Iustin Pop

506 a5961235 Iustin Pop
  This will ensure that an opcode parameter is either a boolean value,
507 a5961235 Iustin Pop
  or None (but that it always exists).
508 a5961235 Iustin Pop

509 a5961235 Iustin Pop
  """
510 a5961235 Iustin Pop
  val = getattr(op, name, None)
511 a5961235 Iustin Pop
  if not (val is None or isinstance(val, bool)):
512 a5961235 Iustin Pop
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
513 5c983ee5 Iustin Pop
                               (name, str(val)), errors.ECODE_INVAL)
514 a5961235 Iustin Pop
  setattr(op, name, val)
515 a5961235 Iustin Pop
516 a5961235 Iustin Pop
517 7736a5f2 Iustin Pop
def _CheckGlobalHvParams(params):
518 7736a5f2 Iustin Pop
  """Validates that given hypervisor params are not global ones.
519 7736a5f2 Iustin Pop

520 7736a5f2 Iustin Pop
  This will ensure that instances don't get customised versions of
521 7736a5f2 Iustin Pop
  global params.
522 7736a5f2 Iustin Pop

523 7736a5f2 Iustin Pop
  """
524 7736a5f2 Iustin Pop
  used_globals = constants.HVC_GLOBALS.intersection(params)
525 7736a5f2 Iustin Pop
  if used_globals:
526 7736a5f2 Iustin Pop
    msg = ("The following hypervisor parameters are global and cannot"
527 7736a5f2 Iustin Pop
           " be customized at instance level, please modify them at"
528 1f864b60 Iustin Pop
           " cluster level: %s" % utils.CommaJoin(used_globals))
529 7736a5f2 Iustin Pop
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
530 7736a5f2 Iustin Pop
531 7736a5f2 Iustin Pop
532 a5961235 Iustin Pop
def _CheckNodeOnline(lu, node):
533 a5961235 Iustin Pop
  """Ensure that a given node is online.
534 a5961235 Iustin Pop

535 a5961235 Iustin Pop
  @param lu: the LU on behalf of which we make the check
536 a5961235 Iustin Pop
  @param node: the node to check
537 733a2b6a Iustin Pop
  @raise errors.OpPrereqError: if the node is offline
538 a5961235 Iustin Pop

539 a5961235 Iustin Pop
  """
540 a5961235 Iustin Pop
  if lu.cfg.GetNodeInfo(node).offline:
541 5c983ee5 Iustin Pop
    raise errors.OpPrereqError("Can't use offline node %s" % node,
542 5c983ee5 Iustin Pop
                               errors.ECODE_INVAL)
543 a5961235 Iustin Pop
544 a5961235 Iustin Pop
545 733a2b6a Iustin Pop
def _CheckNodeNotDrained(lu, node):
546 733a2b6a Iustin Pop
  """Ensure that a given node is not drained.
547 733a2b6a Iustin Pop

548 733a2b6a Iustin Pop
  @param lu: the LU on behalf of which we make the check
549 733a2b6a Iustin Pop
  @param node: the node to check
550 733a2b6a Iustin Pop
  @raise errors.OpPrereqError: if the node is drained
551 733a2b6a Iustin Pop

552 733a2b6a Iustin Pop
  """
553 733a2b6a Iustin Pop
  if lu.cfg.GetNodeInfo(node).drained:
554 5c983ee5 Iustin Pop
    raise errors.OpPrereqError("Can't use drained node %s" % node,
555 5c983ee5 Iustin Pop
                               errors.ECODE_INVAL)
556 733a2b6a Iustin Pop
557 733a2b6a Iustin Pop
558 ecb215b5 Michael Hanselmann
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
559 67fc3042 Iustin Pop
                          memory, vcpus, nics, disk_template, disks,
560 7c4d6c7b Michael Hanselmann
                          bep, hvp, hypervisor_name):
561 e4376078 Iustin Pop
  """Builds instance related env variables for hooks
562 e4376078 Iustin Pop

563 e4376078 Iustin Pop
  This builds the hook environment from individual variables.
564 e4376078 Iustin Pop

565 e4376078 Iustin Pop
  @type name: string
566 e4376078 Iustin Pop
  @param name: the name of the instance
567 e4376078 Iustin Pop
  @type primary_node: string
568 e4376078 Iustin Pop
  @param primary_node: the name of the instance's primary node
569 e4376078 Iustin Pop
  @type secondary_nodes: list
570 e4376078 Iustin Pop
  @param secondary_nodes: list of secondary nodes as strings
571 e4376078 Iustin Pop
  @type os_type: string
572 e4376078 Iustin Pop
  @param os_type: the name of the instance's OS
573 0d68c45d Iustin Pop
  @type status: boolean
574 0d68c45d Iustin Pop
  @param status: the should_run status of the instance
575 e4376078 Iustin Pop
  @type memory: string
576 e4376078 Iustin Pop
  @param memory: the memory size of the instance
577 e4376078 Iustin Pop
  @type vcpus: string
578 e4376078 Iustin Pop
  @param vcpus: the count of VCPUs the instance has
579 e4376078 Iustin Pop
  @type nics: list
580 5e3d3eb3 Guido Trotter
  @param nics: list of tuples (ip, mac, mode, link) representing
581 5e3d3eb3 Guido Trotter
      the NICs the instance has
582 2c2690c9 Iustin Pop
  @type disk_template: string
583 5bbd3f7f Michael Hanselmann
  @param disk_template: the disk template of the instance
584 2c2690c9 Iustin Pop
  @type disks: list
585 2c2690c9 Iustin Pop
  @param disks: the list of (size, mode) pairs
586 67fc3042 Iustin Pop
  @type bep: dict
587 67fc3042 Iustin Pop
  @param bep: the backend parameters for the instance
588 67fc3042 Iustin Pop
  @type hvp: dict
589 67fc3042 Iustin Pop
  @param hvp: the hypervisor parameters for the instance
590 7c4d6c7b Michael Hanselmann
  @type hypervisor_name: string
591 7c4d6c7b Michael Hanselmann
  @param hypervisor_name: the hypervisor for the instance
592 e4376078 Iustin Pop
  @rtype: dict
593 e4376078 Iustin Pop
  @return: the hook environment for this instance
594 ecb215b5 Michael Hanselmann

595 396e1b78 Michael Hanselmann
  """
596 0d68c45d Iustin Pop
  if status:
597 0d68c45d Iustin Pop
    str_status = "up"
598 0d68c45d Iustin Pop
  else:
599 0d68c45d Iustin Pop
    str_status = "down"
600 396e1b78 Michael Hanselmann
  env = {
601 0e137c28 Iustin Pop
    "OP_TARGET": name,
602 396e1b78 Michael Hanselmann
    "INSTANCE_NAME": name,
603 396e1b78 Michael Hanselmann
    "INSTANCE_PRIMARY": primary_node,
604 396e1b78 Michael Hanselmann
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
605 ecb215b5 Michael Hanselmann
    "INSTANCE_OS_TYPE": os_type,
606 0d68c45d Iustin Pop
    "INSTANCE_STATUS": str_status,
607 396e1b78 Michael Hanselmann
    "INSTANCE_MEMORY": memory,
608 396e1b78 Michael Hanselmann
    "INSTANCE_VCPUS": vcpus,
609 2c2690c9 Iustin Pop
    "INSTANCE_DISK_TEMPLATE": disk_template,
610 7c4d6c7b Michael Hanselmann
    "INSTANCE_HYPERVISOR": hypervisor_name,
611 396e1b78 Michael Hanselmann
  }
612 396e1b78 Michael Hanselmann
613 396e1b78 Michael Hanselmann
  if nics:
614 396e1b78 Michael Hanselmann
    nic_count = len(nics)
615 62f0dd02 Guido Trotter
    for idx, (ip, mac, mode, link) in enumerate(nics):
616 396e1b78 Michael Hanselmann
      if ip is None:
617 396e1b78 Michael Hanselmann
        ip = ""
618 396e1b78 Michael Hanselmann
      env["INSTANCE_NIC%d_IP" % idx] = ip
619 2c2690c9 Iustin Pop
      env["INSTANCE_NIC%d_MAC" % idx] = mac
620 62f0dd02 Guido Trotter
      env["INSTANCE_NIC%d_MODE" % idx] = mode
621 62f0dd02 Guido Trotter
      env["INSTANCE_NIC%d_LINK" % idx] = link
622 62f0dd02 Guido Trotter
      if mode == constants.NIC_MODE_BRIDGED:
623 62f0dd02 Guido Trotter
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
624 396e1b78 Michael Hanselmann
  else:
625 396e1b78 Michael Hanselmann
    nic_count = 0
626 396e1b78 Michael Hanselmann
627 396e1b78 Michael Hanselmann
  env["INSTANCE_NIC_COUNT"] = nic_count
628 396e1b78 Michael Hanselmann
629 2c2690c9 Iustin Pop
  if disks:
630 2c2690c9 Iustin Pop
    disk_count = len(disks)
631 2c2690c9 Iustin Pop
    for idx, (size, mode) in enumerate(disks):
632 2c2690c9 Iustin Pop
      env["INSTANCE_DISK%d_SIZE" % idx] = size
633 2c2690c9 Iustin Pop
      env["INSTANCE_DISK%d_MODE" % idx] = mode
634 2c2690c9 Iustin Pop
  else:
635 2c2690c9 Iustin Pop
    disk_count = 0
636 2c2690c9 Iustin Pop
637 2c2690c9 Iustin Pop
  env["INSTANCE_DISK_COUNT"] = disk_count
638 2c2690c9 Iustin Pop
639 67fc3042 Iustin Pop
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
640 67fc3042 Iustin Pop
    for key, value in source.items():
641 67fc3042 Iustin Pop
      env["INSTANCE_%s_%s" % (kind, key)] = value
642 67fc3042 Iustin Pop
643 396e1b78 Michael Hanselmann
  return env
644 396e1b78 Michael Hanselmann
645 96acbc09 Michael Hanselmann
646 f9b10246 Guido Trotter
def _NICListToTuple(lu, nics):
647 62f0dd02 Guido Trotter
  """Build a list of nic information tuples.
648 62f0dd02 Guido Trotter

649 f9b10246 Guido Trotter
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
650 f9b10246 Guido Trotter
  value in LUQueryInstanceData.
651 62f0dd02 Guido Trotter

652 62f0dd02 Guido Trotter
  @type lu:  L{LogicalUnit}
653 62f0dd02 Guido Trotter
  @param lu: the logical unit on whose behalf we execute
654 62f0dd02 Guido Trotter
  @type nics: list of L{objects.NIC}
655 62f0dd02 Guido Trotter
  @param nics: list of nics to convert to hooks tuples
656 62f0dd02 Guido Trotter

657 62f0dd02 Guido Trotter
  """
658 62f0dd02 Guido Trotter
  hooks_nics = []
659 62f0dd02 Guido Trotter
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
660 62f0dd02 Guido Trotter
  for nic in nics:
661 62f0dd02 Guido Trotter
    ip = nic.ip
662 62f0dd02 Guido Trotter
    mac = nic.mac
663 62f0dd02 Guido Trotter
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
664 62f0dd02 Guido Trotter
    mode = filled_params[constants.NIC_MODE]
665 62f0dd02 Guido Trotter
    link = filled_params[constants.NIC_LINK]
666 62f0dd02 Guido Trotter
    hooks_nics.append((ip, mac, mode, link))
667 62f0dd02 Guido Trotter
  return hooks_nics
668 396e1b78 Michael Hanselmann
669 96acbc09 Michael Hanselmann
670 338e51e8 Iustin Pop
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
671 ecb215b5 Michael Hanselmann
  """Builds instance related env variables for hooks from an object.
672 ecb215b5 Michael Hanselmann

673 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
674 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
675 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
676 e4376078 Iustin Pop
  @param instance: the instance for which we should build the
677 e4376078 Iustin Pop
      environment
678 e4376078 Iustin Pop
  @type override: dict
679 e4376078 Iustin Pop
  @param override: dictionary with key/values that will override
680 e4376078 Iustin Pop
      our values
681 e4376078 Iustin Pop
  @rtype: dict
682 e4376078 Iustin Pop
  @return: the hook environment dictionary
683 e4376078 Iustin Pop

684 ecb215b5 Michael Hanselmann
  """
685 67fc3042 Iustin Pop
  cluster = lu.cfg.GetClusterInfo()
686 67fc3042 Iustin Pop
  bep = cluster.FillBE(instance)
687 67fc3042 Iustin Pop
  hvp = cluster.FillHV(instance)
688 396e1b78 Michael Hanselmann
  args = {
689 396e1b78 Michael Hanselmann
    'name': instance.name,
690 396e1b78 Michael Hanselmann
    'primary_node': instance.primary_node,
691 396e1b78 Michael Hanselmann
    'secondary_nodes': instance.secondary_nodes,
692 ecb215b5 Michael Hanselmann
    'os_type': instance.os,
693 0d68c45d Iustin Pop
    'status': instance.admin_up,
694 338e51e8 Iustin Pop
    'memory': bep[constants.BE_MEMORY],
695 338e51e8 Iustin Pop
    'vcpus': bep[constants.BE_VCPUS],
696 f9b10246 Guido Trotter
    'nics': _NICListToTuple(lu, instance.nics),
697 2c2690c9 Iustin Pop
    'disk_template': instance.disk_template,
698 2c2690c9 Iustin Pop
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
699 67fc3042 Iustin Pop
    'bep': bep,
700 67fc3042 Iustin Pop
    'hvp': hvp,
701 b0c63e2b Iustin Pop
    'hypervisor_name': instance.hypervisor,
702 396e1b78 Michael Hanselmann
  }
703 396e1b78 Michael Hanselmann
  if override:
704 396e1b78 Michael Hanselmann
    args.update(override)
705 7260cfbe Iustin Pop
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
706 396e1b78 Michael Hanselmann
707 396e1b78 Michael Hanselmann
708 44485f49 Guido Trotter
def _AdjustCandidatePool(lu, exceptions):
709 ec0292f1 Iustin Pop
  """Adjust the candidate pool after node operations.
710 ec0292f1 Iustin Pop

711 ec0292f1 Iustin Pop
  """
712 44485f49 Guido Trotter
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
713 ec0292f1 Iustin Pop
  if mod_list:
714 ec0292f1 Iustin Pop
    lu.LogInfo("Promoted nodes to master candidate role: %s",
715 1f864b60 Iustin Pop
               utils.CommaJoin(node.name for node in mod_list))
716 ec0292f1 Iustin Pop
    for name in mod_list:
717 ec0292f1 Iustin Pop
      lu.context.ReaddNode(name)
718 44485f49 Guido Trotter
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
719 ec0292f1 Iustin Pop
  if mc_now > mc_max:
720 ec0292f1 Iustin Pop
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
721 ec0292f1 Iustin Pop
               (mc_now, mc_max))
722 ec0292f1 Iustin Pop
723 ec0292f1 Iustin Pop
724 6d7e1f20 Guido Trotter
def _DecideSelfPromotion(lu, exceptions=None):
725 6d7e1f20 Guido Trotter
  """Decide whether I should promote myself as a master candidate.
726 6d7e1f20 Guido Trotter

727 6d7e1f20 Guido Trotter
  """
728 6d7e1f20 Guido Trotter
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
729 6d7e1f20 Guido Trotter
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
730 6d7e1f20 Guido Trotter
  # the new node will increase mc_max with one, so:
731 6d7e1f20 Guido Trotter
  mc_should = min(mc_should + 1, cp_size)
732 6d7e1f20 Guido Trotter
  return mc_now < mc_should
733 6d7e1f20 Guido Trotter
734 6d7e1f20 Guido Trotter
735 b165e77e Guido Trotter
def _CheckNicsBridgesExist(lu, target_nics, target_node,
736 b165e77e Guido Trotter
                               profile=constants.PP_DEFAULT):
737 b165e77e Guido Trotter
  """Check that the brigdes needed by a list of nics exist.
738 b165e77e Guido Trotter

739 b165e77e Guido Trotter
  """
740 b165e77e Guido Trotter
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
741 b165e77e Guido Trotter
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
742 b165e77e Guido Trotter
                for nic in target_nics]
743 b165e77e Guido Trotter
  brlist = [params[constants.NIC_LINK] for params in paramslist
744 b165e77e Guido Trotter
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
745 b165e77e Guido Trotter
  if brlist:
746 b165e77e Guido Trotter
    result = lu.rpc.call_bridges_exist(target_node, brlist)
747 4c4e4e1e Iustin Pop
    result.Raise("Error checking bridges on destination node '%s'" %
748 045dd6d9 Iustin Pop
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
749 b165e77e Guido Trotter
750 b165e77e Guido Trotter
751 b165e77e Guido Trotter
def _CheckInstanceBridgesExist(lu, instance, node=None):
752 bf6929a2 Alexander Schreiber
  """Check that the brigdes needed by an instance exist.
753 bf6929a2 Alexander Schreiber

754 bf6929a2 Alexander Schreiber
  """
755 b165e77e Guido Trotter
  if node is None:
756 29921401 Iustin Pop
    node = instance.primary_node
757 b165e77e Guido Trotter
  _CheckNicsBridgesExist(lu, instance.nics, node)
758 bf6929a2 Alexander Schreiber
759 bf6929a2 Alexander Schreiber
760 c6f1af07 Iustin Pop
def _CheckOSVariant(os_obj, name):
761 f2c05717 Guido Trotter
  """Check whether an OS name conforms to the os variants specification.
762 f2c05717 Guido Trotter

763 c6f1af07 Iustin Pop
  @type os_obj: L{objects.OS}
764 c6f1af07 Iustin Pop
  @param os_obj: OS object to check
765 f2c05717 Guido Trotter
  @type name: string
766 f2c05717 Guido Trotter
  @param name: OS name passed by the user, to check for validity
767 f2c05717 Guido Trotter

768 f2c05717 Guido Trotter
  """
769 c6f1af07 Iustin Pop
  if not os_obj.supported_variants:
770 f2c05717 Guido Trotter
    return
771 f2c05717 Guido Trotter
  try:
772 f2c05717 Guido Trotter
    variant = name.split("+", 1)[1]
773 f2c05717 Guido Trotter
  except IndexError:
774 5c983ee5 Iustin Pop
    raise errors.OpPrereqError("OS name must include a variant",
775 5c983ee5 Iustin Pop
                               errors.ECODE_INVAL)
776 f2c05717 Guido Trotter
777 c6f1af07 Iustin Pop
  if variant not in os_obj.supported_variants:
778 5c983ee5 Iustin Pop
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
779 f2c05717 Guido Trotter
780 f2c05717 Guido Trotter
781 5ba9701d Michael Hanselmann
def _GetNodeInstancesInner(cfg, fn):
782 5ba9701d Michael Hanselmann
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
783 5ba9701d Michael Hanselmann
784 5ba9701d Michael Hanselmann
785 e9721add Michael Hanselmann
def _GetNodeInstances(cfg, node_name):
786 e9721add Michael Hanselmann
  """Returns a list of all primary and secondary instances on a node.
787 e9721add Michael Hanselmann

788 e9721add Michael Hanselmann
  """
789 e9721add Michael Hanselmann
790 e9721add Michael Hanselmann
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
791 e9721add Michael Hanselmann
792 e9721add Michael Hanselmann
793 80cb875c Michael Hanselmann
def _GetNodePrimaryInstances(cfg, node_name):
794 80cb875c Michael Hanselmann
  """Returns primary instances on a node.
795 80cb875c Michael Hanselmann

796 80cb875c Michael Hanselmann
  """
797 5ba9701d Michael Hanselmann
  return _GetNodeInstancesInner(cfg,
798 5ba9701d Michael Hanselmann
                                lambda inst: node_name == inst.primary_node)
799 80cb875c Michael Hanselmann
800 80cb875c Michael Hanselmann
801 692738fc Michael Hanselmann
def _GetNodeSecondaryInstances(cfg, node_name):
802 692738fc Michael Hanselmann
  """Returns secondary instances on a node.
803 692738fc Michael Hanselmann

804 692738fc Michael Hanselmann
  """
805 5ba9701d Michael Hanselmann
  return _GetNodeInstancesInner(cfg,
806 5ba9701d Michael Hanselmann
                                lambda inst: node_name in inst.secondary_nodes)
807 692738fc Michael Hanselmann
808 692738fc Michael Hanselmann
809 efb8da02 Michael Hanselmann
def _GetStorageTypeArgs(cfg, storage_type):
810 efb8da02 Michael Hanselmann
  """Returns the arguments for a storage type.
811 efb8da02 Michael Hanselmann

812 efb8da02 Michael Hanselmann
  """
813 efb8da02 Michael Hanselmann
  # Special case for file storage
814 efb8da02 Michael Hanselmann
  if storage_type == constants.ST_FILE:
815 a4d138b7 Michael Hanselmann
    # storage.FileStorage wants a list of storage directories
816 a4d138b7 Michael Hanselmann
    return [[cfg.GetFileStorageDir()]]
817 efb8da02 Michael Hanselmann
818 efb8da02 Michael Hanselmann
  return []
819 efb8da02 Michael Hanselmann
820 efb8da02 Michael Hanselmann
821 2d9005d8 Michael Hanselmann
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
822 2d9005d8 Michael Hanselmann
  faulty = []
823 2d9005d8 Michael Hanselmann
824 2d9005d8 Michael Hanselmann
  for dev in instance.disks:
825 2d9005d8 Michael Hanselmann
    cfg.SetDiskID(dev, node_name)
826 2d9005d8 Michael Hanselmann
827 2d9005d8 Michael Hanselmann
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
828 2d9005d8 Michael Hanselmann
  result.Raise("Failed to get disk status from node %s" % node_name,
829 045dd6d9 Iustin Pop
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
830 2d9005d8 Michael Hanselmann
831 2d9005d8 Michael Hanselmann
  for idx, bdev_status in enumerate(result.payload):
832 2d9005d8 Michael Hanselmann
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
833 2d9005d8 Michael Hanselmann
      faulty.append(idx)
834 2d9005d8 Michael Hanselmann
835 2d9005d8 Michael Hanselmann
  return faulty
836 2d9005d8 Michael Hanselmann
837 2d9005d8 Michael Hanselmann
838 b5f5fae9 Luca Bigliardi
class LUPostInitCluster(LogicalUnit):
839 b5f5fae9 Luca Bigliardi
  """Logical unit for running hooks after cluster initialization.
840 b5f5fae9 Luca Bigliardi

841 b5f5fae9 Luca Bigliardi
  """
842 b5f5fae9 Luca Bigliardi
  HPATH = "cluster-init"
843 b5f5fae9 Luca Bigliardi
  HTYPE = constants.HTYPE_CLUSTER
844 b5f5fae9 Luca Bigliardi
  _OP_REQP = []
845 b5f5fae9 Luca Bigliardi
846 b5f5fae9 Luca Bigliardi
  def BuildHooksEnv(self):
847 b5f5fae9 Luca Bigliardi
    """Build hooks env.
848 b5f5fae9 Luca Bigliardi

849 b5f5fae9 Luca Bigliardi
    """
850 b5f5fae9 Luca Bigliardi
    env = {"OP_TARGET": self.cfg.GetClusterName()}
851 b5f5fae9 Luca Bigliardi
    mn = self.cfg.GetMasterNode()
852 b5f5fae9 Luca Bigliardi
    return env, [], [mn]
853 b5f5fae9 Luca Bigliardi
854 b5f5fae9 Luca Bigliardi
  def CheckPrereq(self):
855 b5f5fae9 Luca Bigliardi
    """No prerequisites to check.
856 b5f5fae9 Luca Bigliardi

857 b5f5fae9 Luca Bigliardi
    """
858 b5f5fae9 Luca Bigliardi
    return True
859 b5f5fae9 Luca Bigliardi
860 b5f5fae9 Luca Bigliardi
  def Exec(self, feedback_fn):
861 b5f5fae9 Luca Bigliardi
    """Nothing to do.
862 b5f5fae9 Luca Bigliardi

863 b5f5fae9 Luca Bigliardi
    """
864 b5f5fae9 Luca Bigliardi
    return True
865 b5f5fae9 Luca Bigliardi
866 b5f5fae9 Luca Bigliardi
867 b2c750a4 Luca Bigliardi
class LUDestroyCluster(LogicalUnit):
868 a8083063 Iustin Pop
  """Logical unit for destroying the cluster.
869 a8083063 Iustin Pop

870 a8083063 Iustin Pop
  """
871 b2c750a4 Luca Bigliardi
  HPATH = "cluster-destroy"
872 b2c750a4 Luca Bigliardi
  HTYPE = constants.HTYPE_CLUSTER
873 a8083063 Iustin Pop
  _OP_REQP = []
874 a8083063 Iustin Pop
875 b2c750a4 Luca Bigliardi
  def BuildHooksEnv(self):
876 b2c750a4 Luca Bigliardi
    """Build hooks env.
877 b2c750a4 Luca Bigliardi

878 b2c750a4 Luca Bigliardi
    """
879 b2c750a4 Luca Bigliardi
    env = {"OP_TARGET": self.cfg.GetClusterName()}
880 b2c750a4 Luca Bigliardi
    return env, [], []
881 b2c750a4 Luca Bigliardi
882 a8083063 Iustin Pop
  def CheckPrereq(self):
883 a8083063 Iustin Pop
    """Check prerequisites.
884 a8083063 Iustin Pop

885 a8083063 Iustin Pop
    This checks whether the cluster is empty.
886 a8083063 Iustin Pop

887 5bbd3f7f Michael Hanselmann
    Any errors are signaled by raising errors.OpPrereqError.
888 a8083063 Iustin Pop

889 a8083063 Iustin Pop
    """
890 d6a02168 Michael Hanselmann
    master = self.cfg.GetMasterNode()
891 a8083063 Iustin Pop
892 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
893 db915bd1 Michael Hanselmann
    if len(nodelist) != 1 or nodelist[0] != master:
894 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d node(s) in"
895 5c983ee5 Iustin Pop
                                 " this cluster." % (len(nodelist) - 1),
896 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
897 db915bd1 Michael Hanselmann
    instancelist = self.cfg.GetInstanceList()
898 db915bd1 Michael Hanselmann
    if instancelist:
899 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d instance(s) in"
900 5c983ee5 Iustin Pop
                                 " this cluster." % len(instancelist),
901 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
902 a8083063 Iustin Pop
903 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
904 a8083063 Iustin Pop
    """Destroys the cluster.
905 a8083063 Iustin Pop

906 a8083063 Iustin Pop
    """
907 d6a02168 Michael Hanselmann
    master = self.cfg.GetMasterNode()
908 b989b9d9 Ken Wehr
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
909 3141ad3b Luca Bigliardi
910 3141ad3b Luca Bigliardi
    # Run post hooks on master node before it's removed
911 3141ad3b Luca Bigliardi
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
912 3141ad3b Luca Bigliardi
    try:
913 3141ad3b Luca Bigliardi
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
914 3141ad3b Luca Bigliardi
    except:
915 7260cfbe Iustin Pop
      # pylint: disable-msg=W0702
916 3141ad3b Luca Bigliardi
      self.LogWarning("Errors occurred running hooks on %s" % master)
917 3141ad3b Luca Bigliardi
918 781de953 Iustin Pop
    result = self.rpc.call_node_stop_master(master, False)
919 4c4e4e1e Iustin Pop
    result.Raise("Could not disable the master role")
920 b989b9d9 Ken Wehr
921 b989b9d9 Ken Wehr
    if modify_ssh_setup:
922 b989b9d9 Ken Wehr
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
923 b989b9d9 Ken Wehr
      utils.CreateBackup(priv_key)
924 b989b9d9 Ken Wehr
      utils.CreateBackup(pub_key)
925 b989b9d9 Ken Wehr
926 140aa4a8 Iustin Pop
    return master
927 a8083063 Iustin Pop
928 a8083063 Iustin Pop
929 d8fff41c Guido Trotter
class LUVerifyCluster(LogicalUnit):
930 a8083063 Iustin Pop
  """Verifies the cluster status.
931 a8083063 Iustin Pop

932 a8083063 Iustin Pop
  """
933 d8fff41c Guido Trotter
  HPATH = "cluster-verify"
934 d8fff41c Guido Trotter
  HTYPE = constants.HTYPE_CLUSTER
935 a0c9776a Iustin Pop
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
936 d4b9d97f Guido Trotter
  REQ_BGL = False
937 d4b9d97f Guido Trotter
938 7c874ee1 Iustin Pop
  TCLUSTER = "cluster"
939 7c874ee1 Iustin Pop
  TNODE = "node"
940 7c874ee1 Iustin Pop
  TINSTANCE = "instance"
941 7c874ee1 Iustin Pop
942 7c874ee1 Iustin Pop
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
943 7c874ee1 Iustin Pop
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
944 7c874ee1 Iustin Pop
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
945 7c874ee1 Iustin Pop
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
946 7c874ee1 Iustin Pop
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
947 7c874ee1 Iustin Pop
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
948 7c874ee1 Iustin Pop
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
949 7c874ee1 Iustin Pop
  ENODEDRBD = (TNODE, "ENODEDRBD")
950 7c874ee1 Iustin Pop
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
951 7c874ee1 Iustin Pop
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
952 7c874ee1 Iustin Pop
  ENODEHV = (TNODE, "ENODEHV")
953 7c874ee1 Iustin Pop
  ENODELVM = (TNODE, "ENODELVM")
954 7c874ee1 Iustin Pop
  ENODEN1 = (TNODE, "ENODEN1")
955 7c874ee1 Iustin Pop
  ENODENET = (TNODE, "ENODENET")
956 7c874ee1 Iustin Pop
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
957 7c874ee1 Iustin Pop
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
958 7c874ee1 Iustin Pop
  ENODERPC = (TNODE, "ENODERPC")
959 7c874ee1 Iustin Pop
  ENODESSH = (TNODE, "ENODESSH")
960 7c874ee1 Iustin Pop
  ENODEVERSION = (TNODE, "ENODEVERSION")
961 7c0aa8e9 Iustin Pop
  ENODESETUP = (TNODE, "ENODESETUP")
962 313b2dd4 Michael Hanselmann
  ENODETIME = (TNODE, "ENODETIME")
963 7c874ee1 Iustin Pop
964 a0c9776a Iustin Pop
  ETYPE_FIELD = "code"
965 a0c9776a Iustin Pop
  ETYPE_ERROR = "ERROR"
966 a0c9776a Iustin Pop
  ETYPE_WARNING = "WARNING"
967 a0c9776a Iustin Pop
968 d4b9d97f Guido Trotter
  def ExpandNames(self):
969 d4b9d97f Guido Trotter
    self.needed_locks = {
970 d4b9d97f Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
971 d4b9d97f Guido Trotter
      locking.LEVEL_INSTANCE: locking.ALL_SET,
972 d4b9d97f Guido Trotter
    }
973 c772d142 Michael Hanselmann
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
974 a8083063 Iustin Pop
975 7c874ee1 Iustin Pop
  def _Error(self, ecode, item, msg, *args, **kwargs):
976 7c874ee1 Iustin Pop
    """Format an error message.
977 7c874ee1 Iustin Pop

978 7c874ee1 Iustin Pop
    Based on the opcode's error_codes parameter, either format a
979 7c874ee1 Iustin Pop
    parseable error code, or a simpler error string.
980 7c874ee1 Iustin Pop

981 7c874ee1 Iustin Pop
    This must be called only from Exec and functions called from Exec.
982 7c874ee1 Iustin Pop

983 7c874ee1 Iustin Pop
    """
984 a0c9776a Iustin Pop
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
985 7c874ee1 Iustin Pop
    itype, etxt = ecode
986 7c874ee1 Iustin Pop
    # first complete the msg
987 7c874ee1 Iustin Pop
    if args:
988 7c874ee1 Iustin Pop
      msg = msg % args
989 7c874ee1 Iustin Pop
    # then format the whole message
990 7c874ee1 Iustin Pop
    if self.op.error_codes:
991 7c874ee1 Iustin Pop
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
992 7c874ee1 Iustin Pop
    else:
993 7c874ee1 Iustin Pop
      if item:
994 7c874ee1 Iustin Pop
        item = " " + item
995 7c874ee1 Iustin Pop
      else:
996 7c874ee1 Iustin Pop
        item = ""
997 7c874ee1 Iustin Pop
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
998 7c874ee1 Iustin Pop
    # and finally report it via the feedback_fn
999 7c874ee1 Iustin Pop
    self._feedback_fn("  - %s" % msg)
1000 7c874ee1 Iustin Pop
1001 a0c9776a Iustin Pop
  def _ErrorIf(self, cond, *args, **kwargs):
1002 a0c9776a Iustin Pop
    """Log an error message if the passed condition is True.
1003 a0c9776a Iustin Pop

1004 a0c9776a Iustin Pop
    """
1005 a0c9776a Iustin Pop
    cond = bool(cond) or self.op.debug_simulate_errors
1006 a0c9776a Iustin Pop
    if cond:
1007 a0c9776a Iustin Pop
      self._Error(*args, **kwargs)
1008 a0c9776a Iustin Pop
    # do not mark the operation as failed for WARN cases only
1009 a0c9776a Iustin Pop
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1010 a0c9776a Iustin Pop
      self.bad = self.bad or cond
1011 a0c9776a Iustin Pop
1012 25361b9a Iustin Pop
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
1013 7c874ee1 Iustin Pop
                  node_result, master_files, drbd_map, vg_name):
1014 a8083063 Iustin Pop
    """Run multiple tests against a node.
1015 a8083063 Iustin Pop

1016 112f18a5 Iustin Pop
    Test list:
1017 e4376078 Iustin Pop

1018 a8083063 Iustin Pop
      - compares ganeti version
1019 5bbd3f7f Michael Hanselmann
      - checks vg existence and size > 20G
1020 a8083063 Iustin Pop
      - checks config file checksum
1021 a8083063 Iustin Pop
      - checks ssh to other nodes
1022 a8083063 Iustin Pop

1023 112f18a5 Iustin Pop
    @type nodeinfo: L{objects.Node}
1024 112f18a5 Iustin Pop
    @param nodeinfo: the node to check
1025 e4376078 Iustin Pop
    @param file_list: required list of files
1026 e4376078 Iustin Pop
    @param local_cksum: dictionary of local files and their checksums
1027 e4376078 Iustin Pop
    @param node_result: the results from the node
1028 112f18a5 Iustin Pop
    @param master_files: list of files that only masters should have
1029 6d2e83d5 Iustin Pop
    @param drbd_map: the useddrbd minors for this node, in
1030 6d2e83d5 Iustin Pop
        form of minor: (instance, must_exist) which correspond to instances
1031 6d2e83d5 Iustin Pop
        and their running status
1032 cc9e1230 Guido Trotter
    @param vg_name: Ganeti Volume Group (result of self.cfg.GetVGName())
1033 098c0958 Michael Hanselmann

1034 a8083063 Iustin Pop
    """
1035 112f18a5 Iustin Pop
    node = nodeinfo.name
1036 7260cfbe Iustin Pop
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1037 25361b9a Iustin Pop
1038 25361b9a Iustin Pop
    # main result, node_result should be a non-empty dict
1039 a0c9776a Iustin Pop
    test = not node_result or not isinstance(node_result, dict)
1040 a0c9776a Iustin Pop
    _ErrorIf(test, self.ENODERPC, node,
1041 7c874ee1 Iustin Pop
                  "unable to verify node: no data returned")
1042 a0c9776a Iustin Pop
    if test:
1043 a0c9776a Iustin Pop
      return
1044 25361b9a Iustin Pop
1045 a8083063 Iustin Pop
    # compares ganeti version
1046 a8083063 Iustin Pop
    local_version = constants.PROTOCOL_VERSION
1047 25361b9a Iustin Pop
    remote_version = node_result.get('version', None)
1048 a0c9776a Iustin Pop
    test = not (remote_version and
1049 a0c9776a Iustin Pop
                isinstance(remote_version, (list, tuple)) and
1050 a0c9776a Iustin Pop
                len(remote_version) == 2)
1051 a0c9776a Iustin Pop
    _ErrorIf(test, self.ENODERPC, node,
1052 a0c9776a Iustin Pop
             "connection to node returned invalid data")
1053 a0c9776a Iustin Pop
    if test:
1054 a0c9776a Iustin Pop
      return
1055 a0c9776a Iustin Pop
1056 a0c9776a Iustin Pop
    test = local_version != remote_version[0]
1057 a0c9776a Iustin Pop
    _ErrorIf(test, self.ENODEVERSION, node,
1058 a0c9776a Iustin Pop
             "incompatible protocol versions: master %s,"
1059 a0c9776a Iustin Pop
             " node %s", local_version, remote_version[0])
1060 a0c9776a Iustin Pop
    if test:
1061 a0c9776a Iustin Pop
      return
1062 a8083063 Iustin Pop
1063 e9ce0a64 Iustin Pop
    # node seems compatible, we can actually try to look into its results
1064 a8083063 Iustin Pop
1065 e9ce0a64 Iustin Pop
    # full package version
1066 a0c9776a Iustin Pop
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1067 a0c9776a Iustin Pop
                  self.ENODEVERSION, node,
1068 7c874ee1 Iustin Pop
                  "software version mismatch: master %s, node %s",
1069 7c874ee1 Iustin Pop
                  constants.RELEASE_VERSION, remote_version[1],
1070 a0c9776a Iustin Pop
                  code=self.ETYPE_WARNING)
1071 e9ce0a64 Iustin Pop
1072 e9ce0a64 Iustin Pop
    # checks vg existence and size > 20G
1073 cc9e1230 Guido Trotter
    if vg_name is not None:
1074 cc9e1230 Guido Trotter
      vglist = node_result.get(constants.NV_VGLIST, None)
1075 a0c9776a Iustin Pop
      test = not vglist
1076 a0c9776a Iustin Pop
      _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1077 a0c9776a Iustin Pop
      if not test:
1078 cc9e1230 Guido Trotter
        vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1079 cc9e1230 Guido Trotter
                                              constants.MIN_VG_SIZE)
1080 a0c9776a Iustin Pop
        _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1081 a8083063 Iustin Pop
1082 a8083063 Iustin Pop
    # checks config file checksum
1083 a8083063 Iustin Pop
1084 25361b9a Iustin Pop
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
1085 a0c9776a Iustin Pop
    test = not isinstance(remote_cksum, dict)
1086 a0c9776a Iustin Pop
    _ErrorIf(test, self.ENODEFILECHECK, node,
1087 a0c9776a Iustin Pop
             "node hasn't returned file checksum data")
1088 a0c9776a Iustin Pop
    if not test:
1089 a8083063 Iustin Pop
      for file_name in file_list:
1090 112f18a5 Iustin Pop
        node_is_mc = nodeinfo.master_candidate
1091 a0c9776a Iustin Pop
        must_have = (file_name not in master_files) or node_is_mc
1092 a0c9776a Iustin Pop
        # missing
1093 a0c9776a Iustin Pop
        test1 = file_name not in remote_cksum
1094 a0c9776a Iustin Pop
        # invalid checksum
1095 a0c9776a Iustin Pop
        test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1096 a0c9776a Iustin Pop
        # existing and good
1097 a0c9776a Iustin Pop
        test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1098 a0c9776a Iustin Pop
        _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1099 a0c9776a Iustin Pop
                 "file '%s' missing", file_name)
1100 a0c9776a Iustin Pop
        _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1101 a0c9776a Iustin Pop
                 "file '%s' has wrong checksum", file_name)
1102 a0c9776a Iustin Pop
        # not candidate and this is not a must-have file
1103 a0c9776a Iustin Pop
        _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1104 a0c9776a Iustin Pop
                 "file '%s' should not exist on non master"
1105 a0c9776a Iustin Pop
                 " candidates (and the file is outdated)", file_name)
1106 a0c9776a Iustin Pop
        # all good, except non-master/non-must have combination
1107 a0c9776a Iustin Pop
        _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1108 a0c9776a Iustin Pop
                 "file '%s' should not exist"
1109 a0c9776a Iustin Pop
                 " on non master candidates", file_name)
1110 a8083063 Iustin Pop
1111 25361b9a Iustin Pop
    # checks ssh to any
1112 25361b9a Iustin Pop
1113 a0c9776a Iustin Pop
    test = constants.NV_NODELIST not in node_result
1114 a0c9776a Iustin Pop
    _ErrorIf(test, self.ENODESSH, node,
1115 a0c9776a Iustin Pop
             "node hasn't returned node ssh connectivity data")
1116 a0c9776a Iustin Pop
    if not test:
1117 25361b9a Iustin Pop
      if node_result[constants.NV_NODELIST]:
1118 7c874ee1 Iustin Pop
        for a_node, a_msg in node_result[constants.NV_NODELIST].items():
1119 a0c9776a Iustin Pop
          _ErrorIf(True, self.ENODESSH, node,
1120 a0c9776a Iustin Pop
                   "ssh communication with node '%s': %s", a_node, a_msg)
1121 25361b9a Iustin Pop
1122 a0c9776a Iustin Pop
    test = constants.NV_NODENETTEST not in node_result
1123 a0c9776a Iustin Pop
    _ErrorIf(test, self.ENODENET, node,
1124 a0c9776a Iustin Pop
             "node hasn't returned node tcp connectivity data")
1125 a0c9776a Iustin Pop
    if not test:
1126 25361b9a Iustin Pop
      if node_result[constants.NV_NODENETTEST]:
1127 25361b9a Iustin Pop
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
1128 7c874ee1 Iustin Pop
        for anode in nlist:
1129 a0c9776a Iustin Pop
          _ErrorIf(True, self.ENODENET, node,
1130 a0c9776a Iustin Pop
                   "tcp communication with node '%s': %s",
1131 a0c9776a Iustin Pop
                   anode, node_result[constants.NV_NODENETTEST][anode])
1132 9d4bfc96 Iustin Pop
1133 25361b9a Iustin Pop
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
1134 e69d05fd Iustin Pop
    if isinstance(hyp_result, dict):
1135 e69d05fd Iustin Pop
      for hv_name, hv_result in hyp_result.iteritems():
1136 a0c9776a Iustin Pop
        test = hv_result is not None
1137 a0c9776a Iustin Pop
        _ErrorIf(test, self.ENODEHV, node,
1138 a0c9776a Iustin Pop
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1139 6d2e83d5 Iustin Pop
1140 6d2e83d5 Iustin Pop
    # check used drbd list
1141 cc9e1230 Guido Trotter
    if vg_name is not None:
1142 cc9e1230 Guido Trotter
      used_minors = node_result.get(constants.NV_DRBDLIST, [])
1143 a0c9776a Iustin Pop
      test = not isinstance(used_minors, (tuple, list))
1144 a0c9776a Iustin Pop
      _ErrorIf(test, self.ENODEDRBD, node,
1145 a0c9776a Iustin Pop
               "cannot parse drbd status file: %s", str(used_minors))
1146 a0c9776a Iustin Pop
      if not test:
1147 cc9e1230 Guido Trotter
        for minor, (iname, must_exist) in drbd_map.items():
1148 a0c9776a Iustin Pop
          test = minor not in used_minors and must_exist
1149 a0c9776a Iustin Pop
          _ErrorIf(test, self.ENODEDRBD, node,
1150 a0c9776a Iustin Pop
                   "drbd minor %d of instance %s is not active",
1151 a0c9776a Iustin Pop
                   minor, iname)
1152 cc9e1230 Guido Trotter
        for minor in used_minors:
1153 a0c9776a Iustin Pop
          test = minor not in drbd_map
1154 a0c9776a Iustin Pop
          _ErrorIf(test, self.ENODEDRBD, node,
1155 a0c9776a Iustin Pop
                   "unallocated drbd minor %d is in use", minor)
1156 7c0aa8e9 Iustin Pop
    test = node_result.get(constants.NV_NODESETUP,
1157 7c0aa8e9 Iustin Pop
                           ["Missing NODESETUP results"])
1158 7c0aa8e9 Iustin Pop
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1159 7c0aa8e9 Iustin Pop
             "; ".join(test))
1160 a8083063 Iustin Pop
1161 d091393e Iustin Pop
    # check pv names
1162 d091393e Iustin Pop
    if vg_name is not None:
1163 d091393e Iustin Pop
      pvlist = node_result.get(constants.NV_PVLIST, None)
1164 d091393e Iustin Pop
      test = pvlist is None
1165 d091393e Iustin Pop
      _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1166 d091393e Iustin Pop
      if not test:
1167 d091393e Iustin Pop
        # check that ':' is not present in PV names, since it's a
1168 d091393e Iustin Pop
        # special character for lvcreate (denotes the range of PEs to
1169 d091393e Iustin Pop
        # use on the PV)
1170 1122eb25 Iustin Pop
        for _, pvname, owner_vg in pvlist:
1171 d091393e Iustin Pop
          test = ":" in pvname
1172 d091393e Iustin Pop
          _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1173 d091393e Iustin Pop
                   " '%s' of VG '%s'", pvname, owner_vg)
1174 d091393e Iustin Pop
1175 c5705f58 Guido Trotter
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
1176 7c874ee1 Iustin Pop
                      node_instance, n_offline):
1177 a8083063 Iustin Pop
    """Verify an instance.
1178 a8083063 Iustin Pop

1179 a8083063 Iustin Pop
    This function checks to see if the required block devices are
1180 a8083063 Iustin Pop
    available on the instance's node.
1181 a8083063 Iustin Pop

1182 a8083063 Iustin Pop
    """
1183 7260cfbe Iustin Pop
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1184 a8083063 Iustin Pop
    node_current = instanceconfig.primary_node
1185 a8083063 Iustin Pop
1186 a8083063 Iustin Pop
    node_vol_should = {}
1187 a8083063 Iustin Pop
    instanceconfig.MapLVsByNode(node_vol_should)
1188 a8083063 Iustin Pop
1189 a8083063 Iustin Pop
    for node in node_vol_should:
1190 0a66c968 Iustin Pop
      if node in n_offline:
1191 0a66c968 Iustin Pop
        # ignore missing volumes on offline nodes
1192 0a66c968 Iustin Pop
        continue
1193 a8083063 Iustin Pop
      for volume in node_vol_should[node]:
1194 a0c9776a Iustin Pop
        test = node not in node_vol_is or volume not in node_vol_is[node]
1195 a0c9776a Iustin Pop
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1196 a0c9776a Iustin Pop
                 "volume %s missing on node %s", volume, node)
1197 a8083063 Iustin Pop
1198 0d68c45d Iustin Pop
    if instanceconfig.admin_up:
1199 a0c9776a Iustin Pop
      test = ((node_current not in node_instance or
1200 a0c9776a Iustin Pop
               not instance in node_instance[node_current]) and
1201 a0c9776a Iustin Pop
              node_current not in n_offline)
1202 a0c9776a Iustin Pop
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1203 a0c9776a Iustin Pop
               "instance not running on its primary node %s",
1204 a0c9776a Iustin Pop
               node_current)
1205 a8083063 Iustin Pop
1206 a8083063 Iustin Pop
    for node in node_instance:
1207 a8083063 Iustin Pop
      if (not node == node_current):
1208 a0c9776a Iustin Pop
        test = instance in node_instance[node]
1209 a0c9776a Iustin Pop
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1210 a0c9776a Iustin Pop
                 "instance should not run on node %s", node)
1211 a8083063 Iustin Pop
1212 7c874ee1 Iustin Pop
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is):
1213 a8083063 Iustin Pop
    """Verify if there are any unknown volumes in the cluster.
1214 a8083063 Iustin Pop

1215 a8083063 Iustin Pop
    The .os, .swap and backup volumes are ignored. All other volumes are
1216 a8083063 Iustin Pop
    reported as unknown.
1217 a8083063 Iustin Pop

1218 a8083063 Iustin Pop
    """
1219 a8083063 Iustin Pop
    for node in node_vol_is:
1220 a8083063 Iustin Pop
      for volume in node_vol_is[node]:
1221 a0c9776a Iustin Pop
        test = (node not in node_vol_should or
1222 a0c9776a Iustin Pop
                volume not in node_vol_should[node])
1223 a0c9776a Iustin Pop
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1224 7c874ee1 Iustin Pop
                      "volume %s is unknown", volume)
1225 a8083063 Iustin Pop
1226 7c874ee1 Iustin Pop
  def _VerifyOrphanInstances(self, instancelist, node_instance):
1227 a8083063 Iustin Pop
    """Verify the list of running instances.
1228 a8083063 Iustin Pop

1229 a8083063 Iustin Pop
    This checks what instances are running but unknown to the cluster.
1230 a8083063 Iustin Pop

1231 a8083063 Iustin Pop
    """
1232 a8083063 Iustin Pop
    for node in node_instance:
1233 7c874ee1 Iustin Pop
      for o_inst in node_instance[node]:
1234 a0c9776a Iustin Pop
        test = o_inst not in instancelist
1235 a0c9776a Iustin Pop
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1236 7c874ee1 Iustin Pop
                      "instance %s on node %s should not exist", o_inst, node)
1237 a8083063 Iustin Pop
1238 7c874ee1 Iustin Pop
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg):
1239 2b3b6ddd Guido Trotter
    """Verify N+1 Memory Resilience.
1240 2b3b6ddd Guido Trotter

1241 2b3b6ddd Guido Trotter
    Check that if one single node dies we can still start all the instances it
1242 2b3b6ddd Guido Trotter
    was primary for.
1243 2b3b6ddd Guido Trotter

1244 2b3b6ddd Guido Trotter
    """
1245 2b3b6ddd Guido Trotter
    for node, nodeinfo in node_info.iteritems():
1246 2b3b6ddd Guido Trotter
      # This code checks that every node which is now listed as secondary has
1247 2b3b6ddd Guido Trotter
      # enough memory to host all instances it is supposed to should a single
1248 2b3b6ddd Guido Trotter
      # other node in the cluster fail.
1249 2b3b6ddd Guido Trotter
      # FIXME: not ready for failover to an arbitrary node
1250 2b3b6ddd Guido Trotter
      # FIXME: does not support file-backed instances
1251 2b3b6ddd Guido Trotter
      # WARNING: we currently take into account down instances as well as up
1252 2b3b6ddd Guido Trotter
      # ones, considering that even if they're down someone might want to start
1253 2b3b6ddd Guido Trotter
      # them even in the event of a node failure.
1254 2b3b6ddd Guido Trotter
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
1255 2b3b6ddd Guido Trotter
        needed_mem = 0
1256 2b3b6ddd Guido Trotter
        for instance in instances:
1257 338e51e8 Iustin Pop
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1258 c0f2b229 Iustin Pop
          if bep[constants.BE_AUTO_BALANCE]:
1259 3924700f Iustin Pop
            needed_mem += bep[constants.BE_MEMORY]
1260 a0c9776a Iustin Pop
        test = nodeinfo['mfree'] < needed_mem
1261 a0c9776a Iustin Pop
        self._ErrorIf(test, self.ENODEN1, node,
1262 7c874ee1 Iustin Pop
                      "not enough memory on to accommodate"
1263 7c874ee1 Iustin Pop
                      " failovers should peer node %s fail", prinode)
1264 2b3b6ddd Guido Trotter
1265 a8083063 Iustin Pop
  def CheckPrereq(self):
1266 a8083063 Iustin Pop
    """Check prerequisites.
1267 a8083063 Iustin Pop

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

1271 a8083063 Iustin Pop
    """
1272 e54c4c5e Guido Trotter
    self.skip_set = frozenset(self.op.skip_checks)
1273 e54c4c5e Guido Trotter
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1274 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1275 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
1276 a8083063 Iustin Pop
1277 d8fff41c Guido Trotter
  def BuildHooksEnv(self):
1278 d8fff41c Guido Trotter
    """Build hooks env.
1279 d8fff41c Guido Trotter

1280 5bbd3f7f Michael Hanselmann
    Cluster-Verify hooks just ran in the post phase and their failure makes
1281 d8fff41c Guido Trotter
    the output be logged in the verify output and the verification to fail.
1282 d8fff41c Guido Trotter

1283 d8fff41c Guido Trotter
    """
1284 d8fff41c Guido Trotter
    all_nodes = self.cfg.GetNodeList()
1285 35e994e9 Iustin Pop
    env = {
1286 35e994e9 Iustin Pop
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1287 35e994e9 Iustin Pop
      }
1288 35e994e9 Iustin Pop
    for node in self.cfg.GetAllNodesInfo().values():
1289 35e994e9 Iustin Pop
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1290 35e994e9 Iustin Pop
1291 d8fff41c Guido Trotter
    return env, [], all_nodes
1292 d8fff41c Guido Trotter
1293 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1294 a8083063 Iustin Pop
    """Verify integrity of cluster, performing various test on nodes.
1295 a8083063 Iustin Pop

1296 a8083063 Iustin Pop
    """
1297 a0c9776a Iustin Pop
    self.bad = False
1298 7260cfbe Iustin Pop
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1299 7c874ee1 Iustin Pop
    verbose = self.op.verbose
1300 7c874ee1 Iustin Pop
    self._feedback_fn = feedback_fn
1301 a8083063 Iustin Pop
    feedback_fn("* Verifying global settings")
1302 8522ceeb Iustin Pop
    for msg in self.cfg.VerifyConfig():
1303 a0c9776a Iustin Pop
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1304 a8083063 Iustin Pop
1305 a8083063 Iustin Pop
    vg_name = self.cfg.GetVGName()
1306 e69d05fd Iustin Pop
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1307 a8083063 Iustin Pop
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1308 9d4bfc96 Iustin Pop
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1309 a8083063 Iustin Pop
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1310 6d2e83d5 Iustin Pop
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1311 6d2e83d5 Iustin Pop
                        for iname in instancelist)
1312 93e4c50b Guido Trotter
    i_non_redundant = [] # Non redundant instances
1313 3924700f Iustin Pop
    i_non_a_balanced = [] # Non auto-balanced instances
1314 0a66c968 Iustin Pop
    n_offline = [] # List of offline nodes
1315 22f0f71d Iustin Pop
    n_drained = [] # List of nodes being drained
1316 a8083063 Iustin Pop
    node_volume = {}
1317 a8083063 Iustin Pop
    node_instance = {}
1318 9c9c7d30 Guido Trotter
    node_info = {}
1319 26b6af5e Guido Trotter
    instance_cfg = {}
1320 a8083063 Iustin Pop
1321 a8083063 Iustin Pop
    # FIXME: verify OS list
1322 a8083063 Iustin Pop
    # do local checksums
1323 112f18a5 Iustin Pop
    master_files = [constants.CLUSTER_CONF_FILE]
1324 112f18a5 Iustin Pop
1325 112f18a5 Iustin Pop
    file_names = ssconf.SimpleStore().GetFileList()
1326 cb91d46e Iustin Pop
    file_names.append(constants.SSL_CERT_FILE)
1327 699777f2 Michael Hanselmann
    file_names.append(constants.RAPI_CERT_FILE)
1328 112f18a5 Iustin Pop
    file_names.extend(master_files)
1329 112f18a5 Iustin Pop
1330 a8083063 Iustin Pop
    local_checksums = utils.FingerprintFiles(file_names)
1331 a8083063 Iustin Pop
1332 a8083063 Iustin Pop
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1333 a8083063 Iustin Pop
    node_verify_param = {
1334 25361b9a Iustin Pop
      constants.NV_FILELIST: file_names,
1335 82e37788 Iustin Pop
      constants.NV_NODELIST: [node.name for node in nodeinfo
1336 82e37788 Iustin Pop
                              if not node.offline],
1337 25361b9a Iustin Pop
      constants.NV_HYPERVISOR: hypervisors,
1338 25361b9a Iustin Pop
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1339 82e37788 Iustin Pop
                                  node.secondary_ip) for node in nodeinfo
1340 82e37788 Iustin Pop
                                 if not node.offline],
1341 25361b9a Iustin Pop
      constants.NV_INSTANCELIST: hypervisors,
1342 25361b9a Iustin Pop
      constants.NV_VERSION: None,
1343 25361b9a Iustin Pop
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1344 7c0aa8e9 Iustin Pop
      constants.NV_NODESETUP: None,
1345 313b2dd4 Michael Hanselmann
      constants.NV_TIME: None,
1346 a8083063 Iustin Pop
      }
1347 313b2dd4 Michael Hanselmann
1348 cc9e1230 Guido Trotter
    if vg_name is not None:
1349 cc9e1230 Guido Trotter
      node_verify_param[constants.NV_VGLIST] = None
1350 cc9e1230 Guido Trotter
      node_verify_param[constants.NV_LVLIST] = vg_name
1351 d091393e Iustin Pop
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1352 cc9e1230 Guido Trotter
      node_verify_param[constants.NV_DRBDLIST] = None
1353 313b2dd4 Michael Hanselmann
1354 313b2dd4 Michael Hanselmann
    # Due to the way our RPC system works, exact response times cannot be
1355 313b2dd4 Michael Hanselmann
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1356 313b2dd4 Michael Hanselmann
    # time before and after executing the request, we can at least have a time
1357 313b2dd4 Michael Hanselmann
    # window.
1358 313b2dd4 Michael Hanselmann
    nvinfo_starttime = time.time()
1359 72737a7f Iustin Pop
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1360 72737a7f Iustin Pop
                                           self.cfg.GetClusterName())
1361 313b2dd4 Michael Hanselmann
    nvinfo_endtime = time.time()
1362 a8083063 Iustin Pop
1363 3924700f Iustin Pop
    cluster = self.cfg.GetClusterInfo()
1364 112f18a5 Iustin Pop
    master_node = self.cfg.GetMasterNode()
1365 6d2e83d5 Iustin Pop
    all_drbd_map = self.cfg.ComputeDRBDMap()
1366 6d2e83d5 Iustin Pop
1367 7c874ee1 Iustin Pop
    feedback_fn("* Verifying node status")
1368 112f18a5 Iustin Pop
    for node_i in nodeinfo:
1369 112f18a5 Iustin Pop
      node = node_i.name
1370 25361b9a Iustin Pop
1371 0a66c968 Iustin Pop
      if node_i.offline:
1372 7c874ee1 Iustin Pop
        if verbose:
1373 7c874ee1 Iustin Pop
          feedback_fn("* Skipping offline node %s" % (node,))
1374 0a66c968 Iustin Pop
        n_offline.append(node)
1375 0a66c968 Iustin Pop
        continue
1376 0a66c968 Iustin Pop
1377 112f18a5 Iustin Pop
      if node == master_node:
1378 25361b9a Iustin Pop
        ntype = "master"
1379 112f18a5 Iustin Pop
      elif node_i.master_candidate:
1380 25361b9a Iustin Pop
        ntype = "master candidate"
1381 22f0f71d Iustin Pop
      elif node_i.drained:
1382 22f0f71d Iustin Pop
        ntype = "drained"
1383 22f0f71d Iustin Pop
        n_drained.append(node)
1384 112f18a5 Iustin Pop
      else:
1385 25361b9a Iustin Pop
        ntype = "regular"
1386 7c874ee1 Iustin Pop
      if verbose:
1387 7c874ee1 Iustin Pop
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1388 25361b9a Iustin Pop
1389 4c4e4e1e Iustin Pop
      msg = all_nvinfo[node].fail_msg
1390 a0c9776a Iustin Pop
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1391 6f68a739 Iustin Pop
      if msg:
1392 25361b9a Iustin Pop
        continue
1393 25361b9a Iustin Pop
1394 6f68a739 Iustin Pop
      nresult = all_nvinfo[node].payload
1395 6d2e83d5 Iustin Pop
      node_drbd = {}
1396 6d2e83d5 Iustin Pop
      for minor, instance in all_drbd_map[node].items():
1397 a0c9776a Iustin Pop
        test = instance not in instanceinfo
1398 a0c9776a Iustin Pop
        _ErrorIf(test, self.ECLUSTERCFG, None,
1399 a0c9776a Iustin Pop
                 "ghost instance '%s' in temporary DRBD map", instance)
1400 c614e5fb Iustin Pop
          # ghost instance should not be running, but otherwise we
1401 c614e5fb Iustin Pop
          # don't give double warnings (both ghost instance and
1402 c614e5fb Iustin Pop
          # unallocated minor in use)
1403 a0c9776a Iustin Pop
        if test:
1404 c614e5fb Iustin Pop
          node_drbd[minor] = (instance, False)
1405 c614e5fb Iustin Pop
        else:
1406 c614e5fb Iustin Pop
          instance = instanceinfo[instance]
1407 c614e5fb Iustin Pop
          node_drbd[minor] = (instance.name, instance.admin_up)
1408 313b2dd4 Michael Hanselmann
1409 a0c9776a Iustin Pop
      self._VerifyNode(node_i, file_names, local_checksums,
1410 a0c9776a Iustin Pop
                       nresult, master_files, node_drbd, vg_name)
1411 a8083063 Iustin Pop
1412 25361b9a Iustin Pop
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1413 cc9e1230 Guido Trotter
      if vg_name is None:
1414 cc9e1230 Guido Trotter
        node_volume[node] = {}
1415 cc9e1230 Guido Trotter
      elif isinstance(lvdata, basestring):
1416 a0c9776a Iustin Pop
        _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1417 a0c9776a Iustin Pop
                 utils.SafeEncode(lvdata))
1418 b63ed789 Iustin Pop
        node_volume[node] = {}
1419 25361b9a Iustin Pop
      elif not isinstance(lvdata, dict):
1420 a0c9776a Iustin Pop
        _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1421 a8083063 Iustin Pop
        continue
1422 b63ed789 Iustin Pop
      else:
1423 25361b9a Iustin Pop
        node_volume[node] = lvdata
1424 a8083063 Iustin Pop
1425 a8083063 Iustin Pop
      # node_instance
1426 25361b9a Iustin Pop
      idata = nresult.get(constants.NV_INSTANCELIST, None)
1427 a0c9776a Iustin Pop
      test = not isinstance(idata, list)
1428 a0c9776a Iustin Pop
      _ErrorIf(test, self.ENODEHV, node,
1429 a0c9776a Iustin Pop
               "rpc call to node failed (instancelist)")
1430 a0c9776a Iustin Pop
      if test:
1431 a8083063 Iustin Pop
        continue
1432 a8083063 Iustin Pop
1433 25361b9a Iustin Pop
      node_instance[node] = idata
1434 a8083063 Iustin Pop
1435 9c9c7d30 Guido Trotter
      # node_info
1436 25361b9a Iustin Pop
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
1437 a0c9776a Iustin Pop
      test = not isinstance(nodeinfo, dict)
1438 a0c9776a Iustin Pop
      _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1439 a0c9776a Iustin Pop
      if test:
1440 9c9c7d30 Guido Trotter
        continue
1441 9c9c7d30 Guido Trotter
1442 313b2dd4 Michael Hanselmann
      # Node time
1443 313b2dd4 Michael Hanselmann
      ntime = nresult.get(constants.NV_TIME, None)
1444 313b2dd4 Michael Hanselmann
      try:
1445 313b2dd4 Michael Hanselmann
        ntime_merged = utils.MergeTime(ntime)
1446 313b2dd4 Michael Hanselmann
      except (ValueError, TypeError):
1447 313b2dd4 Michael Hanselmann
        _ErrorIf(test, self.ENODETIME, node, "Node returned invalid time")
1448 313b2dd4 Michael Hanselmann
1449 313b2dd4 Michael Hanselmann
      if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1450 313b2dd4 Michael Hanselmann
        ntime_diff = abs(nvinfo_starttime - ntime_merged)
1451 313b2dd4 Michael Hanselmann
      elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1452 313b2dd4 Michael Hanselmann
        ntime_diff = abs(ntime_merged - nvinfo_endtime)
1453 313b2dd4 Michael Hanselmann
      else:
1454 313b2dd4 Michael Hanselmann
        ntime_diff = None
1455 313b2dd4 Michael Hanselmann
1456 313b2dd4 Michael Hanselmann
      _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1457 313b2dd4 Michael Hanselmann
               "Node time diverges by at least %0.1fs from master node time",
1458 313b2dd4 Michael Hanselmann
               ntime_diff)
1459 313b2dd4 Michael Hanselmann
1460 313b2dd4 Michael Hanselmann
      if ntime_diff is not None:
1461 313b2dd4 Michael Hanselmann
        continue
1462 313b2dd4 Michael Hanselmann
1463 9c9c7d30 Guido Trotter
      try:
1464 9c9c7d30 Guido Trotter
        node_info[node] = {
1465 9c9c7d30 Guido Trotter
          "mfree": int(nodeinfo['memory_free']),
1466 93e4c50b Guido Trotter
          "pinst": [],
1467 93e4c50b Guido Trotter
          "sinst": [],
1468 36e7da50 Guido Trotter
          # dictionary holding all instances this node is secondary for,
1469 36e7da50 Guido Trotter
          # grouped by their primary node. Each key is a cluster node, and each
1470 36e7da50 Guido Trotter
          # value is a list of instances which have the key as primary and the
1471 36e7da50 Guido Trotter
          # current node as secondary.  this is handy to calculate N+1 memory
1472 36e7da50 Guido Trotter
          # availability if you can only failover from a primary to its
1473 36e7da50 Guido Trotter
          # secondary.
1474 36e7da50 Guido Trotter
          "sinst-by-pnode": {},
1475 9c9c7d30 Guido Trotter
        }
1476 cc9e1230 Guido Trotter
        # FIXME: devise a free space model for file based instances as well
1477 cc9e1230 Guido Trotter
        if vg_name is not None:
1478 a0c9776a Iustin Pop
          test = (constants.NV_VGLIST not in nresult or
1479 a0c9776a Iustin Pop
                  vg_name not in nresult[constants.NV_VGLIST])
1480 a0c9776a Iustin Pop
          _ErrorIf(test, self.ENODELVM, node,
1481 a0c9776a Iustin Pop
                   "node didn't return data for the volume group '%s'"
1482 a0c9776a Iustin Pop
                   " - it is either missing or broken", vg_name)
1483 a0c9776a Iustin Pop
          if test:
1484 9a198532 Iustin Pop
            continue
1485 cc9e1230 Guido Trotter
          node_info[node]["dfree"] = int(nresult[constants.NV_VGLIST][vg_name])
1486 9a198532 Iustin Pop
      except (ValueError, KeyError):
1487 a0c9776a Iustin Pop
        _ErrorIf(True, self.ENODERPC, node,
1488 a0c9776a Iustin Pop
                 "node returned invalid nodeinfo, check lvm/hypervisor")
1489 9c9c7d30 Guido Trotter
        continue
1490 9c9c7d30 Guido Trotter
1491 a8083063 Iustin Pop
    node_vol_should = {}
1492 a8083063 Iustin Pop
1493 7c874ee1 Iustin Pop
    feedback_fn("* Verifying instance status")
1494 a8083063 Iustin Pop
    for instance in instancelist:
1495 7c874ee1 Iustin Pop
      if verbose:
1496 7c874ee1 Iustin Pop
        feedback_fn("* Verifying instance %s" % instance)
1497 6d2e83d5 Iustin Pop
      inst_config = instanceinfo[instance]
1498 a0c9776a Iustin Pop
      self._VerifyInstance(instance, inst_config, node_volume,
1499 a0c9776a Iustin Pop
                           node_instance, n_offline)
1500 832261fd Iustin Pop
      inst_nodes_offline = []
1501 a8083063 Iustin Pop
1502 a8083063 Iustin Pop
      inst_config.MapLVsByNode(node_vol_should)
1503 a8083063 Iustin Pop
1504 26b6af5e Guido Trotter
      instance_cfg[instance] = inst_config
1505 26b6af5e Guido Trotter
1506 93e4c50b Guido Trotter
      pnode = inst_config.primary_node
1507 a0c9776a Iustin Pop
      _ErrorIf(pnode not in node_info and pnode not in n_offline,
1508 a0c9776a Iustin Pop
               self.ENODERPC, pnode, "instance %s, connection to"
1509 a0c9776a Iustin Pop
               " primary node failed", instance)
1510 93e4c50b Guido Trotter
      if pnode in node_info:
1511 93e4c50b Guido Trotter
        node_info[pnode]['pinst'].append(instance)
1512 93e4c50b Guido Trotter
1513 832261fd Iustin Pop
      if pnode in n_offline:
1514 832261fd Iustin Pop
        inst_nodes_offline.append(pnode)
1515 832261fd Iustin Pop
1516 93e4c50b Guido Trotter
      # If the instance is non-redundant we cannot survive losing its primary
1517 93e4c50b Guido Trotter
      # node, so we are not N+1 compliant. On the other hand we have no disk
1518 93e4c50b Guido Trotter
      # templates with more than one secondary so that situation is not well
1519 93e4c50b Guido Trotter
      # supported either.
1520 93e4c50b Guido Trotter
      # FIXME: does not support file-backed instances
1521 93e4c50b Guido Trotter
      if len(inst_config.secondary_nodes) == 0:
1522 93e4c50b Guido Trotter
        i_non_redundant.append(instance)
1523 a0c9776a Iustin Pop
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
1524 a0c9776a Iustin Pop
               self.EINSTANCELAYOUT, instance,
1525 a0c9776a Iustin Pop
               "instance has multiple secondary nodes", code="WARNING")
1526 93e4c50b Guido Trotter
1527 c0f2b229 Iustin Pop
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1528 3924700f Iustin Pop
        i_non_a_balanced.append(instance)
1529 3924700f Iustin Pop
1530 93e4c50b Guido Trotter
      for snode in inst_config.secondary_nodes:
1531 a0c9776a Iustin Pop
        _ErrorIf(snode not in node_info and snode not in n_offline,
1532 a0c9776a Iustin Pop
                 self.ENODERPC, snode,
1533 a0c9776a Iustin Pop
                 "instance %s, connection to secondary node"
1534 a0c9776a Iustin Pop
                 "failed", instance)
1535 a0c9776a Iustin Pop
1536 93e4c50b Guido Trotter
        if snode in node_info:
1537 93e4c50b Guido Trotter
          node_info[snode]['sinst'].append(instance)
1538 36e7da50 Guido Trotter
          if pnode not in node_info[snode]['sinst-by-pnode']:
1539 36e7da50 Guido Trotter
            node_info[snode]['sinst-by-pnode'][pnode] = []
1540 36e7da50 Guido Trotter
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1541 a0c9776a Iustin Pop
1542 832261fd Iustin Pop
        if snode in n_offline:
1543 832261fd Iustin Pop
          inst_nodes_offline.append(snode)
1544 832261fd Iustin Pop
1545 a0c9776a Iustin Pop
      # warn that the instance lives on offline nodes
1546 a0c9776a Iustin Pop
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1547 a0c9776a Iustin Pop
               "instance lives on offline node(s) %s",
1548 1f864b60 Iustin Pop
               utils.CommaJoin(inst_nodes_offline))
1549 93e4c50b Guido Trotter
1550 a8083063 Iustin Pop
    feedback_fn("* Verifying orphan volumes")
1551 a0c9776a Iustin Pop
    self._VerifyOrphanVolumes(node_vol_should, node_volume)
1552 a8083063 Iustin Pop
1553 a8083063 Iustin Pop
    feedback_fn("* Verifying remaining instances")
1554 a0c9776a Iustin Pop
    self._VerifyOrphanInstances(instancelist, node_instance)
1555 a8083063 Iustin Pop
1556 e54c4c5e Guido Trotter
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1557 e54c4c5e Guido Trotter
      feedback_fn("* Verifying N+1 Memory redundancy")
1558 a0c9776a Iustin Pop
      self._VerifyNPlusOneMemory(node_info, instance_cfg)
1559 2b3b6ddd Guido Trotter
1560 2b3b6ddd Guido Trotter
    feedback_fn("* Other Notes")
1561 2b3b6ddd Guido Trotter
    if i_non_redundant:
1562 2b3b6ddd Guido Trotter
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1563 2b3b6ddd Guido Trotter
                  % len(i_non_redundant))
1564 2b3b6ddd Guido Trotter
1565 3924700f Iustin Pop
    if i_non_a_balanced:
1566 3924700f Iustin Pop
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1567 3924700f Iustin Pop
                  % len(i_non_a_balanced))
1568 3924700f Iustin Pop
1569 0a66c968 Iustin Pop
    if n_offline:
1570 0a66c968 Iustin Pop
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1571 0a66c968 Iustin Pop
1572 22f0f71d Iustin Pop
    if n_drained:
1573 22f0f71d Iustin Pop
      feedback_fn("  - NOTICE: %d drained node(s) found." % len(n_drained))
1574 22f0f71d Iustin Pop
1575 a0c9776a Iustin Pop
    return not self.bad
1576 a8083063 Iustin Pop
1577 d8fff41c Guido Trotter
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1578 5bbd3f7f Michael Hanselmann
    """Analyze the post-hooks' result
1579 e4376078 Iustin Pop

1580 e4376078 Iustin Pop
    This method analyses the hook result, handles it, and sends some
1581 d8fff41c Guido Trotter
    nicely-formatted feedback back to the user.
1582 d8fff41c Guido Trotter

1583 e4376078 Iustin Pop
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1584 e4376078 Iustin Pop
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1585 e4376078 Iustin Pop
    @param hooks_results: the results of the multi-node hooks rpc call
1586 e4376078 Iustin Pop
    @param feedback_fn: function used send feedback back to the caller
1587 e4376078 Iustin Pop
    @param lu_result: previous Exec result
1588 e4376078 Iustin Pop
    @return: the new Exec result, based on the previous result
1589 e4376078 Iustin Pop
        and hook results
1590 d8fff41c Guido Trotter

1591 d8fff41c Guido Trotter
    """
1592 38206f3c Iustin Pop
    # We only really run POST phase hooks, and are only interested in
1593 38206f3c Iustin Pop
    # their results
1594 d8fff41c Guido Trotter
    if phase == constants.HOOKS_PHASE_POST:
1595 d8fff41c Guido Trotter
      # Used to change hooks' output to proper indentation
1596 d8fff41c Guido Trotter
      indent_re = re.compile('^', re.M)
1597 d8fff41c Guido Trotter
      feedback_fn("* Hooks Results")
1598 7c874ee1 Iustin Pop
      assert hooks_results, "invalid result from hooks"
1599 7c874ee1 Iustin Pop
1600 7c874ee1 Iustin Pop
      for node_name in hooks_results:
1601 7c874ee1 Iustin Pop
        res = hooks_results[node_name]
1602 7c874ee1 Iustin Pop
        msg = res.fail_msg
1603 a0c9776a Iustin Pop
        test = msg and not res.offline
1604 a0c9776a Iustin Pop
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1605 7c874ee1 Iustin Pop
                      "Communication failure in hooks execution: %s", msg)
1606 a0c9776a Iustin Pop
        if test:
1607 a0c9776a Iustin Pop
          # override manually lu_result here as _ErrorIf only
1608 a0c9776a Iustin Pop
          # overrides self.bad
1609 7c874ee1 Iustin Pop
          lu_result = 1
1610 7c874ee1 Iustin Pop
          continue
1611 7c874ee1 Iustin Pop
        for script, hkr, output in res.payload:
1612 a0c9776a Iustin Pop
          test = hkr == constants.HKR_FAIL
1613 a0c9776a Iustin Pop
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1614 7c874ee1 Iustin Pop
                        "Script %s failed, output:", script)
1615 a0c9776a Iustin Pop
          if test:
1616 7c874ee1 Iustin Pop
            output = indent_re.sub('      ', output)
1617 7c874ee1 Iustin Pop
            feedback_fn("%s" % output)
1618 7c874ee1 Iustin Pop
            lu_result = 1
1619 d8fff41c Guido Trotter
1620 d8fff41c Guido Trotter
      return lu_result
1621 d8fff41c Guido Trotter
1622 a8083063 Iustin Pop
1623 2c95a8d4 Iustin Pop
class LUVerifyDisks(NoHooksLU):
1624 2c95a8d4 Iustin Pop
  """Verifies the cluster disks status.
1625 2c95a8d4 Iustin Pop

1626 2c95a8d4 Iustin Pop
  """
1627 2c95a8d4 Iustin Pop
  _OP_REQP = []
1628 d4b9d97f Guido Trotter
  REQ_BGL = False
1629 d4b9d97f Guido Trotter
1630 d4b9d97f Guido Trotter
  def ExpandNames(self):
1631 d4b9d97f Guido Trotter
    self.needed_locks = {
1632 d4b9d97f Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
1633 d4b9d97f Guido Trotter
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1634 d4b9d97f Guido Trotter
    }
1635 c772d142 Michael Hanselmann
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1636 2c95a8d4 Iustin Pop
1637 2c95a8d4 Iustin Pop
  def CheckPrereq(self):
1638 2c95a8d4 Iustin Pop
    """Check prerequisites.
1639 2c95a8d4 Iustin Pop

1640 2c95a8d4 Iustin Pop
    This has no prerequisites.
1641 2c95a8d4 Iustin Pop

1642 2c95a8d4 Iustin Pop
    """
1643 2c95a8d4 Iustin Pop
    pass
1644 2c95a8d4 Iustin Pop
1645 2c95a8d4 Iustin Pop
  def Exec(self, feedback_fn):
1646 2c95a8d4 Iustin Pop
    """Verify integrity of cluster disks.
1647 2c95a8d4 Iustin Pop

1648 29d376ec Iustin Pop
    @rtype: tuple of three items
1649 29d376ec Iustin Pop
    @return: a tuple of (dict of node-to-node_error, list of instances
1650 29d376ec Iustin Pop
        which need activate-disks, dict of instance: (node, volume) for
1651 29d376ec Iustin Pop
        missing volumes
1652 29d376ec Iustin Pop

1653 2c95a8d4 Iustin Pop
    """
1654 29d376ec Iustin Pop
    result = res_nodes, res_instances, res_missing = {}, [], {}
1655 2c95a8d4 Iustin Pop
1656 2c95a8d4 Iustin Pop
    vg_name = self.cfg.GetVGName()
1657 2c95a8d4 Iustin Pop
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1658 2c95a8d4 Iustin Pop
    instances = [self.cfg.GetInstanceInfo(name)
1659 2c95a8d4 Iustin Pop
                 for name in self.cfg.GetInstanceList()]
1660 2c95a8d4 Iustin Pop
1661 2c95a8d4 Iustin Pop
    nv_dict = {}
1662 2c95a8d4 Iustin Pop
    for inst in instances:
1663 2c95a8d4 Iustin Pop
      inst_lvs = {}
1664 0d68c45d Iustin Pop
      if (not inst.admin_up or
1665 2c95a8d4 Iustin Pop
          inst.disk_template not in constants.DTS_NET_MIRROR):
1666 2c95a8d4 Iustin Pop
        continue
1667 2c95a8d4 Iustin Pop
      inst.MapLVsByNode(inst_lvs)
1668 2c95a8d4 Iustin Pop
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1669 2c95a8d4 Iustin Pop
      for node, vol_list in inst_lvs.iteritems():
1670 2c95a8d4 Iustin Pop
        for vol in vol_list:
1671 2c95a8d4 Iustin Pop
          nv_dict[(node, vol)] = inst
1672 2c95a8d4 Iustin Pop
1673 2c95a8d4 Iustin Pop
    if not nv_dict:
1674 2c95a8d4 Iustin Pop
      return result
1675 2c95a8d4 Iustin Pop
1676 b2a6ccd4 Iustin Pop
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1677 2c95a8d4 Iustin Pop
1678 2c95a8d4 Iustin Pop
    for node in nodes:
1679 2c95a8d4 Iustin Pop
      # node_volume
1680 29d376ec Iustin Pop
      node_res = node_lvs[node]
1681 29d376ec Iustin Pop
      if node_res.offline:
1682 ea9ddc07 Iustin Pop
        continue
1683 4c4e4e1e Iustin Pop
      msg = node_res.fail_msg
1684 29d376ec Iustin Pop
      if msg:
1685 29d376ec Iustin Pop
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1686 29d376ec Iustin Pop
        res_nodes[node] = msg
1687 2c95a8d4 Iustin Pop
        continue
1688 2c95a8d4 Iustin Pop
1689 29d376ec Iustin Pop
      lvs = node_res.payload
1690 1122eb25 Iustin Pop
      for lv_name, (_, _, lv_online) in lvs.items():
1691 b63ed789 Iustin Pop
        inst = nv_dict.pop((node, lv_name), None)
1692 b63ed789 Iustin Pop
        if (not lv_online and inst is not None
1693 b63ed789 Iustin Pop
            and inst.name not in res_instances):
1694 b08d5a87 Iustin Pop
          res_instances.append(inst.name)
1695 2c95a8d4 Iustin Pop
1696 b63ed789 Iustin Pop
    # any leftover items in nv_dict are missing LVs, let's arrange the
1697 b63ed789 Iustin Pop
    # data better
1698 b63ed789 Iustin Pop
    for key, inst in nv_dict.iteritems():
1699 b63ed789 Iustin Pop
      if inst.name not in res_missing:
1700 b63ed789 Iustin Pop
        res_missing[inst.name] = []
1701 b63ed789 Iustin Pop
      res_missing[inst.name].append(key)
1702 b63ed789 Iustin Pop
1703 2c95a8d4 Iustin Pop
    return result
1704 2c95a8d4 Iustin Pop
1705 2c95a8d4 Iustin Pop
1706 60975797 Iustin Pop
class LURepairDiskSizes(NoHooksLU):
1707 60975797 Iustin Pop
  """Verifies the cluster disks sizes.
1708 60975797 Iustin Pop

1709 60975797 Iustin Pop
  """
1710 60975797 Iustin Pop
  _OP_REQP = ["instances"]
1711 60975797 Iustin Pop
  REQ_BGL = False
1712 60975797 Iustin Pop
1713 60975797 Iustin Pop
  def ExpandNames(self):
1714 60975797 Iustin Pop
    if not isinstance(self.op.instances, list):
1715 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid argument type 'instances'",
1716 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
1717 60975797 Iustin Pop
1718 60975797 Iustin Pop
    if self.op.instances:
1719 60975797 Iustin Pop
      self.wanted_names = []
1720 60975797 Iustin Pop
      for name in self.op.instances:
1721 60975797 Iustin Pop
        full_name = self.cfg.ExpandInstanceName(name)
1722 60975797 Iustin Pop
        if full_name is None:
1723 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Instance '%s' not known" % name,
1724 5c983ee5 Iustin Pop
                                     errors.ECODE_NOENT)
1725 60975797 Iustin Pop
        self.wanted_names.append(full_name)
1726 60975797 Iustin Pop
      self.needed_locks = {
1727 60975797 Iustin Pop
        locking.LEVEL_NODE: [],
1728 60975797 Iustin Pop
        locking.LEVEL_INSTANCE: self.wanted_names,
1729 60975797 Iustin Pop
        }
1730 60975797 Iustin Pop
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1731 60975797 Iustin Pop
    else:
1732 60975797 Iustin Pop
      self.wanted_names = None
1733 60975797 Iustin Pop
      self.needed_locks = {
1734 60975797 Iustin Pop
        locking.LEVEL_NODE: locking.ALL_SET,
1735 60975797 Iustin Pop
        locking.LEVEL_INSTANCE: locking.ALL_SET,
1736 60975797 Iustin Pop
        }
1737 60975797 Iustin Pop
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1738 60975797 Iustin Pop
1739 60975797 Iustin Pop
  def DeclareLocks(self, level):
1740 60975797 Iustin Pop
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
1741 60975797 Iustin Pop
      self._LockInstancesNodes(primary_only=True)
1742 60975797 Iustin Pop
1743 60975797 Iustin Pop
  def CheckPrereq(self):
1744 60975797 Iustin Pop
    """Check prerequisites.
1745 60975797 Iustin Pop

1746 60975797 Iustin Pop
    This only checks the optional instance list against the existing names.
1747 60975797 Iustin Pop

1748 60975797 Iustin Pop
    """
1749 60975797 Iustin Pop
    if self.wanted_names is None:
1750 60975797 Iustin Pop
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
1751 60975797 Iustin Pop
1752 60975797 Iustin Pop
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
1753 60975797 Iustin Pop
                             in self.wanted_names]
1754 60975797 Iustin Pop
1755 b775c337 Iustin Pop
  def _EnsureChildSizes(self, disk):
1756 b775c337 Iustin Pop
    """Ensure children of the disk have the needed disk size.
1757 b775c337 Iustin Pop

1758 b775c337 Iustin Pop
    This is valid mainly for DRBD8 and fixes an issue where the
1759 b775c337 Iustin Pop
    children have smaller disk size.
1760 b775c337 Iustin Pop

1761 b775c337 Iustin Pop
    @param disk: an L{ganeti.objects.Disk} object
1762 b775c337 Iustin Pop

1763 b775c337 Iustin Pop
    """
1764 b775c337 Iustin Pop
    if disk.dev_type == constants.LD_DRBD8:
1765 b775c337 Iustin Pop
      assert disk.children, "Empty children for DRBD8?"
1766 b775c337 Iustin Pop
      fchild = disk.children[0]
1767 b775c337 Iustin Pop
      mismatch = fchild.size < disk.size
1768 b775c337 Iustin Pop
      if mismatch:
1769 b775c337 Iustin Pop
        self.LogInfo("Child disk has size %d, parent %d, fixing",
1770 b775c337 Iustin Pop
                     fchild.size, disk.size)
1771 b775c337 Iustin Pop
        fchild.size = disk.size
1772 b775c337 Iustin Pop
1773 b775c337 Iustin Pop
      # and we recurse on this child only, not on the metadev
1774 b775c337 Iustin Pop
      return self._EnsureChildSizes(fchild) or mismatch
1775 b775c337 Iustin Pop
    else:
1776 b775c337 Iustin Pop
      return False
1777 b775c337 Iustin Pop
1778 60975797 Iustin Pop
  def Exec(self, feedback_fn):
1779 60975797 Iustin Pop
    """Verify the size of cluster disks.
1780 60975797 Iustin Pop

1781 60975797 Iustin Pop
    """
1782 60975797 Iustin Pop
    # TODO: check child disks too
1783 60975797 Iustin Pop
    # TODO: check differences in size between primary/secondary nodes
1784 60975797 Iustin Pop
    per_node_disks = {}
1785 60975797 Iustin Pop
    for instance in self.wanted_instances:
1786 60975797 Iustin Pop
      pnode = instance.primary_node
1787 60975797 Iustin Pop
      if pnode not in per_node_disks:
1788 60975797 Iustin Pop
        per_node_disks[pnode] = []
1789 60975797 Iustin Pop
      for idx, disk in enumerate(instance.disks):
1790 60975797 Iustin Pop
        per_node_disks[pnode].append((instance, idx, disk))
1791 60975797 Iustin Pop
1792 60975797 Iustin Pop
    changed = []
1793 60975797 Iustin Pop
    for node, dskl in per_node_disks.items():
1794 4d9e6835 Iustin Pop
      newl = [v[2].Copy() for v in dskl]
1795 4d9e6835 Iustin Pop
      for dsk in newl:
1796 4d9e6835 Iustin Pop
        self.cfg.SetDiskID(dsk, node)
1797 4d9e6835 Iustin Pop
      result = self.rpc.call_blockdev_getsizes(node, newl)
1798 3cebe102 Michael Hanselmann
      if result.fail_msg:
1799 60975797 Iustin Pop
        self.LogWarning("Failure in blockdev_getsizes call to node"
1800 60975797 Iustin Pop
                        " %s, ignoring", node)
1801 60975797 Iustin Pop
        continue
1802 60975797 Iustin Pop
      if len(result.data) != len(dskl):
1803 60975797 Iustin Pop
        self.LogWarning("Invalid result from node %s, ignoring node results",
1804 60975797 Iustin Pop
                        node)
1805 60975797 Iustin Pop
        continue
1806 60975797 Iustin Pop
      for ((instance, idx, disk), size) in zip(dskl, result.data):
1807 60975797 Iustin Pop
        if size is None:
1808 60975797 Iustin Pop
          self.LogWarning("Disk %d of instance %s did not return size"
1809 60975797 Iustin Pop
                          " information, ignoring", idx, instance.name)
1810 60975797 Iustin Pop
          continue
1811 60975797 Iustin Pop
        if not isinstance(size, (int, long)):
1812 60975797 Iustin Pop
          self.LogWarning("Disk %d of instance %s did not return valid"
1813 60975797 Iustin Pop
                          " size information, ignoring", idx, instance.name)
1814 60975797 Iustin Pop
          continue
1815 60975797 Iustin Pop
        size = size >> 20
1816 60975797 Iustin Pop
        if size != disk.size:
1817 60975797 Iustin Pop
          self.LogInfo("Disk %d of instance %s has mismatched size,"
1818 60975797 Iustin Pop
                       " correcting: recorded %d, actual %d", idx,
1819 60975797 Iustin Pop
                       instance.name, disk.size, size)
1820 60975797 Iustin Pop
          disk.size = size
1821 a4eae71f Michael Hanselmann
          self.cfg.Update(instance, feedback_fn)
1822 60975797 Iustin Pop
          changed.append((instance.name, idx, size))
1823 b775c337 Iustin Pop
        if self._EnsureChildSizes(disk):
1824 a4eae71f Michael Hanselmann
          self.cfg.Update(instance, feedback_fn)
1825 b775c337 Iustin Pop
          changed.append((instance.name, idx, disk.size))
1826 60975797 Iustin Pop
    return changed
1827 60975797 Iustin Pop
1828 60975797 Iustin Pop
1829 07bd8a51 Iustin Pop
class LURenameCluster(LogicalUnit):
1830 07bd8a51 Iustin Pop
  """Rename the cluster.
1831 07bd8a51 Iustin Pop

1832 07bd8a51 Iustin Pop
  """
1833 07bd8a51 Iustin Pop
  HPATH = "cluster-rename"
1834 07bd8a51 Iustin Pop
  HTYPE = constants.HTYPE_CLUSTER
1835 07bd8a51 Iustin Pop
  _OP_REQP = ["name"]
1836 07bd8a51 Iustin Pop
1837 07bd8a51 Iustin Pop
  def BuildHooksEnv(self):
1838 07bd8a51 Iustin Pop
    """Build hooks env.
1839 07bd8a51 Iustin Pop

1840 07bd8a51 Iustin Pop
    """
1841 07bd8a51 Iustin Pop
    env = {
1842 d6a02168 Michael Hanselmann
      "OP_TARGET": self.cfg.GetClusterName(),
1843 07bd8a51 Iustin Pop
      "NEW_NAME": self.op.name,
1844 07bd8a51 Iustin Pop
      }
1845 d6a02168 Michael Hanselmann
    mn = self.cfg.GetMasterNode()
1846 47a72f18 Iustin Pop
    all_nodes = self.cfg.GetNodeList()
1847 47a72f18 Iustin Pop
    return env, [mn], all_nodes
1848 07bd8a51 Iustin Pop
1849 07bd8a51 Iustin Pop
  def CheckPrereq(self):
1850 07bd8a51 Iustin Pop
    """Verify that the passed name is a valid one.
1851 07bd8a51 Iustin Pop

1852 07bd8a51 Iustin Pop
    """
1853 104f4ca1 Iustin Pop
    hostname = utils.GetHostInfo(self.op.name)
1854 07bd8a51 Iustin Pop
1855 bcf043c9 Iustin Pop
    new_name = hostname.name
1856 bcf043c9 Iustin Pop
    self.ip = new_ip = hostname.ip
1857 d6a02168 Michael Hanselmann
    old_name = self.cfg.GetClusterName()
1858 d6a02168 Michael Hanselmann
    old_ip = self.cfg.GetMasterIP()
1859 07bd8a51 Iustin Pop
    if new_name == old_name and new_ip == old_ip:
1860 07bd8a51 Iustin Pop
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1861 5c983ee5 Iustin Pop
                                 " cluster has changed",
1862 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
1863 07bd8a51 Iustin Pop
    if new_ip != old_ip:
1864 937f983d Guido Trotter
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1865 07bd8a51 Iustin Pop
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1866 07bd8a51 Iustin Pop
                                   " reachable on the network. Aborting." %
1867 5c983ee5 Iustin Pop
                                   new_ip, errors.ECODE_NOTUNIQUE)
1868 07bd8a51 Iustin Pop
1869 07bd8a51 Iustin Pop
    self.op.name = new_name
1870 07bd8a51 Iustin Pop
1871 07bd8a51 Iustin Pop
  def Exec(self, feedback_fn):
1872 07bd8a51 Iustin Pop
    """Rename the cluster.
1873 07bd8a51 Iustin Pop

1874 07bd8a51 Iustin Pop
    """
1875 07bd8a51 Iustin Pop
    clustername = self.op.name
1876 07bd8a51 Iustin Pop
    ip = self.ip
1877 07bd8a51 Iustin Pop
1878 07bd8a51 Iustin Pop
    # shutdown the master IP
1879 d6a02168 Michael Hanselmann
    master = self.cfg.GetMasterNode()
1880 781de953 Iustin Pop
    result = self.rpc.call_node_stop_master(master, False)
1881 4c4e4e1e Iustin Pop
    result.Raise("Could not disable the master role")
1882 07bd8a51 Iustin Pop
1883 07bd8a51 Iustin Pop
    try:
1884 55cf7d83 Iustin Pop
      cluster = self.cfg.GetClusterInfo()
1885 55cf7d83 Iustin Pop
      cluster.cluster_name = clustername
1886 55cf7d83 Iustin Pop
      cluster.master_ip = ip
1887 a4eae71f Michael Hanselmann
      self.cfg.Update(cluster, feedback_fn)
1888 ec85e3d5 Iustin Pop
1889 ec85e3d5 Iustin Pop
      # update the known hosts file
1890 ec85e3d5 Iustin Pop
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1891 ec85e3d5 Iustin Pop
      node_list = self.cfg.GetNodeList()
1892 ec85e3d5 Iustin Pop
      try:
1893 ec85e3d5 Iustin Pop
        node_list.remove(master)
1894 ec85e3d5 Iustin Pop
      except ValueError:
1895 ec85e3d5 Iustin Pop
        pass
1896 ec85e3d5 Iustin Pop
      result = self.rpc.call_upload_file(node_list,
1897 ec85e3d5 Iustin Pop
                                         constants.SSH_KNOWN_HOSTS_FILE)
1898 ec85e3d5 Iustin Pop
      for to_node, to_result in result.iteritems():
1899 6f7d4e75 Iustin Pop
        msg = to_result.fail_msg
1900 6f7d4e75 Iustin Pop
        if msg:
1901 6f7d4e75 Iustin Pop
          msg = ("Copy of file %s to node %s failed: %s" %
1902 6f7d4e75 Iustin Pop
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
1903 6f7d4e75 Iustin Pop
          self.proc.LogWarning(msg)
1904 ec85e3d5 Iustin Pop
1905 07bd8a51 Iustin Pop
    finally:
1906 3583908a Guido Trotter
      result = self.rpc.call_node_start_master(master, False, False)
1907 4c4e4e1e Iustin Pop
      msg = result.fail_msg
1908 b726aff0 Iustin Pop
      if msg:
1909 86d9d3bb Iustin Pop
        self.LogWarning("Could not re-enable the master role on"
1910 b726aff0 Iustin Pop
                        " the master, please restart manually: %s", msg)
1911 07bd8a51 Iustin Pop
1912 07bd8a51 Iustin Pop
1913 8084f9f6 Manuel Franceschini
def _RecursiveCheckIfLVMBased(disk):
1914 8084f9f6 Manuel Franceschini
  """Check if the given disk or its children are lvm-based.
1915 8084f9f6 Manuel Franceschini

1916 e4376078 Iustin Pop
  @type disk: L{objects.Disk}
1917 e4376078 Iustin Pop
  @param disk: the disk to check
1918 5bbd3f7f Michael Hanselmann
  @rtype: boolean
1919 e4376078 Iustin Pop
  @return: boolean indicating whether a LD_LV dev_type was found or not
1920 8084f9f6 Manuel Franceschini

1921 8084f9f6 Manuel Franceschini
  """
1922 8084f9f6 Manuel Franceschini
  if disk.children:
1923 8084f9f6 Manuel Franceschini
    for chdisk in disk.children:
1924 8084f9f6 Manuel Franceschini
      if _RecursiveCheckIfLVMBased(chdisk):
1925 8084f9f6 Manuel Franceschini
        return True
1926 8084f9f6 Manuel Franceschini
  return disk.dev_type == constants.LD_LV
1927 8084f9f6 Manuel Franceschini
1928 8084f9f6 Manuel Franceschini
1929 8084f9f6 Manuel Franceschini
class LUSetClusterParams(LogicalUnit):
1930 8084f9f6 Manuel Franceschini
  """Change the parameters of the cluster.
1931 8084f9f6 Manuel Franceschini

1932 8084f9f6 Manuel Franceschini
  """
1933 8084f9f6 Manuel Franceschini
  HPATH = "cluster-modify"
1934 8084f9f6 Manuel Franceschini
  HTYPE = constants.HTYPE_CLUSTER
1935 8084f9f6 Manuel Franceschini
  _OP_REQP = []
1936 c53279cf Guido Trotter
  REQ_BGL = False
1937 c53279cf Guido Trotter
1938 3994f455 Iustin Pop
  def CheckArguments(self):
1939 4b7735f9 Iustin Pop
    """Check parameters
1940 4b7735f9 Iustin Pop

1941 4b7735f9 Iustin Pop
    """
1942 4b7735f9 Iustin Pop
    if not hasattr(self.op, "candidate_pool_size"):
1943 4b7735f9 Iustin Pop
      self.op.candidate_pool_size = None
1944 4b7735f9 Iustin Pop
    if self.op.candidate_pool_size is not None:
1945 4b7735f9 Iustin Pop
      try:
1946 4b7735f9 Iustin Pop
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1947 3994f455 Iustin Pop
      except (ValueError, TypeError), err:
1948 4b7735f9 Iustin Pop
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1949 5c983ee5 Iustin Pop
                                   str(err), errors.ECODE_INVAL)
1950 4b7735f9 Iustin Pop
      if self.op.candidate_pool_size < 1:
1951 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("At least one master candidate needed",
1952 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
1953 4b7735f9 Iustin Pop
1954 c53279cf Guido Trotter
  def ExpandNames(self):
1955 c53279cf Guido Trotter
    # FIXME: in the future maybe other cluster params won't require checking on
1956 c53279cf Guido Trotter
    # all nodes to be modified.
1957 c53279cf Guido Trotter
    self.needed_locks = {
1958 c53279cf Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
1959 c53279cf Guido Trotter
    }
1960 c53279cf Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1961 8084f9f6 Manuel Franceschini
1962 8084f9f6 Manuel Franceschini
  def BuildHooksEnv(self):
1963 8084f9f6 Manuel Franceschini
    """Build hooks env.
1964 8084f9f6 Manuel Franceschini

1965 8084f9f6 Manuel Franceschini
    """
1966 8084f9f6 Manuel Franceschini
    env = {
1967 d6a02168 Michael Hanselmann
      "OP_TARGET": self.cfg.GetClusterName(),
1968 8084f9f6 Manuel Franceschini
      "NEW_VG_NAME": self.op.vg_name,
1969 8084f9f6 Manuel Franceschini
      }
1970 d6a02168 Michael Hanselmann
    mn = self.cfg.GetMasterNode()
1971 8084f9f6 Manuel Franceschini
    return env, [mn], [mn]
1972 8084f9f6 Manuel Franceschini
1973 8084f9f6 Manuel Franceschini
  def CheckPrereq(self):
1974 8084f9f6 Manuel Franceschini
    """Check prerequisites.
1975 8084f9f6 Manuel Franceschini

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

1979 8084f9f6 Manuel Franceschini
    """
1980 779c15bb Iustin Pop
    if self.op.vg_name is not None and not self.op.vg_name:
1981 c53279cf Guido Trotter
      instances = self.cfg.GetAllInstancesInfo().values()
1982 8084f9f6 Manuel Franceschini
      for inst in instances:
1983 8084f9f6 Manuel Franceschini
        for disk in inst.disks:
1984 8084f9f6 Manuel Franceschini
          if _RecursiveCheckIfLVMBased(disk):
1985 8084f9f6 Manuel Franceschini
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1986 5c983ee5 Iustin Pop
                                       " lvm-based instances exist",
1987 5c983ee5 Iustin Pop
                                       errors.ECODE_INVAL)
1988 8084f9f6 Manuel Franceschini
1989 779c15bb Iustin Pop
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1990 779c15bb Iustin Pop
1991 8084f9f6 Manuel Franceschini
    # if vg_name not None, checks given volume group on all nodes
1992 8084f9f6 Manuel Franceschini
    if self.op.vg_name:
1993 72737a7f Iustin Pop
      vglist = self.rpc.call_vg_list(node_list)
1994 8084f9f6 Manuel Franceschini
      for node in node_list:
1995 4c4e4e1e Iustin Pop
        msg = vglist[node].fail_msg
1996 e480923b Iustin Pop
        if msg:
1997 781de953 Iustin Pop
          # ignoring down node
1998 e480923b Iustin Pop
          self.LogWarning("Error while gathering data on node %s"
1999 e480923b Iustin Pop
                          " (ignoring node): %s", node, msg)
2000 781de953 Iustin Pop
          continue
2001 e480923b Iustin Pop
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2002 781de953 Iustin Pop
                                              self.op.vg_name,
2003 8d1a2a64 Michael Hanselmann
                                              constants.MIN_VG_SIZE)
2004 8084f9f6 Manuel Franceschini
        if vgstatus:
2005 8084f9f6 Manuel Franceschini
          raise errors.OpPrereqError("Error on node '%s': %s" %
2006 5c983ee5 Iustin Pop
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2007 8084f9f6 Manuel Franceschini
2008 779c15bb Iustin Pop
    self.cluster = cluster = self.cfg.GetClusterInfo()
2009 5af3da74 Guido Trotter
    # validate params changes
2010 779c15bb Iustin Pop
    if self.op.beparams:
2011 a5728081 Guido Trotter
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2012 abe609b2 Guido Trotter
      self.new_beparams = objects.FillDict(
2013 4ef7f423 Guido Trotter
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
2014 779c15bb Iustin Pop
2015 5af3da74 Guido Trotter
    if self.op.nicparams:
2016 5af3da74 Guido Trotter
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2017 5af3da74 Guido Trotter
      self.new_nicparams = objects.FillDict(
2018 5af3da74 Guido Trotter
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
2019 5af3da74 Guido Trotter
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2020 90b704a1 Guido Trotter
      nic_errors = []
2021 90b704a1 Guido Trotter
2022 90b704a1 Guido Trotter
      # check all instances for consistency
2023 90b704a1 Guido Trotter
      for instance in self.cfg.GetAllInstancesInfo().values():
2024 90b704a1 Guido Trotter
        for nic_idx, nic in enumerate(instance.nics):
2025 90b704a1 Guido Trotter
          params_copy = copy.deepcopy(nic.nicparams)
2026 90b704a1 Guido Trotter
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2027 90b704a1 Guido Trotter
2028 90b704a1 Guido Trotter
          # check parameter syntax
2029 90b704a1 Guido Trotter
          try:
2030 90b704a1 Guido Trotter
            objects.NIC.CheckParameterSyntax(params_filled)
2031 90b704a1 Guido Trotter
          except errors.ConfigurationError, err:
2032 90b704a1 Guido Trotter
            nic_errors.append("Instance %s, nic/%d: %s" %
2033 90b704a1 Guido Trotter
                              (instance.name, nic_idx, err))
2034 90b704a1 Guido Trotter
2035 90b704a1 Guido Trotter
          # if we're moving instances to routed, check that they have an ip
2036 90b704a1 Guido Trotter
          target_mode = params_filled[constants.NIC_MODE]
2037 90b704a1 Guido Trotter
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2038 90b704a1 Guido Trotter
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2039 90b704a1 Guido Trotter
                              (instance.name, nic_idx))
2040 90b704a1 Guido Trotter
      if nic_errors:
2041 90b704a1 Guido Trotter
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2042 90b704a1 Guido Trotter
                                   "\n".join(nic_errors))
2043 5af3da74 Guido Trotter
2044 779c15bb Iustin Pop
    # hypervisor list/parameters
2045 abe609b2 Guido Trotter
    self.new_hvparams = objects.FillDict(cluster.hvparams, {})
2046 779c15bb Iustin Pop
    if self.op.hvparams:
2047 779c15bb Iustin Pop
      if not isinstance(self.op.hvparams, dict):
2048 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
2049 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
2050 779c15bb Iustin Pop
      for hv_name, hv_dict in self.op.hvparams.items():
2051 779c15bb Iustin Pop
        if hv_name not in self.new_hvparams:
2052 779c15bb Iustin Pop
          self.new_hvparams[hv_name] = hv_dict
2053 779c15bb Iustin Pop
        else:
2054 779c15bb Iustin Pop
          self.new_hvparams[hv_name].update(hv_dict)
2055 779c15bb Iustin Pop
2056 779c15bb Iustin Pop
    if self.op.enabled_hypervisors is not None:
2057 779c15bb Iustin Pop
      self.hv_list = self.op.enabled_hypervisors
2058 b119bccb Guido Trotter
      if not self.hv_list:
2059 b119bccb Guido Trotter
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
2060 5c983ee5 Iustin Pop
                                   " least one member",
2061 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
2062 b119bccb Guido Trotter
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
2063 b119bccb Guido Trotter
      if invalid_hvs:
2064 b119bccb Guido Trotter
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
2065 ab3e6da8 Iustin Pop
                                   " entries: %s" %
2066 ab3e6da8 Iustin Pop
                                   utils.CommaJoin(invalid_hvs),
2067 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
2068 779c15bb Iustin Pop
    else:
2069 779c15bb Iustin Pop
      self.hv_list = cluster.enabled_hypervisors
2070 779c15bb Iustin Pop
2071 779c15bb Iustin Pop
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2072 779c15bb Iustin Pop
      # either the enabled list has changed, or the parameters have, validate
2073 779c15bb Iustin Pop
      for hv_name, hv_params in self.new_hvparams.items():
2074 779c15bb Iustin Pop
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2075 779c15bb Iustin Pop
            (self.op.enabled_hypervisors and
2076 779c15bb Iustin Pop
             hv_name in self.op.enabled_hypervisors)):
2077 779c15bb Iustin Pop
          # either this is a new hypervisor, or its parameters have changed
2078 779c15bb Iustin Pop
          hv_class = hypervisor.GetHypervisor(hv_name)
2079 a5728081 Guido Trotter
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2080 779c15bb Iustin Pop
          hv_class.CheckParameterSyntax(hv_params)
2081 779c15bb Iustin Pop
          _CheckHVParams(self, node_list, hv_name, hv_params)
2082 779c15bb Iustin Pop
2083 8084f9f6 Manuel Franceschini
  def Exec(self, feedback_fn):
2084 8084f9f6 Manuel Franceschini
    """Change the parameters of the cluster.
2085 8084f9f6 Manuel Franceschini

2086 8084f9f6 Manuel Franceschini
    """
2087 779c15bb Iustin Pop
    if self.op.vg_name is not None:
2088 b2482333 Guido Trotter
      new_volume = self.op.vg_name
2089 b2482333 Guido Trotter
      if not new_volume:
2090 b2482333 Guido Trotter
        new_volume = None
2091 b2482333 Guido Trotter
      if new_volume != self.cfg.GetVGName():
2092 b2482333 Guido Trotter
        self.cfg.SetVGName(new_volume)
2093 779c15bb Iustin Pop
      else:
2094 779c15bb Iustin Pop
        feedback_fn("Cluster LVM configuration already in desired"
2095 779c15bb Iustin Pop
                    " state, not changing")
2096 779c15bb Iustin Pop
    if self.op.hvparams:
2097 779c15bb Iustin Pop
      self.cluster.hvparams = self.new_hvparams
2098 779c15bb Iustin Pop
    if self.op.enabled_hypervisors is not None:
2099 779c15bb Iustin Pop
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2100 779c15bb Iustin Pop
    if self.op.beparams:
2101 4ef7f423 Guido Trotter
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2102 5af3da74 Guido Trotter
    if self.op.nicparams:
2103 5af3da74 Guido Trotter
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2104 5af3da74 Guido Trotter
2105 4b7735f9 Iustin Pop
    if self.op.candidate_pool_size is not None:
2106 4b7735f9 Iustin Pop
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2107 75e914fb Iustin Pop
      # we need to update the pool size here, otherwise the save will fail
2108 44485f49 Guido Trotter
      _AdjustCandidatePool(self, [])
2109 4b7735f9 Iustin Pop
2110 a4eae71f Michael Hanselmann
    self.cfg.Update(self.cluster, feedback_fn)
2111 8084f9f6 Manuel Franceschini
2112 8084f9f6 Manuel Franceschini
2113 28eddce5 Guido Trotter
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2114 28eddce5 Guido Trotter
  """Distribute additional files which are part of the cluster configuration.
2115 28eddce5 Guido Trotter

2116 28eddce5 Guido Trotter
  ConfigWriter takes care of distributing the config and ssconf files, but
2117 28eddce5 Guido Trotter
  there are more files which should be distributed to all nodes. This function
2118 28eddce5 Guido Trotter
  makes sure those are copied.
2119 28eddce5 Guido Trotter

2120 28eddce5 Guido Trotter
  @param lu: calling logical unit
2121 28eddce5 Guido Trotter
  @param additional_nodes: list of nodes not in the config to distribute to
2122 28eddce5 Guido Trotter

2123 28eddce5 Guido Trotter
  """
2124 28eddce5 Guido Trotter
  # 1. Gather target nodes
2125 28eddce5 Guido Trotter
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2126 28eddce5 Guido Trotter
  dist_nodes = lu.cfg.GetNodeList()
2127 28eddce5 Guido Trotter
  if additional_nodes is not None:
2128 28eddce5 Guido Trotter
    dist_nodes.extend(additional_nodes)
2129 28eddce5 Guido Trotter
  if myself.name in dist_nodes:
2130 28eddce5 Guido Trotter
    dist_nodes.remove(myself.name)
2131 a4eae71f Michael Hanselmann
2132 28eddce5 Guido Trotter
  # 2. Gather files to distribute
2133 28eddce5 Guido Trotter
  dist_files = set([constants.ETC_HOSTS,
2134 28eddce5 Guido Trotter
                    constants.SSH_KNOWN_HOSTS_FILE,
2135 28eddce5 Guido Trotter
                    constants.RAPI_CERT_FILE,
2136 28eddce5 Guido Trotter
                    constants.RAPI_USERS_FILE,
2137 4a34c5cf Guido Trotter
                    constants.HMAC_CLUSTER_KEY,
2138 28eddce5 Guido Trotter
                   ])
2139 e1b8653f Guido Trotter
2140 e1b8653f Guido Trotter
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2141 e1b8653f Guido Trotter
  for hv_name in enabled_hypervisors:
2142 e1b8653f Guido Trotter
    hv_class = hypervisor.GetHypervisor(hv_name)
2143 e1b8653f Guido Trotter
    dist_files.update(hv_class.GetAncillaryFiles())
2144 e1b8653f Guido Trotter
2145 28eddce5 Guido Trotter
  # 3. Perform the files upload
2146 28eddce5 Guido Trotter
  for fname in dist_files:
2147 28eddce5 Guido Trotter
    if os.path.exists(fname):
2148 28eddce5 Guido Trotter
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2149 28eddce5 Guido Trotter
      for to_node, to_result in result.items():
2150 6f7d4e75 Iustin Pop
        msg = to_result.fail_msg
2151 6f7d4e75 Iustin Pop
        if msg:
2152 6f7d4e75 Iustin Pop
          msg = ("Copy of file %s to node %s failed: %s" %
2153 6f7d4e75 Iustin Pop
                 (fname, to_node, msg))
2154 6f7d4e75 Iustin Pop
          lu.proc.LogWarning(msg)
2155 28eddce5 Guido Trotter
2156 28eddce5 Guido Trotter
2157 afee0879 Iustin Pop
class LURedistributeConfig(NoHooksLU):
2158 afee0879 Iustin Pop
  """Force the redistribution of cluster configuration.
2159 afee0879 Iustin Pop

2160 afee0879 Iustin Pop
  This is a very simple LU.
2161 afee0879 Iustin Pop

2162 afee0879 Iustin Pop
  """
2163 afee0879 Iustin Pop
  _OP_REQP = []
2164 afee0879 Iustin Pop
  REQ_BGL = False
2165 afee0879 Iustin Pop
2166 afee0879 Iustin Pop
  def ExpandNames(self):
2167 afee0879 Iustin Pop
    self.needed_locks = {
2168 afee0879 Iustin Pop
      locking.LEVEL_NODE: locking.ALL_SET,
2169 afee0879 Iustin Pop
    }
2170 afee0879 Iustin Pop
    self.share_locks[locking.LEVEL_NODE] = 1
2171 afee0879 Iustin Pop
2172 afee0879 Iustin Pop
  def CheckPrereq(self):
2173 afee0879 Iustin Pop
    """Check prerequisites.
2174 afee0879 Iustin Pop

2175 afee0879 Iustin Pop
    """
2176 afee0879 Iustin Pop
2177 afee0879 Iustin Pop
  def Exec(self, feedback_fn):
2178 afee0879 Iustin Pop
    """Redistribute the configuration.
2179 afee0879 Iustin Pop

2180 afee0879 Iustin Pop
    """
2181 a4eae71f Michael Hanselmann
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2182 28eddce5 Guido Trotter
    _RedistributeAncillaryFiles(self)
2183 afee0879 Iustin Pop
2184 afee0879 Iustin Pop
2185 b6c07b79 Michael Hanselmann
def _WaitForSync(lu, instance, oneshot=False):
2186 a8083063 Iustin Pop
  """Sleep and poll for an instance's disk to sync.
2187 a8083063 Iustin Pop

2188 a8083063 Iustin Pop
  """
2189 a8083063 Iustin Pop
  if not instance.disks:
2190 a8083063 Iustin Pop
    return True
2191 a8083063 Iustin Pop
2192 a8083063 Iustin Pop
  if not oneshot:
2193 b9bddb6b Iustin Pop
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2194 a8083063 Iustin Pop
2195 a8083063 Iustin Pop
  node = instance.primary_node
2196 a8083063 Iustin Pop
2197 a8083063 Iustin Pop
  for dev in instance.disks:
2198 b9bddb6b Iustin Pop
    lu.cfg.SetDiskID(dev, node)
2199 a8083063 Iustin Pop
2200 6bcb1446 Michael Hanselmann
  # TODO: Convert to utils.Retry
2201 6bcb1446 Michael Hanselmann
2202 a8083063 Iustin Pop
  retries = 0
2203 fbafd7a8 Iustin Pop
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2204 a8083063 Iustin Pop
  while True:
2205 a8083063 Iustin Pop
    max_time = 0
2206 a8083063 Iustin Pop
    done = True
2207 a8083063 Iustin Pop
    cumul_degraded = False
2208 72737a7f Iustin Pop
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2209 4c4e4e1e Iustin Pop
    msg = rstats.fail_msg
2210 3efa9051 Iustin Pop
    if msg:
2211 3efa9051 Iustin Pop
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2212 a8083063 Iustin Pop
      retries += 1
2213 a8083063 Iustin Pop
      if retries >= 10:
2214 3ecf6786 Iustin Pop
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2215 3ecf6786 Iustin Pop
                                 " aborting." % node)
2216 a8083063 Iustin Pop
      time.sleep(6)
2217 a8083063 Iustin Pop
      continue
2218 3efa9051 Iustin Pop
    rstats = rstats.payload
2219 a8083063 Iustin Pop
    retries = 0
2220 1492cca7 Iustin Pop
    for i, mstat in enumerate(rstats):
2221 a8083063 Iustin Pop
      if mstat is None:
2222 86d9d3bb Iustin Pop
        lu.LogWarning("Can't compute data for node %s/%s",
2223 86d9d3bb Iustin Pop
                           node, instance.disks[i].iv_name)
2224 a8083063 Iustin Pop
        continue
2225 36145b12 Michael Hanselmann
2226 36145b12 Michael Hanselmann
      cumul_degraded = (cumul_degraded or
2227 36145b12 Michael Hanselmann
                        (mstat.is_degraded and mstat.sync_percent is None))
2228 36145b12 Michael Hanselmann
      if mstat.sync_percent is not None:
2229 a8083063 Iustin Pop
        done = False
2230 36145b12 Michael Hanselmann
        if mstat.estimated_time is not None:
2231 36145b12 Michael Hanselmann
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2232 36145b12 Michael Hanselmann
          max_time = mstat.estimated_time
2233 a8083063 Iustin Pop
        else:
2234 a8083063 Iustin Pop
          rem_time = "no time estimate"
2235 b9bddb6b Iustin Pop
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2236 4d4a651d Michael Hanselmann
                        (instance.disks[i].iv_name, mstat.sync_percent,
2237 4d4a651d Michael Hanselmann
                         rem_time))
2238 fbafd7a8 Iustin Pop
2239 fbafd7a8 Iustin Pop
    # if we're done but degraded, let's do a few small retries, to
2240 fbafd7a8 Iustin Pop
    # make sure we see a stable and not transient situation; therefore
2241 fbafd7a8 Iustin Pop
    # we force restart of the loop
2242 fbafd7a8 Iustin Pop
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2243 fbafd7a8 Iustin Pop
      logging.info("Degraded disks found, %d retries left", degr_retries)
2244 fbafd7a8 Iustin Pop
      degr_retries -= 1
2245 fbafd7a8 Iustin Pop
      time.sleep(1)
2246 fbafd7a8 Iustin Pop
      continue
2247 fbafd7a8 Iustin Pop
2248 a8083063 Iustin Pop
    if done or oneshot:
2249 a8083063 Iustin Pop
      break
2250 a8083063 Iustin Pop
2251 d4fa5c23 Iustin Pop
    time.sleep(min(60, max_time))
2252 a8083063 Iustin Pop
2253 a8083063 Iustin Pop
  if done:
2254 b9bddb6b Iustin Pop
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2255 a8083063 Iustin Pop
  return not cumul_degraded
2256 a8083063 Iustin Pop
2257 a8083063 Iustin Pop
2258 b9bddb6b Iustin Pop
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2259 a8083063 Iustin Pop
  """Check that mirrors are not degraded.
2260 a8083063 Iustin Pop

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

2265 a8083063 Iustin Pop
  """
2266 b9bddb6b Iustin Pop
  lu.cfg.SetDiskID(dev, node)
2267 a8083063 Iustin Pop
2268 a8083063 Iustin Pop
  result = True
2269 96acbc09 Michael Hanselmann
2270 a8083063 Iustin Pop
  if on_primary or dev.AssembleOnSecondary():
2271 72737a7f Iustin Pop
    rstats = lu.rpc.call_blockdev_find(node, dev)
2272 4c4e4e1e Iustin Pop
    msg = rstats.fail_msg
2273 23829f6f Iustin Pop
    if msg:
2274 23829f6f Iustin Pop
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2275 23829f6f Iustin Pop
      result = False
2276 23829f6f Iustin Pop
    elif not rstats.payload:
2277 23829f6f Iustin Pop
      lu.LogWarning("Can't find disk on node %s", node)
2278 a8083063 Iustin Pop
      result = False
2279 a8083063 Iustin Pop
    else:
2280 96acbc09 Michael Hanselmann
      if ldisk:
2281 f208978a Michael Hanselmann
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2282 96acbc09 Michael Hanselmann
      else:
2283 96acbc09 Michael Hanselmann
        result = result and not rstats.payload.is_degraded
2284 96acbc09 Michael Hanselmann
2285 a8083063 Iustin Pop
  if dev.children:
2286 a8083063 Iustin Pop
    for child in dev.children:
2287 b9bddb6b Iustin Pop
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2288 a8083063 Iustin Pop
2289 a8083063 Iustin Pop
  return result
2290 a8083063 Iustin Pop
2291 a8083063 Iustin Pop
2292 a8083063 Iustin Pop
class LUDiagnoseOS(NoHooksLU):
2293 a8083063 Iustin Pop
  """Logical unit for OS diagnose/query.
2294 a8083063 Iustin Pop

2295 a8083063 Iustin Pop
  """
2296 1f9430d6 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
2297 6bf01bbb Guido Trotter
  REQ_BGL = False
2298 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet()
2299 1e288a26 Guido Trotter
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2300 1e288a26 Guido Trotter
  # Fields that need calculation of global os validity
2301 1e288a26 Guido Trotter
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2302 a8083063 Iustin Pop
2303 6bf01bbb Guido Trotter
  def ExpandNames(self):
2304 1f9430d6 Iustin Pop
    if self.op.names:
2305 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Selective OS query not supported",
2306 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
2307 1f9430d6 Iustin Pop
2308 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
2309 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
2310 1f9430d6 Iustin Pop
                       selected=self.op.output_fields)
2311 1f9430d6 Iustin Pop
2312 6bf01bbb Guido Trotter
    # Lock all nodes, in shared mode
2313 a6ab004b Iustin Pop
    # Temporary removal of locks, should be reverted later
2314 a6ab004b Iustin Pop
    # TODO: reintroduce locks when they are lighter-weight
2315 6bf01bbb Guido Trotter
    self.needed_locks = {}
2316 a6ab004b Iustin Pop
    #self.share_locks[locking.LEVEL_NODE] = 1
2317 a6ab004b Iustin Pop
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2318 6bf01bbb Guido Trotter
2319 6bf01bbb Guido Trotter
  def CheckPrereq(self):
2320 6bf01bbb Guido Trotter
    """Check prerequisites.
2321 6bf01bbb Guido Trotter

2322 6bf01bbb Guido Trotter
    """
2323 6bf01bbb Guido Trotter
2324 1f9430d6 Iustin Pop
  @staticmethod
2325 857121ad Iustin Pop
  def _DiagnoseByOS(rlist):
2326 1f9430d6 Iustin Pop
    """Remaps a per-node return list into an a per-os per-node dictionary
2327 1f9430d6 Iustin Pop

2328 e4376078 Iustin Pop
    @param rlist: a map with node names as keys and OS objects as values
2329 1f9430d6 Iustin Pop

2330 e4376078 Iustin Pop
    @rtype: dict
2331 5fcc718f Iustin Pop
    @return: a dictionary with osnames as keys and as value another map, with
2332 255dcebd Iustin Pop
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2333 e4376078 Iustin Pop

2334 255dcebd Iustin Pop
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2335 255dcebd Iustin Pop
                                     (/srv/..., False, "invalid api")],
2336 255dcebd Iustin Pop
                           "node2": [(/srv/..., True, "")]}
2337 e4376078 Iustin Pop
          }
2338 1f9430d6 Iustin Pop

2339 1f9430d6 Iustin Pop
    """
2340 1f9430d6 Iustin Pop
    all_os = {}
2341 a6ab004b Iustin Pop
    # we build here the list of nodes that didn't fail the RPC (at RPC
2342 a6ab004b Iustin Pop
    # level), so that nodes with a non-responding node daemon don't
2343 a6ab004b Iustin Pop
    # make all OSes invalid
2344 a6ab004b Iustin Pop
    good_nodes = [node_name for node_name in rlist
2345 4c4e4e1e Iustin Pop
                  if not rlist[node_name].fail_msg]
2346 83d92ad8 Iustin Pop
    for node_name, nr in rlist.items():
2347 4c4e4e1e Iustin Pop
      if nr.fail_msg or not nr.payload:
2348 1f9430d6 Iustin Pop
        continue
2349 ba00557a Guido Trotter
      for name, path, status, diagnose, variants in nr.payload:
2350 255dcebd Iustin Pop
        if name not in all_os:
2351 1f9430d6 Iustin Pop
          # build a list of nodes for this os containing empty lists
2352 1f9430d6 Iustin Pop
          # for each node in node_list
2353 255dcebd Iustin Pop
          all_os[name] = {}
2354 a6ab004b Iustin Pop
          for nname in good_nodes:
2355 255dcebd Iustin Pop
            all_os[name][nname] = []
2356 ba00557a Guido Trotter
        all_os[name][node_name].append((path, status, diagnose, variants))
2357 1f9430d6 Iustin Pop
    return all_os
2358 a8083063 Iustin Pop
2359 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2360 a8083063 Iustin Pop
    """Compute the list of OSes.
2361 a8083063 Iustin Pop

2362 a8083063 Iustin Pop
    """
2363 a6ab004b Iustin Pop
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2364 94a02bb5 Iustin Pop
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2365 857121ad Iustin Pop
    pol = self._DiagnoseByOS(node_data)
2366 1f9430d6 Iustin Pop
    output = []
2367 1e288a26 Guido Trotter
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2368 1e288a26 Guido Trotter
    calc_variants = "variants" in self.op.output_fields
2369 1e288a26 Guido Trotter
2370 83d92ad8 Iustin Pop
    for os_name, os_data in pol.items():
2371 1f9430d6 Iustin Pop
      row = []
2372 1e288a26 Guido Trotter
      if calc_valid:
2373 1e288a26 Guido Trotter
        valid = True
2374 1e288a26 Guido Trotter
        variants = None
2375 1e288a26 Guido Trotter
        for osl in os_data.values():
2376 1e288a26 Guido Trotter
          valid = valid and osl and osl[0][1]
2377 1e288a26 Guido Trotter
          if not valid:
2378 1e288a26 Guido Trotter
            variants = None
2379 1e288a26 Guido Trotter
            break
2380 1e288a26 Guido Trotter
          if calc_variants:
2381 1e288a26 Guido Trotter
            node_variants = osl[0][3]
2382 1e288a26 Guido Trotter
            if variants is None:
2383 1e288a26 Guido Trotter
              variants = node_variants
2384 1e288a26 Guido Trotter
            else:
2385 1e288a26 Guido Trotter
              variants = [v for v in variants if v in node_variants]
2386 1e288a26 Guido Trotter
2387 1f9430d6 Iustin Pop
      for field in self.op.output_fields:
2388 1f9430d6 Iustin Pop
        if field == "name":
2389 1f9430d6 Iustin Pop
          val = os_name
2390 1f9430d6 Iustin Pop
        elif field == "valid":
2391 1e288a26 Guido Trotter
          val = valid
2392 1f9430d6 Iustin Pop
        elif field == "node_status":
2393 255dcebd Iustin Pop
          # this is just a copy of the dict
2394 1f9430d6 Iustin Pop
          val = {}
2395 255dcebd Iustin Pop
          for node_name, nos_list in os_data.items():
2396 255dcebd Iustin Pop
            val[node_name] = nos_list
2397 1e288a26 Guido Trotter
        elif field == "variants":
2398 1e288a26 Guido Trotter
          val =  variants
2399 1f9430d6 Iustin Pop
        else:
2400 1f9430d6 Iustin Pop
          raise errors.ParameterError(field)
2401 1f9430d6 Iustin Pop
        row.append(val)
2402 1f9430d6 Iustin Pop
      output.append(row)
2403 1f9430d6 Iustin Pop
2404 1f9430d6 Iustin Pop
    return output
2405 a8083063 Iustin Pop
2406 a8083063 Iustin Pop
2407 a8083063 Iustin Pop
class LURemoveNode(LogicalUnit):
2408 a8083063 Iustin Pop
  """Logical unit for removing a node.
2409 a8083063 Iustin Pop

2410 a8083063 Iustin Pop
  """
2411 a8083063 Iustin Pop
  HPATH = "node-remove"
2412 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
2413 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
2414 a8083063 Iustin Pop
2415 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2416 a8083063 Iustin Pop
    """Build hooks env.
2417 a8083063 Iustin Pop

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

2421 a8083063 Iustin Pop
    """
2422 396e1b78 Michael Hanselmann
    env = {
2423 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
2424 396e1b78 Michael Hanselmann
      "NODE_NAME": self.op.node_name,
2425 396e1b78 Michael Hanselmann
      }
2426 a8083063 Iustin Pop
    all_nodes = self.cfg.GetNodeList()
2427 cd46f3b4 Luca Bigliardi
    if self.op.node_name in all_nodes:
2428 cd46f3b4 Luca Bigliardi
      all_nodes.remove(self.op.node_name)
2429 396e1b78 Michael Hanselmann
    return env, all_nodes, all_nodes
2430 a8083063 Iustin Pop
2431 a8083063 Iustin Pop
  def CheckPrereq(self):
2432 a8083063 Iustin Pop
    """Check prerequisites.
2433 a8083063 Iustin Pop

2434 a8083063 Iustin Pop
    This checks:
2435 a8083063 Iustin Pop
     - the node exists in the configuration
2436 a8083063 Iustin Pop
     - it does not have primary or secondary instances
2437 a8083063 Iustin Pop
     - it's not the master
2438 a8083063 Iustin Pop

2439 5bbd3f7f Michael Hanselmann
    Any errors are signaled by raising errors.OpPrereqError.
2440 a8083063 Iustin Pop

2441 a8083063 Iustin Pop
    """
2442 a8083063 Iustin Pop
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
2443 a8083063 Iustin Pop
    if node is None:
2444 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Node '%s' is unknown." % self.op.node_name,
2445 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
2446 a8083063 Iustin Pop
2447 a8083063 Iustin Pop
    instance_list = self.cfg.GetInstanceList()
2448 a8083063 Iustin Pop
2449 d6a02168 Michael Hanselmann
    masternode = self.cfg.GetMasterNode()
2450 a8083063 Iustin Pop
    if node.name == masternode:
2451 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node is the master node,"
2452 5c983ee5 Iustin Pop
                                 " you need to failover first.",
2453 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
2454 a8083063 Iustin Pop
2455 a8083063 Iustin Pop
    for instance_name in instance_list:
2456 a8083063 Iustin Pop
      instance = self.cfg.GetInstanceInfo(instance_name)
2457 6b12959c Iustin Pop
      if node.name in instance.all_nodes:
2458 6b12959c Iustin Pop
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2459 5c983ee5 Iustin Pop
                                   " please remove first." % instance_name,
2460 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
2461 a8083063 Iustin Pop
    self.op.node_name = node.name
2462 a8083063 Iustin Pop
    self.node = node
2463 a8083063 Iustin Pop
2464 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2465 a8083063 Iustin Pop
    """Removes the node from the cluster.
2466 a8083063 Iustin Pop

2467 a8083063 Iustin Pop
    """
2468 a8083063 Iustin Pop
    node = self.node
2469 9a4f63d1 Iustin Pop
    logging.info("Stopping the node daemon and removing configs from node %s",
2470 9a4f63d1 Iustin Pop
                 node.name)
2471 a8083063 Iustin Pop
2472 b989b9d9 Ken Wehr
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2473 b989b9d9 Ken Wehr
2474 44485f49 Guido Trotter
    # Promote nodes to master candidate as needed
2475 44485f49 Guido Trotter
    _AdjustCandidatePool(self, exceptions=[node.name])
2476 d8470559 Michael Hanselmann
    self.context.RemoveNode(node.name)
2477 a8083063 Iustin Pop
2478 cd46f3b4 Luca Bigliardi
    # Run post hooks on the node before it's removed
2479 cd46f3b4 Luca Bigliardi
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2480 cd46f3b4 Luca Bigliardi
    try:
2481 1122eb25 Iustin Pop
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2482 3cb5c1e3 Luca Bigliardi
    except:
2483 7260cfbe Iustin Pop
      # pylint: disable-msg=W0702
2484 3cb5c1e3 Luca Bigliardi
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2485 cd46f3b4 Luca Bigliardi
2486 b989b9d9 Ken Wehr
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2487 4c4e4e1e Iustin Pop
    msg = result.fail_msg
2488 0623d351 Iustin Pop
    if msg:
2489 0623d351 Iustin Pop
      self.LogWarning("Errors encountered on the remote node while leaving"
2490 0623d351 Iustin Pop
                      " the cluster: %s", msg)
2491 c8a0948f Michael Hanselmann
2492 a8083063 Iustin Pop
2493 a8083063 Iustin Pop
class LUQueryNodes(NoHooksLU):
2494 a8083063 Iustin Pop
  """Logical unit for querying nodes.
2495 a8083063 Iustin Pop

2496 a8083063 Iustin Pop
  """
2497 7260cfbe Iustin Pop
  # pylint: disable-msg=W0142
2498 bc8e4a1a Iustin Pop
  _OP_REQP = ["output_fields", "names", "use_locking"]
2499 35705d8f Guido Trotter
  REQ_BGL = False
2500 19bed813 Iustin Pop
2501 19bed813 Iustin Pop
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2502 19bed813 Iustin Pop
                    "master_candidate", "offline", "drained"]
2503 19bed813 Iustin Pop
2504 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet(
2505 31bf511f Iustin Pop
    "dtotal", "dfree",
2506 31bf511f Iustin Pop
    "mtotal", "mnode", "mfree",
2507 31bf511f Iustin Pop
    "bootid",
2508 0105bad3 Iustin Pop
    "ctotal", "cnodes", "csockets",
2509 31bf511f Iustin Pop
    )
2510 31bf511f Iustin Pop
2511 19bed813 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet(*[
2512 19bed813 Iustin Pop
    "pinst_cnt", "sinst_cnt",
2513 31bf511f Iustin Pop
    "pinst_list", "sinst_list",
2514 31bf511f Iustin Pop
    "pip", "sip", "tags",
2515 0e67cdbe Iustin Pop
    "master",
2516 19bed813 Iustin Pop
    "role"] + _SIMPLE_FIELDS
2517 31bf511f Iustin Pop
    )
2518 a8083063 Iustin Pop
2519 35705d8f Guido Trotter
  def ExpandNames(self):
2520 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
2521 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
2522 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
2523 a8083063 Iustin Pop
2524 35705d8f Guido Trotter
    self.needed_locks = {}
2525 35705d8f Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
2526 c8d8b4c8 Iustin Pop
2527 c8d8b4c8 Iustin Pop
    if self.op.names:
2528 c8d8b4c8 Iustin Pop
      self.wanted = _GetWantedNodes(self, self.op.names)
2529 35705d8f Guido Trotter
    else:
2530 c8d8b4c8 Iustin Pop
      self.wanted = locking.ALL_SET
2531 c8d8b4c8 Iustin Pop
2532 bc8e4a1a Iustin Pop
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2533 bc8e4a1a Iustin Pop
    self.do_locking = self.do_node_query and self.op.use_locking
2534 c8d8b4c8 Iustin Pop
    if self.do_locking:
2535 c8d8b4c8 Iustin Pop
      # if we don't request only static fields, we need to lock the nodes
2536 c8d8b4c8 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2537 c8d8b4c8 Iustin Pop
2538 35705d8f Guido Trotter
  def CheckPrereq(self):
2539 35705d8f Guido Trotter
    """Check prerequisites.
2540 35705d8f Guido Trotter

2541 35705d8f Guido Trotter
    """
2542 c8d8b4c8 Iustin Pop
    # The validation of the node list is done in the _GetWantedNodes,
2543 c8d8b4c8 Iustin Pop
    # if non empty, and if empty, there's no validation to do
2544 c8d8b4c8 Iustin Pop
    pass
2545 a8083063 Iustin Pop
2546 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2547 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
2548 a8083063 Iustin Pop

2549 a8083063 Iustin Pop
    """
2550 c8d8b4c8 Iustin Pop
    all_info = self.cfg.GetAllNodesInfo()
2551 c8d8b4c8 Iustin Pop
    if self.do_locking:
2552 c8d8b4c8 Iustin Pop
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2553 3fa93523 Guido Trotter
    elif self.wanted != locking.ALL_SET:
2554 3fa93523 Guido Trotter
      nodenames = self.wanted
2555 3fa93523 Guido Trotter
      missing = set(nodenames).difference(all_info.keys())
2556 3fa93523 Guido Trotter
      if missing:
2557 7b3a8fb5 Iustin Pop
        raise errors.OpExecError(
2558 3fa93523 Guido Trotter
          "Some nodes were removed before retrieving their data: %s" % missing)
2559 c8d8b4c8 Iustin Pop
    else:
2560 c8d8b4c8 Iustin Pop
      nodenames = all_info.keys()
2561 c1f1cbb2 Iustin Pop
2562 c1f1cbb2 Iustin Pop
    nodenames = utils.NiceSort(nodenames)
2563 c8d8b4c8 Iustin Pop
    nodelist = [all_info[name] for name in nodenames]
2564 a8083063 Iustin Pop
2565 a8083063 Iustin Pop
    # begin data gathering
2566 a8083063 Iustin Pop
2567 bc8e4a1a Iustin Pop
    if self.do_node_query:
2568 a8083063 Iustin Pop
      live_data = {}
2569 72737a7f Iustin Pop
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2570 72737a7f Iustin Pop
                                          self.cfg.GetHypervisorType())
2571 a8083063 Iustin Pop
      for name in nodenames:
2572 781de953 Iustin Pop
        nodeinfo = node_data[name]
2573 4c4e4e1e Iustin Pop
        if not nodeinfo.fail_msg and nodeinfo.payload:
2574 070e998b Iustin Pop
          nodeinfo = nodeinfo.payload
2575 d599d686 Iustin Pop
          fn = utils.TryConvert
2576 a8083063 Iustin Pop
          live_data[name] = {
2577 d599d686 Iustin Pop
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2578 d599d686 Iustin Pop
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2579 d599d686 Iustin Pop
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2580 d599d686 Iustin Pop
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2581 d599d686 Iustin Pop
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2582 d599d686 Iustin Pop
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2583 d599d686 Iustin Pop
            "bootid": nodeinfo.get('bootid', None),
2584 0105bad3 Iustin Pop
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2585 0105bad3 Iustin Pop
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2586 a8083063 Iustin Pop
            }
2587 a8083063 Iustin Pop
        else:
2588 a8083063 Iustin Pop
          live_data[name] = {}
2589 a8083063 Iustin Pop
    else:
2590 a8083063 Iustin Pop
      live_data = dict.fromkeys(nodenames, {})
2591 a8083063 Iustin Pop
2592 ec223efb Iustin Pop
    node_to_primary = dict([(name, set()) for name in nodenames])
2593 ec223efb Iustin Pop
    node_to_secondary = dict([(name, set()) for name in nodenames])
2594 a8083063 Iustin Pop
2595 ec223efb Iustin Pop
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2596 ec223efb Iustin Pop
                             "sinst_cnt", "sinst_list"))
2597 ec223efb Iustin Pop
    if inst_fields & frozenset(self.op.output_fields):
2598 4dfd6266 Iustin Pop
      inst_data = self.cfg.GetAllInstancesInfo()
2599 a8083063 Iustin Pop
2600 1122eb25 Iustin Pop
      for inst in inst_data.values():
2601 ec223efb Iustin Pop
        if inst.primary_node in node_to_primary:
2602 ec223efb Iustin Pop
          node_to_primary[inst.primary_node].add(inst.name)
2603 ec223efb Iustin Pop
        for secnode in inst.secondary_nodes:
2604 ec223efb Iustin Pop
          if secnode in node_to_secondary:
2605 ec223efb Iustin Pop
            node_to_secondary[secnode].add(inst.name)
2606 a8083063 Iustin Pop
2607 0e67cdbe Iustin Pop
    master_node = self.cfg.GetMasterNode()
2608 0e67cdbe Iustin Pop
2609 a8083063 Iustin Pop
    # end data gathering
2610 a8083063 Iustin Pop
2611 a8083063 Iustin Pop
    output = []
2612 a8083063 Iustin Pop
    for node in nodelist:
2613 a8083063 Iustin Pop
      node_output = []
2614 a8083063 Iustin Pop
      for field in self.op.output_fields:
2615 19bed813 Iustin Pop
        if field in self._SIMPLE_FIELDS:
2616 19bed813 Iustin Pop
          val = getattr(node, field)
2617 ec223efb Iustin Pop
        elif field == "pinst_list":
2618 ec223efb Iustin Pop
          val = list(node_to_primary[node.name])
2619 ec223efb Iustin Pop
        elif field == "sinst_list":
2620 ec223efb Iustin Pop
          val = list(node_to_secondary[node.name])
2621 ec223efb Iustin Pop
        elif field == "pinst_cnt":
2622 ec223efb Iustin Pop
          val = len(node_to_primary[node.name])
2623 ec223efb Iustin Pop
        elif field == "sinst_cnt":
2624 ec223efb Iustin Pop
          val = len(node_to_secondary[node.name])
2625 a8083063 Iustin Pop
        elif field == "pip":
2626 a8083063 Iustin Pop
          val = node.primary_ip
2627 a8083063 Iustin Pop
        elif field == "sip":
2628 a8083063 Iustin Pop
          val = node.secondary_ip
2629 130a6a6f Iustin Pop
        elif field == "tags":
2630 130a6a6f Iustin Pop
          val = list(node.GetTags())
2631 0e67cdbe Iustin Pop
        elif field == "master":
2632 0e67cdbe Iustin Pop
          val = node.name == master_node
2633 31bf511f Iustin Pop
        elif self._FIELDS_DYNAMIC.Matches(field):
2634 ec223efb Iustin Pop
          val = live_data[node.name].get(field, None)
2635 c120ff34 Iustin Pop
        elif field == "role":
2636 c120ff34 Iustin Pop
          if node.name == master_node:
2637 c120ff34 Iustin Pop
            val = "M"
2638 c120ff34 Iustin Pop
          elif node.master_candidate:
2639 c120ff34 Iustin Pop
            val = "C"
2640 c120ff34 Iustin Pop
          elif node.drained:
2641 c120ff34 Iustin Pop
            val = "D"
2642 c120ff34 Iustin Pop
          elif node.offline:
2643 c120ff34 Iustin Pop
            val = "O"
2644 c120ff34 Iustin Pop
          else:
2645 c120ff34 Iustin Pop
            val = "R"
2646 a8083063 Iustin Pop
        else:
2647 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
2648 a8083063 Iustin Pop
        node_output.append(val)
2649 a8083063 Iustin Pop
      output.append(node_output)
2650 a8083063 Iustin Pop
2651 a8083063 Iustin Pop
    return output
2652 a8083063 Iustin Pop
2653 a8083063 Iustin Pop
2654 dcb93971 Michael Hanselmann
class LUQueryNodeVolumes(NoHooksLU):
2655 dcb93971 Michael Hanselmann
  """Logical unit for getting volumes on node(s).
2656 dcb93971 Michael Hanselmann

2657 dcb93971 Michael Hanselmann
  """
2658 dcb93971 Michael Hanselmann
  _OP_REQP = ["nodes", "output_fields"]
2659 21a15682 Guido Trotter
  REQ_BGL = False
2660 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
2661 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet("node")
2662 21a15682 Guido Trotter
2663 21a15682 Guido Trotter
  def ExpandNames(self):
2664 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
2665 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
2666 21a15682 Guido Trotter
                       selected=self.op.output_fields)
2667 21a15682 Guido Trotter
2668 21a15682 Guido Trotter
    self.needed_locks = {}
2669 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
2670 21a15682 Guido Trotter
    if not self.op.nodes:
2671 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2672 21a15682 Guido Trotter
    else:
2673 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
2674 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
2675 dcb93971 Michael Hanselmann
2676 dcb93971 Michael Hanselmann
  def CheckPrereq(self):
2677 dcb93971 Michael Hanselmann
    """Check prerequisites.
2678 dcb93971 Michael Hanselmann

2679 dcb93971 Michael Hanselmann
    This checks that the fields required are valid output fields.
2680 dcb93971 Michael Hanselmann

2681 dcb93971 Michael Hanselmann
    """
2682 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2683 dcb93971 Michael Hanselmann
2684 dcb93971 Michael Hanselmann
  def Exec(self, feedback_fn):
2685 dcb93971 Michael Hanselmann
    """Computes the list of nodes and their attributes.
2686 dcb93971 Michael Hanselmann

2687 dcb93971 Michael Hanselmann
    """
2688 a7ba5e53 Iustin Pop
    nodenames = self.nodes
2689 72737a7f Iustin Pop
    volumes = self.rpc.call_node_volumes(nodenames)
2690 dcb93971 Michael Hanselmann
2691 dcb93971 Michael Hanselmann
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
2692 dcb93971 Michael Hanselmann
             in self.cfg.GetInstanceList()]
2693 dcb93971 Michael Hanselmann
2694 dcb93971 Michael Hanselmann
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
2695 dcb93971 Michael Hanselmann
2696 dcb93971 Michael Hanselmann
    output = []
2697 dcb93971 Michael Hanselmann
    for node in nodenames:
2698 10bfe6cb Iustin Pop
      nresult = volumes[node]
2699 10bfe6cb Iustin Pop
      if nresult.offline:
2700 10bfe6cb Iustin Pop
        continue
2701 4c4e4e1e Iustin Pop
      msg = nresult.fail_msg
2702 10bfe6cb Iustin Pop
      if msg:
2703 10bfe6cb Iustin Pop
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
2704 37d19eb2 Michael Hanselmann
        continue
2705 37d19eb2 Michael Hanselmann
2706 10bfe6cb Iustin Pop
      node_vols = nresult.payload[:]
2707 dcb93971 Michael Hanselmann
      node_vols.sort(key=lambda vol: vol['dev'])
2708 dcb93971 Michael Hanselmann
2709 dcb93971 Michael Hanselmann
      for vol in node_vols:
2710 dcb93971 Michael Hanselmann
        node_output = []
2711 dcb93971 Michael Hanselmann
        for field in self.op.output_fields:
2712 dcb93971 Michael Hanselmann
          if field == "node":
2713 dcb93971 Michael Hanselmann
            val = node
2714 dcb93971 Michael Hanselmann
          elif field == "phys":
2715 dcb93971 Michael Hanselmann
            val = vol['dev']
2716 dcb93971 Michael Hanselmann
          elif field == "vg":
2717 dcb93971 Michael Hanselmann
            val = vol['vg']
2718 dcb93971 Michael Hanselmann
          elif field == "name":
2719 dcb93971 Michael Hanselmann
            val = vol['name']
2720 dcb93971 Michael Hanselmann
          elif field == "size":
2721 dcb93971 Michael Hanselmann
            val = int(float(vol['size']))
2722 dcb93971 Michael Hanselmann
          elif field == "instance":
2723 dcb93971 Michael Hanselmann
            for inst in ilist:
2724 dcb93971 Michael Hanselmann
              if node not in lv_by_node[inst]:
2725 dcb93971 Michael Hanselmann
                continue
2726 dcb93971 Michael Hanselmann
              if vol['name'] in lv_by_node[inst][node]:
2727 dcb93971 Michael Hanselmann
                val = inst.name
2728 dcb93971 Michael Hanselmann
                break
2729 dcb93971 Michael Hanselmann
            else:
2730 dcb93971 Michael Hanselmann
              val = '-'
2731 dcb93971 Michael Hanselmann
          else:
2732 3ecf6786 Iustin Pop
            raise errors.ParameterError(field)
2733 dcb93971 Michael Hanselmann
          node_output.append(str(val))
2734 dcb93971 Michael Hanselmann
2735 dcb93971 Michael Hanselmann
        output.append(node_output)
2736 dcb93971 Michael Hanselmann
2737 dcb93971 Michael Hanselmann
    return output
2738 dcb93971 Michael Hanselmann
2739 dcb93971 Michael Hanselmann
2740 9e5442ce Michael Hanselmann
class LUQueryNodeStorage(NoHooksLU):
2741 9e5442ce Michael Hanselmann
  """Logical unit for getting information on storage units on node(s).
2742 9e5442ce Michael Hanselmann

2743 9e5442ce Michael Hanselmann
  """
2744 9e5442ce Michael Hanselmann
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
2745 9e5442ce Michael Hanselmann
  REQ_BGL = False
2746 620a85fd Iustin Pop
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
2747 9e5442ce Michael Hanselmann
2748 9e5442ce Michael Hanselmann
  def ExpandNames(self):
2749 9e5442ce Michael Hanselmann
    storage_type = self.op.storage_type
2750 9e5442ce Michael Hanselmann
2751 620a85fd Iustin Pop
    if storage_type not in constants.VALID_STORAGE_TYPES:
2752 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2753 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
2754 9e5442ce Michael Hanselmann
2755 9e5442ce Michael Hanselmann
    _CheckOutputFields(static=self._FIELDS_STATIC,
2756 620a85fd Iustin Pop
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
2757 9e5442ce Michael Hanselmann
                       selected=self.op.output_fields)
2758 9e5442ce Michael Hanselmann
2759 9e5442ce Michael Hanselmann
    self.needed_locks = {}
2760 9e5442ce Michael Hanselmann
    self.share_locks[locking.LEVEL_NODE] = 1
2761 9e5442ce Michael Hanselmann
2762 9e5442ce Michael Hanselmann
    if self.op.nodes:
2763 9e5442ce Michael Hanselmann
      self.needed_locks[locking.LEVEL_NODE] = \
2764 9e5442ce Michael Hanselmann
        _GetWantedNodes(self, self.op.nodes)
2765 9e5442ce Michael Hanselmann
    else:
2766 9e5442ce Michael Hanselmann
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2767 9e5442ce Michael Hanselmann
2768 9e5442ce Michael Hanselmann
  def CheckPrereq(self):
2769 9e5442ce Michael Hanselmann
    """Check prerequisites.
2770 9e5442ce Michael Hanselmann

2771 9e5442ce Michael Hanselmann
    This checks that the fields required are valid output fields.
2772 9e5442ce Michael Hanselmann

2773 9e5442ce Michael Hanselmann
    """
2774 9e5442ce Michael Hanselmann
    self.op.name = getattr(self.op, "name", None)
2775 9e5442ce Michael Hanselmann
2776 9e5442ce Michael Hanselmann
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
2777 9e5442ce Michael Hanselmann
2778 9e5442ce Michael Hanselmann
  def Exec(self, feedback_fn):
2779 9e5442ce Michael Hanselmann
    """Computes the list of nodes and their attributes.
2780 9e5442ce Michael Hanselmann

2781 9e5442ce Michael Hanselmann
    """
2782 9e5442ce Michael Hanselmann
    # Always get name to sort by
2783 9e5442ce Michael Hanselmann
    if constants.SF_NAME in self.op.output_fields:
2784 9e5442ce Michael Hanselmann
      fields = self.op.output_fields[:]
2785 9e5442ce Michael Hanselmann
    else:
2786 9e5442ce Michael Hanselmann
      fields = [constants.SF_NAME] + self.op.output_fields
2787 9e5442ce Michael Hanselmann
2788 620a85fd Iustin Pop
    # Never ask for node or type as it's only known to the LU
2789 620a85fd Iustin Pop
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
2790 620a85fd Iustin Pop
      while extra in fields:
2791 620a85fd Iustin Pop
        fields.remove(extra)
2792 9e5442ce Michael Hanselmann
2793 9e5442ce Michael Hanselmann
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
2794 9e5442ce Michael Hanselmann
    name_idx = field_idx[constants.SF_NAME]
2795 9e5442ce Michael Hanselmann
2796 efb8da02 Michael Hanselmann
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2797 9e5442ce Michael Hanselmann
    data = self.rpc.call_storage_list(self.nodes,
2798 9e5442ce Michael Hanselmann
                                      self.op.storage_type, st_args,
2799 9e5442ce Michael Hanselmann
                                      self.op.name, fields)
2800 9e5442ce Michael Hanselmann
2801 9e5442ce Michael Hanselmann
    result = []
2802 9e5442ce Michael Hanselmann
2803 9e5442ce Michael Hanselmann
    for node in utils.NiceSort(self.nodes):
2804 9e5442ce Michael Hanselmann
      nresult = data[node]
2805 9e5442ce Michael Hanselmann
      if nresult.offline:
2806 9e5442ce Michael Hanselmann
        continue
2807 9e5442ce Michael Hanselmann
2808 9e5442ce Michael Hanselmann
      msg = nresult.fail_msg
2809 9e5442ce Michael Hanselmann
      if msg:
2810 9e5442ce Michael Hanselmann
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
2811 9e5442ce Michael Hanselmann
        continue
2812 9e5442ce Michael Hanselmann
2813 9e5442ce Michael Hanselmann
      rows = dict([(row[name_idx], row) for row in nresult.payload])
2814 9e5442ce Michael Hanselmann
2815 9e5442ce Michael Hanselmann
      for name in utils.NiceSort(rows.keys()):
2816 9e5442ce Michael Hanselmann
        row = rows[name]
2817 9e5442ce Michael Hanselmann
2818 9e5442ce Michael Hanselmann
        out = []
2819 9e5442ce Michael Hanselmann
2820 9e5442ce Michael Hanselmann
        for field in self.op.output_fields:
2821 620a85fd Iustin Pop
          if field == constants.SF_NODE:
2822 9e5442ce Michael Hanselmann
            val = node
2823 620a85fd Iustin Pop
          elif field == constants.SF_TYPE:
2824 620a85fd Iustin Pop
            val = self.op.storage_type
2825 9e5442ce Michael Hanselmann
          elif field in field_idx:
2826 9e5442ce Michael Hanselmann
            val = row[field_idx[field]]
2827 9e5442ce Michael Hanselmann
          else:
2828 9e5442ce Michael Hanselmann
            raise errors.ParameterError(field)
2829 9e5442ce Michael Hanselmann
2830 9e5442ce Michael Hanselmann
          out.append(val)
2831 9e5442ce Michael Hanselmann
2832 9e5442ce Michael Hanselmann
        result.append(out)
2833 9e5442ce Michael Hanselmann
2834 9e5442ce Michael Hanselmann
    return result
2835 9e5442ce Michael Hanselmann
2836 9e5442ce Michael Hanselmann
2837 efb8da02 Michael Hanselmann
class LUModifyNodeStorage(NoHooksLU):
2838 efb8da02 Michael Hanselmann
  """Logical unit for modifying a storage volume on a node.
2839 efb8da02 Michael Hanselmann

2840 efb8da02 Michael Hanselmann
  """
2841 efb8da02 Michael Hanselmann
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
2842 efb8da02 Michael Hanselmann
  REQ_BGL = False
2843 efb8da02 Michael Hanselmann
2844 efb8da02 Michael Hanselmann
  def CheckArguments(self):
2845 efb8da02 Michael Hanselmann
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2846 efb8da02 Michael Hanselmann
    if node_name is None:
2847 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
2848 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
2849 efb8da02 Michael Hanselmann
2850 efb8da02 Michael Hanselmann
    self.op.node_name = node_name
2851 efb8da02 Michael Hanselmann
2852 efb8da02 Michael Hanselmann
    storage_type = self.op.storage_type
2853 620a85fd Iustin Pop
    if storage_type not in constants.VALID_STORAGE_TYPES:
2854 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
2855 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
2856 efb8da02 Michael Hanselmann
2857 efb8da02 Michael Hanselmann
  def ExpandNames(self):
2858 efb8da02 Michael Hanselmann
    self.needed_locks = {
2859 efb8da02 Michael Hanselmann
      locking.LEVEL_NODE: self.op.node_name,
2860 efb8da02 Michael Hanselmann
      }
2861 efb8da02 Michael Hanselmann
2862 efb8da02 Michael Hanselmann
  def CheckPrereq(self):
2863 efb8da02 Michael Hanselmann
    """Check prerequisites.
2864 efb8da02 Michael Hanselmann

2865 efb8da02 Michael Hanselmann
    """
2866 efb8da02 Michael Hanselmann
    storage_type = self.op.storage_type
2867 efb8da02 Michael Hanselmann
2868 efb8da02 Michael Hanselmann
    try:
2869 efb8da02 Michael Hanselmann
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
2870 efb8da02 Michael Hanselmann
    except KeyError:
2871 efb8da02 Michael Hanselmann
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
2872 5c983ee5 Iustin Pop
                                 " modified" % storage_type,
2873 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
2874 efb8da02 Michael Hanselmann
2875 efb8da02 Michael Hanselmann
    diff = set(self.op.changes.keys()) - modifiable
2876 efb8da02 Michael Hanselmann
    if diff:
2877 efb8da02 Michael Hanselmann
      raise errors.OpPrereqError("The following fields can not be modified for"
2878 efb8da02 Michael Hanselmann
                                 " storage units of type '%s': %r" %
2879 5c983ee5 Iustin Pop
                                 (storage_type, list(diff)),
2880 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
2881 efb8da02 Michael Hanselmann
2882 efb8da02 Michael Hanselmann
  def Exec(self, feedback_fn):
2883 efb8da02 Michael Hanselmann
    """Computes the list of nodes and their attributes.
2884 efb8da02 Michael Hanselmann

2885 efb8da02 Michael Hanselmann
    """
2886 efb8da02 Michael Hanselmann
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
2887 efb8da02 Michael Hanselmann
    result = self.rpc.call_storage_modify(self.op.node_name,
2888 efb8da02 Michael Hanselmann
                                          self.op.storage_type, st_args,
2889 efb8da02 Michael Hanselmann
                                          self.op.name, self.op.changes)
2890 efb8da02 Michael Hanselmann
    result.Raise("Failed to modify storage unit '%s' on %s" %
2891 efb8da02 Michael Hanselmann
                 (self.op.name, self.op.node_name))
2892 efb8da02 Michael Hanselmann
2893 efb8da02 Michael Hanselmann
2894 a8083063 Iustin Pop
class LUAddNode(LogicalUnit):
2895 a8083063 Iustin Pop
  """Logical unit for adding node to the cluster.
2896 a8083063 Iustin Pop

2897 a8083063 Iustin Pop
  """
2898 a8083063 Iustin Pop
  HPATH = "node-add"
2899 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
2900 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
2901 a8083063 Iustin Pop
2902 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2903 a8083063 Iustin Pop
    """Build hooks env.
2904 a8083063 Iustin Pop

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

2907 a8083063 Iustin Pop
    """
2908 a8083063 Iustin Pop
    env = {
2909 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
2910 a8083063 Iustin Pop
      "NODE_NAME": self.op.node_name,
2911 a8083063 Iustin Pop
      "NODE_PIP": self.op.primary_ip,
2912 a8083063 Iustin Pop
      "NODE_SIP": self.op.secondary_ip,
2913 a8083063 Iustin Pop
      }
2914 a8083063 Iustin Pop
    nodes_0 = self.cfg.GetNodeList()
2915 a8083063 Iustin Pop
    nodes_1 = nodes_0 + [self.op.node_name, ]
2916 a8083063 Iustin Pop
    return env, nodes_0, nodes_1
2917 a8083063 Iustin Pop
2918 a8083063 Iustin Pop
  def CheckPrereq(self):
2919 a8083063 Iustin Pop
    """Check prerequisites.
2920 a8083063 Iustin Pop

2921 a8083063 Iustin Pop
    This checks:
2922 a8083063 Iustin Pop
     - the new node is not already in the config
2923 a8083063 Iustin Pop
     - it is resolvable
2924 a8083063 Iustin Pop
     - its parameters (single/dual homed) matches the cluster
2925 a8083063 Iustin Pop

2926 5bbd3f7f Michael Hanselmann
    Any errors are signaled by raising errors.OpPrereqError.
2927 a8083063 Iustin Pop

2928 a8083063 Iustin Pop
    """
2929 a8083063 Iustin Pop
    node_name = self.op.node_name
2930 a8083063 Iustin Pop
    cfg = self.cfg
2931 a8083063 Iustin Pop
2932 104f4ca1 Iustin Pop
    dns_data = utils.GetHostInfo(node_name)
2933 a8083063 Iustin Pop
2934 bcf043c9 Iustin Pop
    node = dns_data.name
2935 bcf043c9 Iustin Pop
    primary_ip = self.op.primary_ip = dns_data.ip
2936 a8083063 Iustin Pop
    secondary_ip = getattr(self.op, "secondary_ip", None)
2937 a8083063 Iustin Pop
    if secondary_ip is None:
2938 a8083063 Iustin Pop
      secondary_ip = primary_ip
2939 a8083063 Iustin Pop
    if not utils.IsValidIP(secondary_ip):
2940 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid secondary IP given",
2941 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
2942 a8083063 Iustin Pop
    self.op.secondary_ip = secondary_ip
2943 e7c6e02b Michael Hanselmann
2944 a8083063 Iustin Pop
    node_list = cfg.GetNodeList()
2945 e7c6e02b Michael Hanselmann
    if not self.op.readd and node in node_list:
2946 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is already in the configuration" %
2947 5c983ee5 Iustin Pop
                                 node, errors.ECODE_EXISTS)
2948 e7c6e02b Michael Hanselmann
    elif self.op.readd and node not in node_list:
2949 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
2950 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
2951 a8083063 Iustin Pop
2952 a8083063 Iustin Pop
    for existing_node_name in node_list:
2953 a8083063 Iustin Pop
      existing_node = cfg.GetNodeInfo(existing_node_name)
2954 e7c6e02b Michael Hanselmann
2955 e7c6e02b Michael Hanselmann
      if self.op.readd and node == existing_node_name:
2956 e7c6e02b Michael Hanselmann
        if (existing_node.primary_ip != primary_ip or
2957 e7c6e02b Michael Hanselmann
            existing_node.secondary_ip != secondary_ip):
2958 e7c6e02b Michael Hanselmann
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2959 5c983ee5 Iustin Pop
                                     " address configuration as before",
2960 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
2961 e7c6e02b Michael Hanselmann
        continue
2962 e7c6e02b Michael Hanselmann
2963 a8083063 Iustin Pop
      if (existing_node.primary_ip == primary_ip or
2964 a8083063 Iustin Pop
          existing_node.secondary_ip == primary_ip or
2965 a8083063 Iustin Pop
          existing_node.primary_ip == secondary_ip or
2966 a8083063 Iustin Pop
          existing_node.secondary_ip == secondary_ip):
2967 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2968 5c983ee5 Iustin Pop
                                   " existing node %s" % existing_node.name,
2969 5c983ee5 Iustin Pop
                                   errors.ECODE_NOTUNIQUE)
2970 a8083063 Iustin Pop
2971 a8083063 Iustin Pop
    # check that the type of the node (single versus dual homed) is the
2972 a8083063 Iustin Pop
    # same as for the master
2973 d6a02168 Michael Hanselmann
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2974 a8083063 Iustin Pop
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2975 a8083063 Iustin Pop
    newbie_singlehomed = secondary_ip == primary_ip
2976 a8083063 Iustin Pop
    if master_singlehomed != newbie_singlehomed:
2977 a8083063 Iustin Pop
      if master_singlehomed:
2978 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has no private ip but the"
2979 5c983ee5 Iustin Pop
                                   " new node has one",
2980 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
2981 a8083063 Iustin Pop
      else:
2982 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has a private ip but the"
2983 5c983ee5 Iustin Pop
                                   " new node doesn't have one",
2984 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
2985 a8083063 Iustin Pop
2986 5bbd3f7f Michael Hanselmann
    # checks reachability
2987 b15d625f Iustin Pop
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2988 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Node not reachable by ping",
2989 5c983ee5 Iustin Pop
                                 errors.ECODE_ENVIRON)
2990 a8083063 Iustin Pop
2991 a8083063 Iustin Pop
    if not newbie_singlehomed:
2992 a8083063 Iustin Pop
      # check reachability from my secondary ip to newbie's secondary ip
2993 b15d625f Iustin Pop
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2994 b15d625f Iustin Pop
                           source=myself.secondary_ip):
2995 f4bc1f2c Michael Hanselmann
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2996 5c983ee5 Iustin Pop
                                   " based ping to noded port",
2997 5c983ee5 Iustin Pop
                                   errors.ECODE_ENVIRON)
2998 a8083063 Iustin Pop
2999 a8ae3eb5 Iustin Pop
    if self.op.readd:
3000 a8ae3eb5 Iustin Pop
      exceptions = [node]
3001 a8ae3eb5 Iustin Pop
    else:
3002 a8ae3eb5 Iustin Pop
      exceptions = []
3003 6d7e1f20 Guido Trotter
3004 6d7e1f20 Guido Trotter
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3005 0fff97e9 Guido Trotter
3006 a8ae3eb5 Iustin Pop
    if self.op.readd:
3007 a8ae3eb5 Iustin Pop
      self.new_node = self.cfg.GetNodeInfo(node)
3008 a8ae3eb5 Iustin Pop
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3009 a8ae3eb5 Iustin Pop
    else:
3010 a8ae3eb5 Iustin Pop
      self.new_node = objects.Node(name=node,
3011 a8ae3eb5 Iustin Pop
                                   primary_ip=primary_ip,
3012 a8ae3eb5 Iustin Pop
                                   secondary_ip=secondary_ip,
3013 a8ae3eb5 Iustin Pop
                                   master_candidate=self.master_candidate,
3014 a8ae3eb5 Iustin Pop
                                   offline=False, drained=False)
3015 a8083063 Iustin Pop
3016 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3017 a8083063 Iustin Pop
    """Adds the new node to the cluster.
3018 a8083063 Iustin Pop

3019 a8083063 Iustin Pop
    """
3020 a8083063 Iustin Pop
    new_node = self.new_node
3021 a8083063 Iustin Pop
    node = new_node.name
3022 a8083063 Iustin Pop
3023 a8ae3eb5 Iustin Pop
    # for re-adds, reset the offline/drained/master-candidate flags;
3024 a8ae3eb5 Iustin Pop
    # we need to reset here, otherwise offline would prevent RPC calls
3025 a8ae3eb5 Iustin Pop
    # later in the procedure; this also means that if the re-add
3026 a8ae3eb5 Iustin Pop
    # fails, we are left with a non-offlined, broken node
3027 a8ae3eb5 Iustin Pop
    if self.op.readd:
3028 7260cfbe Iustin Pop
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3029 a8ae3eb5 Iustin Pop
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3030 a8ae3eb5 Iustin Pop
      # if we demote the node, we do cleanup later in the procedure
3031 a8ae3eb5 Iustin Pop
      new_node.master_candidate = self.master_candidate
3032 a8ae3eb5 Iustin Pop
3033 a8ae3eb5 Iustin Pop
    # notify the user about any possible mc promotion
3034 a8ae3eb5 Iustin Pop
    if new_node.master_candidate:
3035 a8ae3eb5 Iustin Pop
      self.LogInfo("Node will be a master candidate")
3036 a8ae3eb5 Iustin Pop
3037 a8083063 Iustin Pop
    # check connectivity
3038 72737a7f Iustin Pop
    result = self.rpc.call_version([node])[node]
3039 4c4e4e1e Iustin Pop
    result.Raise("Can't get version information from node %s" % node)
3040 90b54c26 Iustin Pop
    if constants.PROTOCOL_VERSION == result.payload:
3041 90b54c26 Iustin Pop
      logging.info("Communication to node %s fine, sw version %s match",
3042 90b54c26 Iustin Pop
                   node, result.payload)
3043 a8083063 Iustin Pop
    else:
3044 90b54c26 Iustin Pop
      raise errors.OpExecError("Version mismatch master version %s,"
3045 90b54c26 Iustin Pop
                               " node version %s" %
3046 90b54c26 Iustin Pop
                               (constants.PROTOCOL_VERSION, result.payload))
3047 a8083063 Iustin Pop
3048 a8083063 Iustin Pop
    # setup ssh on node
3049 b989b9d9 Ken Wehr
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3050 b989b9d9 Ken Wehr
      logging.info("Copy ssh key to node %s", node)
3051 b989b9d9 Ken Wehr
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3052 b989b9d9 Ken Wehr
      keyarray = []
3053 b989b9d9 Ken Wehr
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3054 b989b9d9 Ken Wehr
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3055 b989b9d9 Ken Wehr
                  priv_key, pub_key]
3056 b989b9d9 Ken Wehr
3057 b989b9d9 Ken Wehr
      for i in keyfiles:
3058 b989b9d9 Ken Wehr
        keyarray.append(utils.ReadFile(i))
3059 b989b9d9 Ken Wehr
3060 b989b9d9 Ken Wehr
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3061 b989b9d9 Ken Wehr
                                      keyarray[2], keyarray[3], keyarray[4],
3062 b989b9d9 Ken Wehr
                                      keyarray[5])
3063 b989b9d9 Ken Wehr
      result.Raise("Cannot transfer ssh keys to the new node")
3064 a8083063 Iustin Pop
3065 a8083063 Iustin Pop
    # Add node to our /etc/hosts, and add key to known_hosts
3066 b86a6bcd Guido Trotter
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3067 b86a6bcd Guido Trotter
      utils.AddHostToEtcHosts(new_node.name)
3068 c8a0948f Michael Hanselmann
3069 a8083063 Iustin Pop
    if new_node.secondary_ip != new_node.primary_ip:
3070 781de953 Iustin Pop
      result = self.rpc.call_node_has_ip_address(new_node.name,
3071 781de953 Iustin Pop
                                                 new_node.secondary_ip)
3072 4c4e4e1e Iustin Pop
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3073 045dd6d9 Iustin Pop
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3074 c2fc8250 Iustin Pop
      if not result.payload:
3075 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3076 f4bc1f2c Michael Hanselmann
                                 " you gave (%s). Please fix and re-run this"
3077 f4bc1f2c Michael Hanselmann
                                 " command." % new_node.secondary_ip)
3078 a8083063 Iustin Pop
3079 d6a02168 Michael Hanselmann
    node_verify_list = [self.cfg.GetMasterNode()]
3080 5c0527ed Guido Trotter
    node_verify_param = {
3081 f60759f7 Iustin Pop
      constants.NV_NODELIST: [node],
3082 5c0527ed Guido Trotter
      # TODO: do a node-net-test as well?
3083 5c0527ed Guido Trotter
    }
3084 5c0527ed Guido Trotter
3085 72737a7f Iustin Pop
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3086 72737a7f Iustin Pop
                                       self.cfg.GetClusterName())
3087 5c0527ed Guido Trotter
    for verifier in node_verify_list:
3088 4c4e4e1e Iustin Pop
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3089 f60759f7 Iustin Pop
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3090 6f68a739 Iustin Pop
      if nl_payload:
3091 6f68a739 Iustin Pop
        for failed in nl_payload:
3092 31821208 Iustin Pop
          feedback_fn("ssh/hostname verification failed"
3093 31821208 Iustin Pop
                      " (checking from %s): %s" %
3094 6f68a739 Iustin Pop
                      (verifier, nl_payload[failed]))
3095 5c0527ed Guido Trotter
        raise errors.OpExecError("ssh/hostname verification failed.")
3096 ff98055b Iustin Pop
3097 d8470559 Michael Hanselmann
    if self.op.readd:
3098 28eddce5 Guido Trotter
      _RedistributeAncillaryFiles(self)
3099 d8470559 Michael Hanselmann
      self.context.ReaddNode(new_node)
3100 a8ae3eb5 Iustin Pop
      # make sure we redistribute the config
3101 a4eae71f Michael Hanselmann
      self.cfg.Update(new_node, feedback_fn)
3102 a8ae3eb5 Iustin Pop
      # and make sure the new node will not have old files around
3103 a8ae3eb5 Iustin Pop
      if not new_node.master_candidate:
3104 a8ae3eb5 Iustin Pop
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3105 3cebe102 Michael Hanselmann
        msg = result.fail_msg
3106 a8ae3eb5 Iustin Pop
        if msg:
3107 a8ae3eb5 Iustin Pop
          self.LogWarning("Node failed to demote itself from master"
3108 a8ae3eb5 Iustin Pop
                          " candidate status: %s" % msg)
3109 d8470559 Michael Hanselmann
    else:
3110 035566e3 Iustin Pop
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3111 0debfb35 Guido Trotter
      self.context.AddNode(new_node, self.proc.GetECId())
3112 a8083063 Iustin Pop
3113 a8083063 Iustin Pop
3114 b31c8676 Iustin Pop
class LUSetNodeParams(LogicalUnit):
3115 b31c8676 Iustin Pop
  """Modifies the parameters of a node.
3116 b31c8676 Iustin Pop

3117 b31c8676 Iustin Pop
  """
3118 b31c8676 Iustin Pop
  HPATH = "node-modify"
3119 b31c8676 Iustin Pop
  HTYPE = constants.HTYPE_NODE
3120 b31c8676 Iustin Pop
  _OP_REQP = ["node_name"]
3121 b31c8676 Iustin Pop
  REQ_BGL = False
3122 b31c8676 Iustin Pop
3123 b31c8676 Iustin Pop
  def CheckArguments(self):
3124 b31c8676 Iustin Pop
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3125 b31c8676 Iustin Pop
    if node_name is None:
3126 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3127 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
3128 b31c8676 Iustin Pop
    self.op.node_name = node_name
3129 3a5ba66a Iustin Pop
    _CheckBooleanOpField(self.op, 'master_candidate')
3130 3a5ba66a Iustin Pop
    _CheckBooleanOpField(self.op, 'offline')
3131 c9d443ea Iustin Pop
    _CheckBooleanOpField(self.op, 'drained')
3132 c9d443ea Iustin Pop
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3133 c9d443ea Iustin Pop
    if all_mods.count(None) == 3:
3134 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Please pass at least one modification",
3135 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
3136 c9d443ea Iustin Pop
    if all_mods.count(True) > 1:
3137 c9d443ea Iustin Pop
      raise errors.OpPrereqError("Can't set the node into more than one"
3138 5c983ee5 Iustin Pop
                                 " state at the same time",
3139 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
3140 b31c8676 Iustin Pop
3141 b31c8676 Iustin Pop
  def ExpandNames(self):
3142 b31c8676 Iustin Pop
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3143 b31c8676 Iustin Pop
3144 b31c8676 Iustin Pop
  def BuildHooksEnv(self):
3145 b31c8676 Iustin Pop
    """Build hooks env.
3146 b31c8676 Iustin Pop

3147 b31c8676 Iustin Pop
    This runs on the master node.
3148 b31c8676 Iustin Pop

3149 b31c8676 Iustin Pop
    """
3150 b31c8676 Iustin Pop
    env = {
3151 b31c8676 Iustin Pop
      "OP_TARGET": self.op.node_name,
3152 b31c8676 Iustin Pop
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3153 3a5ba66a Iustin Pop
      "OFFLINE": str(self.op.offline),
3154 c9d443ea Iustin Pop
      "DRAINED": str(self.op.drained),
3155 b31c8676 Iustin Pop
      }
3156 b31c8676 Iustin Pop
    nl = [self.cfg.GetMasterNode(),
3157 b31c8676 Iustin Pop
          self.op.node_name]
3158 b31c8676 Iustin Pop
    return env, nl, nl
3159 b31c8676 Iustin Pop
3160 b31c8676 Iustin Pop
  def CheckPrereq(self):
3161 b31c8676 Iustin Pop
    """Check prerequisites.
3162 b31c8676 Iustin Pop

3163 b31c8676 Iustin Pop
    This only checks the instance list against the existing names.
3164 b31c8676 Iustin Pop

3165 b31c8676 Iustin Pop
    """
3166 3a5ba66a Iustin Pop
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3167 b31c8676 Iustin Pop
3168 97c61d46 Iustin Pop
    if (self.op.master_candidate is not None or
3169 97c61d46 Iustin Pop
        self.op.drained is not None or
3170 97c61d46 Iustin Pop
        self.op.offline is not None):
3171 97c61d46 Iustin Pop
      # we can't change the master's node flags
3172 97c61d46 Iustin Pop
      if self.op.node_name == self.cfg.GetMasterNode():
3173 97c61d46 Iustin Pop
        raise errors.OpPrereqError("The master role can be changed"
3174 5c983ee5 Iustin Pop
                                   " only via masterfailover",
3175 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
3176 97c61d46 Iustin Pop
3177 8fbf5ac7 Guido Trotter
    # Boolean value that tells us whether we're offlining or draining the node
3178 8fbf5ac7 Guido Trotter
    offline_or_drain = self.op.offline == True or self.op.drained == True
3179 3d9eb52b Guido Trotter
    deoffline_or_drain = self.op.offline == False or self.op.drained == False
3180 8fbf5ac7 Guido Trotter
3181 8fbf5ac7 Guido Trotter
    if (node.master_candidate and
3182 8fbf5ac7 Guido Trotter
        (self.op.master_candidate == False or offline_or_drain)):
3183 3e83dd48 Iustin Pop
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
3184 8fbf5ac7 Guido Trotter
      mc_now, mc_should, mc_max = self.cfg.GetMasterCandidateStats()
3185 8fbf5ac7 Guido Trotter
      if mc_now <= cp_size:
3186 3e83dd48 Iustin Pop
        msg = ("Not enough master candidates (desired"
3187 8fbf5ac7 Guido Trotter
               " %d, new value will be %d)" % (cp_size, mc_now-1))
3188 8fbf5ac7 Guido Trotter
        # Only allow forcing the operation if it's an offline/drain operation,
3189 8fbf5ac7 Guido Trotter
        # and we could not possibly promote more nodes.
3190 8fbf5ac7 Guido Trotter
        # FIXME: this can still lead to issues if in any way another node which
3191 8fbf5ac7 Guido Trotter
        # could be promoted appears in the meantime.
3192 8fbf5ac7 Guido Trotter
        if self.op.force and offline_or_drain and mc_should == mc_max:
3193 3e83dd48 Iustin Pop
          self.LogWarning(msg)
3194 3e83dd48 Iustin Pop
        else:
3195 5c983ee5 Iustin Pop
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3196 3e83dd48 Iustin Pop
3197 c9d443ea Iustin Pop
    if (self.op.master_candidate == True and
3198 c9d443ea Iustin Pop
        ((node.offline and not self.op.offline == False) or
3199 c9d443ea Iustin Pop
         (node.drained and not self.op.drained == False))):
3200 c9d443ea Iustin Pop
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3201 5c983ee5 Iustin Pop
                                 " to master_candidate" % node.name,
3202 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
3203 3a5ba66a Iustin Pop
3204 3d9eb52b Guido Trotter
    # If we're being deofflined/drained, we'll MC ourself if needed
3205 3d9eb52b Guido Trotter
    if (deoffline_or_drain and not offline_or_drain and not
3206 3d9eb52b Guido Trotter
        self.op.master_candidate == True):
3207 3d9eb52b Guido Trotter
      self.op.master_candidate = _DecideSelfPromotion(self)
3208 3d9eb52b Guido Trotter
      if self.op.master_candidate:
3209 3d9eb52b Guido Trotter
        self.LogInfo("Autopromoting node to master candidate")
3210 3d9eb52b Guido Trotter
3211 b31c8676 Iustin Pop
    return
3212 b31c8676 Iustin Pop
3213 b31c8676 Iustin Pop
  def Exec(self, feedback_fn):
3214 b31c8676 Iustin Pop
    """Modifies a node.
3215 b31c8676 Iustin Pop

3216 b31c8676 Iustin Pop
    """
3217 3a5ba66a Iustin Pop
    node = self.node
3218 b31c8676 Iustin Pop
3219 b31c8676 Iustin Pop
    result = []
3220 c9d443ea Iustin Pop
    changed_mc = False
3221 b31c8676 Iustin Pop
3222 3a5ba66a Iustin Pop
    if self.op.offline is not None:
3223 3a5ba66a Iustin Pop
      node.offline = self.op.offline
3224 3a5ba66a Iustin Pop
      result.append(("offline", str(self.op.offline)))
3225 c9d443ea Iustin Pop
      if self.op.offline == True:
3226 c9d443ea Iustin Pop
        if node.master_candidate:
3227 c9d443ea Iustin Pop
          node.master_candidate = False
3228 c9d443ea Iustin Pop
          changed_mc = True
3229 c9d443ea Iustin Pop
          result.append(("master_candidate", "auto-demotion due to offline"))
3230 c9d443ea Iustin Pop
        if node.drained:
3231 c9d443ea Iustin Pop
          node.drained = False
3232 c9d443ea Iustin Pop
          result.append(("drained", "clear drained status due to offline"))
3233 3a5ba66a Iustin Pop
3234 b31c8676 Iustin Pop
    if self.op.master_candidate is not None:
3235 b31c8676 Iustin Pop
      node.master_candidate = self.op.master_candidate
3236 c9d443ea Iustin Pop
      changed_mc = True
3237 b31c8676 Iustin Pop
      result.append(("master_candidate", str(self.op.master_candidate)))
3238 56aa9fd5 Iustin Pop
      if self.op.master_candidate == False:
3239 56aa9fd5 Iustin Pop
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3240 4c4e4e1e Iustin Pop
        msg = rrc.fail_msg
3241 0959c824 Iustin Pop
        if msg:
3242 0959c824 Iustin Pop
          self.LogWarning("Node failed to demote itself: %s" % msg)
3243 b31c8676 Iustin Pop
3244 c9d443ea Iustin Pop
    if self.op.drained is not None:
3245 c9d443ea Iustin Pop
      node.drained = self.op.drained
3246 82e12743 Iustin Pop
      result.append(("drained", str(self.op.drained)))
3247 c9d443ea Iustin Pop
      if self.op.drained == True:
3248 c9d443ea Iustin Pop
        if node.master_candidate:
3249 c9d443ea Iustin Pop
          node.master_candidate = False
3250 c9d443ea Iustin Pop
          changed_mc = True
3251 c9d443ea Iustin Pop
          result.append(("master_candidate", "auto-demotion due to drain"))
3252 dec0d9da Iustin Pop
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3253 3cebe102 Michael Hanselmann
          msg = rrc.fail_msg
3254 dec0d9da Iustin Pop
          if msg:
3255 dec0d9da Iustin Pop
            self.LogWarning("Node failed to demote itself: %s" % msg)
3256 c9d443ea Iustin Pop
        if node.offline:
3257 c9d443ea Iustin Pop
          node.offline = False
3258 c9d443ea Iustin Pop
          result.append(("offline", "clear offline status due to drain"))
3259 c9d443ea Iustin Pop
3260 b31c8676 Iustin Pop
    # this will trigger configuration file update, if needed
3261 a4eae71f Michael Hanselmann
    self.cfg.Update(node, feedback_fn)
3262 b31c8676 Iustin Pop
    # this will trigger job queue propagation or cleanup
3263 c9d443ea Iustin Pop
    if changed_mc:
3264 3a26773f Iustin Pop
      self.context.ReaddNode(node)
3265 b31c8676 Iustin Pop
3266 b31c8676 Iustin Pop
    return result
3267 b31c8676 Iustin Pop
3268 b31c8676 Iustin Pop
3269 f5118ade Iustin Pop
class LUPowercycleNode(NoHooksLU):
3270 f5118ade Iustin Pop
  """Powercycles a node.
3271 f5118ade Iustin Pop

3272 f5118ade Iustin Pop
  """
3273 f5118ade Iustin Pop
  _OP_REQP = ["node_name", "force"]
3274 f5118ade Iustin Pop
  REQ_BGL = False
3275 f5118ade Iustin Pop
3276 f5118ade Iustin Pop
  def CheckArguments(self):
3277 f5118ade Iustin Pop
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
3278 f5118ade Iustin Pop
    if node_name is None:
3279 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
3280 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
3281 f5118ade Iustin Pop
    self.op.node_name = node_name
3282 f5118ade Iustin Pop
    if node_name == self.cfg.GetMasterNode() and not self.op.force:
3283 f5118ade Iustin Pop
      raise errors.OpPrereqError("The node is the master and the force"
3284 5c983ee5 Iustin Pop
                                 " parameter was not set",
3285 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
3286 f5118ade Iustin Pop
3287 f5118ade Iustin Pop
  def ExpandNames(self):
3288 f5118ade Iustin Pop
    """Locking for PowercycleNode.
3289 f5118ade Iustin Pop

3290 efb8da02 Michael Hanselmann
    This is a last-resort option and shouldn't block on other
3291 f5118ade Iustin Pop
    jobs. Therefore, we grab no locks.
3292 f5118ade Iustin Pop

3293 f5118ade Iustin Pop
    """
3294 f5118ade Iustin Pop
    self.needed_locks = {}
3295 f5118ade Iustin Pop
3296 f5118ade Iustin Pop
  def CheckPrereq(self):
3297 f5118ade Iustin Pop
    """Check prerequisites.
3298 f5118ade Iustin Pop

3299 f5118ade Iustin Pop
    This LU has no prereqs.
3300 f5118ade Iustin Pop

3301 f5118ade Iustin Pop
    """
3302 f5118ade Iustin Pop
    pass
3303 f5118ade Iustin Pop
3304 f5118ade Iustin Pop
  def Exec(self, feedback_fn):
3305 f5118ade Iustin Pop
    """Reboots a node.
3306 f5118ade Iustin Pop

3307 f5118ade Iustin Pop
    """
3308 f5118ade Iustin Pop
    result = self.rpc.call_node_powercycle(self.op.node_name,
3309 f5118ade Iustin Pop
                                           self.cfg.GetHypervisorType())
3310 4c4e4e1e Iustin Pop
    result.Raise("Failed to schedule the reboot")
3311 f5118ade Iustin Pop
    return result.payload
3312 f5118ade Iustin Pop
3313 f5118ade Iustin Pop
3314 a8083063 Iustin Pop
class LUQueryClusterInfo(NoHooksLU):
3315 a8083063 Iustin Pop
  """Query cluster configuration.
3316 a8083063 Iustin Pop

3317 a8083063 Iustin Pop
  """
3318 a8083063 Iustin Pop
  _OP_REQP = []
3319 642339cf Guido Trotter
  REQ_BGL = False
3320 642339cf Guido Trotter
3321 642339cf Guido Trotter
  def ExpandNames(self):
3322 642339cf Guido Trotter
    self.needed_locks = {}
3323 a8083063 Iustin Pop
3324 a8083063 Iustin Pop
  def CheckPrereq(self):
3325 a8083063 Iustin Pop
    """No prerequsites needed for this LU.
3326 a8083063 Iustin Pop

3327 a8083063 Iustin Pop
    """
3328 a8083063 Iustin Pop
    pass
3329 a8083063 Iustin Pop
3330 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3331 a8083063 Iustin Pop
    """Return cluster config.
3332 a8083063 Iustin Pop

3333 a8083063 Iustin Pop
    """
3334 469f88e1 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
3335 a8083063 Iustin Pop
    result = {
3336 a8083063 Iustin Pop
      "software_version": constants.RELEASE_VERSION,
3337 a8083063 Iustin Pop
      "protocol_version": constants.PROTOCOL_VERSION,
3338 a8083063 Iustin Pop
      "config_version": constants.CONFIG_VERSION,
3339 d1a7d66f Guido Trotter
      "os_api_version": max(constants.OS_API_VERSIONS),
3340 a8083063 Iustin Pop
      "export_version": constants.EXPORT_VERSION,
3341 a8083063 Iustin Pop
      "architecture": (platform.architecture()[0], platform.machine()),
3342 469f88e1 Iustin Pop
      "name": cluster.cluster_name,
3343 469f88e1 Iustin Pop
      "master": cluster.master_node,
3344 066f465d Guido Trotter
      "default_hypervisor": cluster.enabled_hypervisors[0],
3345 469f88e1 Iustin Pop
      "enabled_hypervisors": cluster.enabled_hypervisors,
3346 b8810fec Michael Hanselmann
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3347 7c4d6c7b Michael Hanselmann
                        for hypervisor_name in cluster.enabled_hypervisors]),
3348 469f88e1 Iustin Pop
      "beparams": cluster.beparams,
3349 1094acda Guido Trotter
      "nicparams": cluster.nicparams,
3350 4b7735f9 Iustin Pop
      "candidate_pool_size": cluster.candidate_pool_size,
3351 7a56b411 Guido Trotter
      "master_netdev": cluster.master_netdev,
3352 7a56b411 Guido Trotter
      "volume_group_name": cluster.volume_group_name,
3353 7a56b411 Guido Trotter
      "file_storage_dir": cluster.file_storage_dir,
3354 90f72445 Iustin Pop
      "ctime": cluster.ctime,
3355 90f72445 Iustin Pop
      "mtime": cluster.mtime,
3356 259578eb Iustin Pop
      "uuid": cluster.uuid,
3357 c118d1f4 Michael Hanselmann
      "tags": list(cluster.GetTags()),
3358 a8083063 Iustin Pop
      }
3359 a8083063 Iustin Pop
3360 a8083063 Iustin Pop
    return result
3361 a8083063 Iustin Pop
3362 a8083063 Iustin Pop
3363 ae5849b5 Michael Hanselmann
class LUQueryConfigValues(NoHooksLU):
3364 ae5849b5 Michael Hanselmann
  """Return configuration values.
3365 a8083063 Iustin Pop

3366 a8083063 Iustin Pop
  """
3367 a8083063 Iustin Pop
  _OP_REQP = []
3368 642339cf Guido Trotter
  REQ_BGL = False
3369 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet()
3370 05e50653 Michael Hanselmann
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3371 05e50653 Michael Hanselmann
                                  "watcher_pause")
3372 642339cf Guido Trotter
3373 642339cf Guido Trotter
  def ExpandNames(self):
3374 642339cf Guido Trotter
    self.needed_locks = {}
3375 a8083063 Iustin Pop
3376 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
3377 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
3378 ae5849b5 Michael Hanselmann
                       selected=self.op.output_fields)
3379 ae5849b5 Michael Hanselmann
3380 a8083063 Iustin Pop
  def CheckPrereq(self):
3381 a8083063 Iustin Pop
    """No prerequisites.
3382 a8083063 Iustin Pop

3383 a8083063 Iustin Pop
    """
3384 a8083063 Iustin Pop
    pass
3385 a8083063 Iustin Pop
3386 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3387 a8083063 Iustin Pop
    """Dump a representation of the cluster config to the standard output.
3388 a8083063 Iustin Pop

3389 a8083063 Iustin Pop
    """
3390 ae5849b5 Michael Hanselmann
    values = []
3391 ae5849b5 Michael Hanselmann
    for field in self.op.output_fields:
3392 ae5849b5 Michael Hanselmann
      if field == "cluster_name":
3393 3ccafd0e Iustin Pop
        entry = self.cfg.GetClusterName()
3394 ae5849b5 Michael Hanselmann
      elif field == "master_node":
3395 3ccafd0e Iustin Pop
        entry = self.cfg.GetMasterNode()
3396 3ccafd0e Iustin Pop
      elif field == "drain_flag":
3397 3ccafd0e Iustin Pop
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3398 05e50653 Michael Hanselmann
      elif field == "watcher_pause":
3399 05e50653 Michael Hanselmann
        return utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3400 ae5849b5 Michael Hanselmann
      else:
3401 ae5849b5 Michael Hanselmann
        raise errors.ParameterError(field)
3402 3ccafd0e Iustin Pop
      values.append(entry)
3403 ae5849b5 Michael Hanselmann
    return values
3404 a8083063 Iustin Pop
3405 a8083063 Iustin Pop
3406 a8083063 Iustin Pop
class LUActivateInstanceDisks(NoHooksLU):
3407 a8083063 Iustin Pop
  """Bring up an instance's disks.
3408 a8083063 Iustin Pop

3409 a8083063 Iustin Pop
  """
3410 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
3411 f22a8ba3 Guido Trotter
  REQ_BGL = False
3412 f22a8ba3 Guido Trotter
3413 f22a8ba3 Guido Trotter
  def ExpandNames(self):
3414 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
3415 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
3416 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3417 f22a8ba3 Guido Trotter
3418 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
3419 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
3420 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
3421 a8083063 Iustin Pop
3422 a8083063 Iustin Pop
  def CheckPrereq(self):
3423 a8083063 Iustin Pop
    """Check prerequisites.
3424 a8083063 Iustin Pop

3425 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3426 a8083063 Iustin Pop

3427 a8083063 Iustin Pop
    """
3428 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3429 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
3430 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3431 43017d26 Iustin Pop
    _CheckNodeOnline(self, self.instance.primary_node)
3432 b4ec07f8 Iustin Pop
    if not hasattr(self.op, "ignore_size"):
3433 b4ec07f8 Iustin Pop
      self.op.ignore_size = False
3434 a8083063 Iustin Pop
3435 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3436 a8083063 Iustin Pop
    """Activate the disks.
3437 a8083063 Iustin Pop

3438 a8083063 Iustin Pop
    """
3439 b4ec07f8 Iustin Pop
    disks_ok, disks_info = \
3440 b4ec07f8 Iustin Pop
              _AssembleInstanceDisks(self, self.instance,
3441 b4ec07f8 Iustin Pop
                                     ignore_size=self.op.ignore_size)
3442 a8083063 Iustin Pop
    if not disks_ok:
3443 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot activate block devices")
3444 a8083063 Iustin Pop
3445 a8083063 Iustin Pop
    return disks_info
3446 a8083063 Iustin Pop
3447 a8083063 Iustin Pop
3448 e3443b36 Iustin Pop
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3449 e3443b36 Iustin Pop
                           ignore_size=False):
3450 a8083063 Iustin Pop
  """Prepare the block devices for an instance.
3451 a8083063 Iustin Pop

3452 a8083063 Iustin Pop
  This sets up the block devices on all nodes.
3453 a8083063 Iustin Pop

3454 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
3455 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
3456 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
3457 e4376078 Iustin Pop
  @param instance: the instance for whose disks we assemble
3458 e4376078 Iustin Pop
  @type ignore_secondaries: boolean
3459 e4376078 Iustin Pop
  @param ignore_secondaries: if true, errors on secondary nodes
3460 e4376078 Iustin Pop
      won't result in an error return from the function
3461 e3443b36 Iustin Pop
  @type ignore_size: boolean
3462 e3443b36 Iustin Pop
  @param ignore_size: if true, the current known size of the disk
3463 e3443b36 Iustin Pop
      will not be used during the disk activation, useful for cases
3464 e3443b36 Iustin Pop
      when the size is wrong
3465 e4376078 Iustin Pop
  @return: False if the operation failed, otherwise a list of
3466 e4376078 Iustin Pop
      (host, instance_visible_name, node_visible_name)
3467 e4376078 Iustin Pop
      with the mapping from node devices to instance devices
3468 a8083063 Iustin Pop

3469 a8083063 Iustin Pop
  """
3470 a8083063 Iustin Pop
  device_info = []
3471 a8083063 Iustin Pop
  disks_ok = True
3472 fdbd668d Iustin Pop
  iname = instance.name
3473 fdbd668d Iustin Pop
  # With the two passes mechanism we try to reduce the window of
3474 fdbd668d Iustin Pop
  # opportunity for the race condition of switching DRBD to primary
3475 fdbd668d Iustin Pop
  # before handshaking occured, but we do not eliminate it
3476 fdbd668d Iustin Pop
3477 fdbd668d Iustin Pop
  # The proper fix would be to wait (with some limits) until the
3478 fdbd668d Iustin Pop
  # connection has been made and drbd transitions from WFConnection
3479 fdbd668d Iustin Pop
  # into any other network-connected state (Connected, SyncTarget,
3480 fdbd668d Iustin Pop
  # SyncSource, etc.)
3481 fdbd668d Iustin Pop
3482 fdbd668d Iustin Pop
  # 1st pass, assemble on all nodes in secondary mode
3483 a8083063 Iustin Pop
  for inst_disk in instance.disks:
3484 a8083063 Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3485 e3443b36 Iustin Pop
      if ignore_size:
3486 e3443b36 Iustin Pop
        node_disk = node_disk.Copy()
3487 e3443b36 Iustin Pop
        node_disk.UnsetSize()
3488 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(node_disk, node)
3489 72737a7f Iustin Pop
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3490 4c4e4e1e Iustin Pop
      msg = result.fail_msg
3491 53c14ef1 Iustin Pop
      if msg:
3492 86d9d3bb Iustin Pop
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3493 53c14ef1 Iustin Pop
                           " (is_primary=False, pass=1): %s",
3494 53c14ef1 Iustin Pop
                           inst_disk.iv_name, node, msg)
3495 fdbd668d Iustin Pop
        if not ignore_secondaries:
3496 a8083063 Iustin Pop
          disks_ok = False
3497 fdbd668d Iustin Pop
3498 fdbd668d Iustin Pop
  # FIXME: race condition on drbd migration to primary
3499 fdbd668d Iustin Pop
3500 fdbd668d Iustin Pop
  # 2nd pass, do only the primary node
3501 fdbd668d Iustin Pop
  for inst_disk in instance.disks:
3502 d52ea991 Michael Hanselmann
    dev_path = None
3503 d52ea991 Michael Hanselmann
3504 fdbd668d Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3505 fdbd668d Iustin Pop
      if node != instance.primary_node:
3506 fdbd668d Iustin Pop
        continue
3507 e3443b36 Iustin Pop
      if ignore_size:
3508 e3443b36 Iustin Pop
        node_disk = node_disk.Copy()
3509 e3443b36 Iustin Pop
        node_disk.UnsetSize()
3510 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(node_disk, node)
3511 72737a7f Iustin Pop
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3512 4c4e4e1e Iustin Pop
      msg = result.fail_msg
3513 53c14ef1 Iustin Pop
      if msg:
3514 86d9d3bb Iustin Pop
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3515 53c14ef1 Iustin Pop
                           " (is_primary=True, pass=2): %s",
3516 53c14ef1 Iustin Pop
                           inst_disk.iv_name, node, msg)
3517 fdbd668d Iustin Pop
        disks_ok = False
3518 d52ea991 Michael Hanselmann
      else:
3519 d52ea991 Michael Hanselmann
        dev_path = result.payload
3520 d52ea991 Michael Hanselmann
3521 d52ea991 Michael Hanselmann
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3522 a8083063 Iustin Pop
3523 b352ab5b Iustin Pop
  # leave the disks configured for the primary node
3524 b352ab5b Iustin Pop
  # this is a workaround that would be fixed better by
3525 b352ab5b Iustin Pop
  # improving the logical/physical id handling
3526 b352ab5b Iustin Pop
  for disk in instance.disks:
3527 b9bddb6b Iustin Pop
    lu.cfg.SetDiskID(disk, instance.primary_node)
3528 b352ab5b Iustin Pop
3529 a8083063 Iustin Pop
  return disks_ok, device_info
3530 a8083063 Iustin Pop
3531 a8083063 Iustin Pop
3532 b9bddb6b Iustin Pop
def _StartInstanceDisks(lu, instance, force):
3533 3ecf6786 Iustin Pop
  """Start the disks of an instance.
3534 3ecf6786 Iustin Pop

3535 3ecf6786 Iustin Pop
  """
3536 7c4d6c7b Michael Hanselmann
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3537 fe7b0351 Michael Hanselmann
                                           ignore_secondaries=force)
3538 fe7b0351 Michael Hanselmann
  if not disks_ok:
3539 b9bddb6b Iustin Pop
    _ShutdownInstanceDisks(lu, instance)
3540 fe7b0351 Michael Hanselmann
    if force is not None and not force:
3541 86d9d3bb Iustin Pop
      lu.proc.LogWarning("", hint="If the message above refers to a"
3542 86d9d3bb Iustin Pop
                         " secondary node,"
3543 86d9d3bb Iustin Pop
                         " you can retry the operation using '--force'.")
3544 3ecf6786 Iustin Pop
    raise errors.OpExecError("Disk consistency error")
3545 fe7b0351 Michael Hanselmann
3546 fe7b0351 Michael Hanselmann
3547 a8083063 Iustin Pop
class LUDeactivateInstanceDisks(NoHooksLU):
3548 a8083063 Iustin Pop
  """Shutdown an instance's disks.
3549 a8083063 Iustin Pop

3550 a8083063 Iustin Pop
  """
3551 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
3552 f22a8ba3 Guido Trotter
  REQ_BGL = False
3553 f22a8ba3 Guido Trotter
3554 f22a8ba3 Guido Trotter
  def ExpandNames(self):
3555 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
3556 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
3557 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3558 f22a8ba3 Guido Trotter
3559 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
3560 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
3561 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
3562 a8083063 Iustin Pop
3563 a8083063 Iustin Pop
  def CheckPrereq(self):
3564 a8083063 Iustin Pop
    """Check prerequisites.
3565 a8083063 Iustin Pop

3566 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3567 a8083063 Iustin Pop

3568 a8083063 Iustin Pop
    """
3569 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3570 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
3571 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3572 a8083063 Iustin Pop
3573 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3574 a8083063 Iustin Pop
    """Deactivate the disks
3575 a8083063 Iustin Pop

3576 a8083063 Iustin Pop
    """
3577 a8083063 Iustin Pop
    instance = self.instance
3578 b9bddb6b Iustin Pop
    _SafeShutdownInstanceDisks(self, instance)
3579 a8083063 Iustin Pop
3580 a8083063 Iustin Pop
3581 b9bddb6b Iustin Pop
def _SafeShutdownInstanceDisks(lu, instance):
3582 155d6c75 Guido Trotter
  """Shutdown block devices of an instance.
3583 155d6c75 Guido Trotter

3584 155d6c75 Guido Trotter
  This function checks if an instance is running, before calling
3585 155d6c75 Guido Trotter
  _ShutdownInstanceDisks.
3586 155d6c75 Guido Trotter

3587 155d6c75 Guido Trotter
  """
3588 aca13712 Iustin Pop
  pnode = instance.primary_node
3589 4c4e4e1e Iustin Pop
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
3590 4c4e4e1e Iustin Pop
  ins_l.Raise("Can't contact node %s" % pnode)
3591 aca13712 Iustin Pop
3592 aca13712 Iustin Pop
  if instance.name in ins_l.payload:
3593 155d6c75 Guido Trotter
    raise errors.OpExecError("Instance is running, can't shutdown"
3594 155d6c75 Guido Trotter
                             " block devices.")
3595 155d6c75 Guido Trotter
3596 b9bddb6b Iustin Pop
  _ShutdownInstanceDisks(lu, instance)
3597 a8083063 Iustin Pop
3598 a8083063 Iustin Pop
3599 b9bddb6b Iustin Pop
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3600 a8083063 Iustin Pop
  """Shutdown block devices of an instance.
3601 a8083063 Iustin Pop

3602 a8083063 Iustin Pop
  This does the shutdown on all nodes of the instance.
3603 a8083063 Iustin Pop

3604 a8083063 Iustin Pop
  If the ignore_primary is false, errors on the primary node are
3605 a8083063 Iustin Pop
  ignored.
3606 a8083063 Iustin Pop

3607 a8083063 Iustin Pop
  """
3608 cacfd1fd Iustin Pop
  all_result = True
3609 a8083063 Iustin Pop
  for disk in instance.disks:
3610 a8083063 Iustin Pop
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
3611 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(top_disk, node)
3612 781de953 Iustin Pop
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
3613 4c4e4e1e Iustin Pop
      msg = result.fail_msg
3614 cacfd1fd Iustin Pop
      if msg:
3615 cacfd1fd Iustin Pop
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
3616 cacfd1fd Iustin Pop
                      disk.iv_name, node, msg)
3617 a8083063 Iustin Pop
        if not ignore_primary or node != instance.primary_node:
3618 cacfd1fd Iustin Pop
          all_result = False
3619 cacfd1fd Iustin Pop
  return all_result
3620 a8083063 Iustin Pop
3621 a8083063 Iustin Pop
3622 9ca87a96 Iustin Pop
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
3623 d4f16fd9 Iustin Pop
  """Checks if a node has enough free memory.
3624 d4f16fd9 Iustin Pop

3625 d4f16fd9 Iustin Pop
  This function check if a given node has the needed amount of free
3626 d4f16fd9 Iustin Pop
  memory. In case the node has less memory or we cannot get the
3627 d4f16fd9 Iustin Pop
  information from the node, this function raise an OpPrereqError
3628 d4f16fd9 Iustin Pop
  exception.
3629 d4f16fd9 Iustin Pop

3630 b9bddb6b Iustin Pop
  @type lu: C{LogicalUnit}
3631 b9bddb6b Iustin Pop
  @param lu: a logical unit from which we get configuration data
3632 e69d05fd Iustin Pop
  @type node: C{str}
3633 e69d05fd Iustin Pop
  @param node: the node to check
3634 e69d05fd Iustin Pop
  @type reason: C{str}
3635 e69d05fd Iustin Pop
  @param reason: string to use in the error message
3636 e69d05fd Iustin Pop
  @type requested: C{int}
3637 e69d05fd Iustin Pop
  @param requested: the amount of memory in MiB to check for
3638 9ca87a96 Iustin Pop
  @type hypervisor_name: C{str}
3639 9ca87a96 Iustin Pop
  @param hypervisor_name: the hypervisor to ask for memory stats
3640 e69d05fd Iustin Pop
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
3641 e69d05fd Iustin Pop
      we cannot check the node
3642 d4f16fd9 Iustin Pop

3643 d4f16fd9 Iustin Pop
  """
3644 9ca87a96 Iustin Pop
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
3645 045dd6d9 Iustin Pop
  nodeinfo[node].Raise("Can't get data from node %s" % node,
3646 045dd6d9 Iustin Pop
                       prereq=True, ecode=errors.ECODE_ENVIRON)
3647 070e998b Iustin Pop
  free_mem = nodeinfo[node].payload.get('memory_free', None)
3648 d4f16fd9 Iustin Pop
  if not isinstance(free_mem, int):
3649 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
3650 5c983ee5 Iustin Pop
                               " was '%s'" % (node, free_mem),
3651 5c983ee5 Iustin Pop
                               errors.ECODE_ENVIRON)
3652 d4f16fd9 Iustin Pop
  if requested > free_mem:
3653 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
3654 070e998b Iustin Pop
                               " needed %s MiB, available %s MiB" %
3655 5c983ee5 Iustin Pop
                               (node, reason, requested, free_mem),
3656 5c983ee5 Iustin Pop
                               errors.ECODE_NORES)
3657 d4f16fd9 Iustin Pop
3658 d4f16fd9 Iustin Pop
3659 a8083063 Iustin Pop
class LUStartupInstance(LogicalUnit):
3660 a8083063 Iustin Pop
  """Starts an instance.
3661 a8083063 Iustin Pop

3662 a8083063 Iustin Pop
  """
3663 a8083063 Iustin Pop
  HPATH = "instance-start"
3664 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3665 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "force"]
3666 e873317a Guido Trotter
  REQ_BGL = False
3667 e873317a Guido Trotter
3668 e873317a Guido Trotter
  def ExpandNames(self):
3669 e873317a Guido Trotter
    self._ExpandAndLockInstance()
3670 a8083063 Iustin Pop
3671 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3672 a8083063 Iustin Pop
    """Build hooks env.
3673 a8083063 Iustin Pop

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

3676 a8083063 Iustin Pop
    """
3677 a8083063 Iustin Pop
    env = {
3678 a8083063 Iustin Pop
      "FORCE": self.op.force,
3679 a8083063 Iustin Pop
      }
3680 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3681 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3682 a8083063 Iustin Pop
    return env, nl, nl
3683 a8083063 Iustin Pop
3684 a8083063 Iustin Pop
  def CheckPrereq(self):
3685 a8083063 Iustin Pop
    """Check prerequisites.
3686 a8083063 Iustin Pop

3687 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3688 a8083063 Iustin Pop

3689 a8083063 Iustin Pop
    """
3690 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3691 e873317a Guido Trotter
    assert self.instance is not None, \
3692 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3693 a8083063 Iustin Pop
3694 d04aaa2f Iustin Pop
    # extra beparams
3695 d04aaa2f Iustin Pop
    self.beparams = getattr(self.op, "beparams", {})
3696 d04aaa2f Iustin Pop
    if self.beparams:
3697 d04aaa2f Iustin Pop
      if not isinstance(self.beparams, dict):
3698 d04aaa2f Iustin Pop
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
3699 5c983ee5 Iustin Pop
                                   " dict" % (type(self.beparams), ),
3700 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
3701 d04aaa2f Iustin Pop
      # fill the beparams dict
3702 d04aaa2f Iustin Pop
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
3703 d04aaa2f Iustin Pop
      self.op.beparams = self.beparams
3704 d04aaa2f Iustin Pop
3705 d04aaa2f Iustin Pop
    # extra hvparams
3706 d04aaa2f Iustin Pop
    self.hvparams = getattr(self.op, "hvparams", {})
3707 d04aaa2f Iustin Pop
    if self.hvparams:
3708 d04aaa2f Iustin Pop
      if not isinstance(self.hvparams, dict):
3709 d04aaa2f Iustin Pop
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
3710 5c983ee5 Iustin Pop
                                   " dict" % (type(self.hvparams), ),
3711 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
3712 d04aaa2f Iustin Pop
3713 d04aaa2f Iustin Pop
      # check hypervisor parameter syntax (locally)
3714 d04aaa2f Iustin Pop
      cluster = self.cfg.GetClusterInfo()
3715 d04aaa2f Iustin Pop
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
3716 abe609b2 Guido Trotter
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
3717 d04aaa2f Iustin Pop
                                    instance.hvparams)
3718 d04aaa2f Iustin Pop
      filled_hvp.update(self.hvparams)
3719 d04aaa2f Iustin Pop
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
3720 d04aaa2f Iustin Pop
      hv_type.CheckParameterSyntax(filled_hvp)
3721 d04aaa2f Iustin Pop
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
3722 d04aaa2f Iustin Pop
      self.op.hvparams = self.hvparams
3723 d04aaa2f Iustin Pop
3724 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
3725 7527a8a4 Iustin Pop
3726 338e51e8 Iustin Pop
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3727 5bbd3f7f Michael Hanselmann
    # check bridges existence
3728 b9bddb6b Iustin Pop
    _CheckInstanceBridgesExist(self, instance)
3729 a8083063 Iustin Pop
3730 f1926756 Guido Trotter
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3731 f1926756 Guido Trotter
                                              instance.name,
3732 f1926756 Guido Trotter
                                              instance.hypervisor)
3733 4c4e4e1e Iustin Pop
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3734 045dd6d9 Iustin Pop
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3735 7ad1af4a Iustin Pop
    if not remote_info.payload: # not running already
3736 f1926756 Guido Trotter
      _CheckNodeFreeMemory(self, instance.primary_node,
3737 f1926756 Guido Trotter
                           "starting instance %s" % instance.name,
3738 f1926756 Guido Trotter
                           bep[constants.BE_MEMORY], instance.hypervisor)
3739 d4f16fd9 Iustin Pop
3740 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3741 a8083063 Iustin Pop
    """Start the instance.
3742 a8083063 Iustin Pop

3743 a8083063 Iustin Pop
    """
3744 a8083063 Iustin Pop
    instance = self.instance
3745 a8083063 Iustin Pop
    force = self.op.force
3746 a8083063 Iustin Pop
3747 fe482621 Iustin Pop
    self.cfg.MarkInstanceUp(instance.name)
3748 fe482621 Iustin Pop
3749 a8083063 Iustin Pop
    node_current = instance.primary_node
3750 a8083063 Iustin Pop
3751 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, instance, force)
3752 a8083063 Iustin Pop
3753 d04aaa2f Iustin Pop
    result = self.rpc.call_instance_start(node_current, instance,
3754 d04aaa2f Iustin Pop
                                          self.hvparams, self.beparams)
3755 4c4e4e1e Iustin Pop
    msg = result.fail_msg
3756 dd279568 Iustin Pop
    if msg:
3757 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, instance)
3758 dd279568 Iustin Pop
      raise errors.OpExecError("Could not start instance: %s" % msg)
3759 a8083063 Iustin Pop
3760 a8083063 Iustin Pop
3761 bf6929a2 Alexander Schreiber
class LURebootInstance(LogicalUnit):
3762 bf6929a2 Alexander Schreiber
  """Reboot an instance.
3763 bf6929a2 Alexander Schreiber

3764 bf6929a2 Alexander Schreiber
  """
3765 bf6929a2 Alexander Schreiber
  HPATH = "instance-reboot"
3766 bf6929a2 Alexander Schreiber
  HTYPE = constants.HTYPE_INSTANCE
3767 bf6929a2 Alexander Schreiber
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
3768 e873317a Guido Trotter
  REQ_BGL = False
3769 e873317a Guido Trotter
3770 17c3f802 Guido Trotter
  def CheckArguments(self):
3771 17c3f802 Guido Trotter
    """Check the arguments.
3772 17c3f802 Guido Trotter

3773 17c3f802 Guido Trotter
    """
3774 17c3f802 Guido Trotter
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
3775 17c3f802 Guido Trotter
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
3776 17c3f802 Guido Trotter
3777 e873317a Guido Trotter
  def ExpandNames(self):
3778 0fcc5db3 Guido Trotter
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
3779 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
3780 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL]:
3781 0fcc5db3 Guido Trotter
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
3782 0fcc5db3 Guido Trotter
                                  (constants.INSTANCE_REBOOT_SOFT,
3783 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
3784 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL))
3785 e873317a Guido Trotter
    self._ExpandAndLockInstance()
3786 bf6929a2 Alexander Schreiber
3787 bf6929a2 Alexander Schreiber
  def BuildHooksEnv(self):
3788 bf6929a2 Alexander Schreiber
    """Build hooks env.
3789 bf6929a2 Alexander Schreiber

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

3792 bf6929a2 Alexander Schreiber
    """
3793 bf6929a2 Alexander Schreiber
    env = {
3794 bf6929a2 Alexander Schreiber
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
3795 2c2690c9 Iustin Pop
      "REBOOT_TYPE": self.op.reboot_type,
3796 17c3f802 Guido Trotter
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
3797 bf6929a2 Alexander Schreiber
      }
3798 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3799 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3800 bf6929a2 Alexander Schreiber
    return env, nl, nl
3801 bf6929a2 Alexander Schreiber
3802 bf6929a2 Alexander Schreiber
  def CheckPrereq(self):
3803 bf6929a2 Alexander Schreiber
    """Check prerequisites.
3804 bf6929a2 Alexander Schreiber

3805 bf6929a2 Alexander Schreiber
    This checks that the instance is in the cluster.
3806 bf6929a2 Alexander Schreiber

3807 bf6929a2 Alexander Schreiber
    """
3808 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3809 e873317a Guido Trotter
    assert self.instance is not None, \
3810 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3811 bf6929a2 Alexander Schreiber
3812 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
3813 7527a8a4 Iustin Pop
3814 5bbd3f7f Michael Hanselmann
    # check bridges existence
3815 b9bddb6b Iustin Pop
    _CheckInstanceBridgesExist(self, instance)
3816 bf6929a2 Alexander Schreiber
3817 bf6929a2 Alexander Schreiber
  def Exec(self, feedback_fn):
3818 bf6929a2 Alexander Schreiber
    """Reboot the instance.
3819 bf6929a2 Alexander Schreiber

3820 bf6929a2 Alexander Schreiber
    """
3821 bf6929a2 Alexander Schreiber
    instance = self.instance
3822 bf6929a2 Alexander Schreiber
    ignore_secondaries = self.op.ignore_secondaries
3823 bf6929a2 Alexander Schreiber
    reboot_type = self.op.reboot_type
3824 bf6929a2 Alexander Schreiber
3825 bf6929a2 Alexander Schreiber
    node_current = instance.primary_node
3826 bf6929a2 Alexander Schreiber
3827 bf6929a2 Alexander Schreiber
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
3828 bf6929a2 Alexander Schreiber
                       constants.INSTANCE_REBOOT_HARD]:
3829 ae48ac32 Iustin Pop
      for disk in instance.disks:
3830 ae48ac32 Iustin Pop
        self.cfg.SetDiskID(disk, node_current)
3831 781de953 Iustin Pop
      result = self.rpc.call_instance_reboot(node_current, instance,
3832 17c3f802 Guido Trotter
                                             reboot_type,
3833 17c3f802 Guido Trotter
                                             self.shutdown_timeout)
3834 4c4e4e1e Iustin Pop
      result.Raise("Could not reboot instance")
3835 bf6929a2 Alexander Schreiber
    else:
3836 17c3f802 Guido Trotter
      result = self.rpc.call_instance_shutdown(node_current, instance,
3837 17c3f802 Guido Trotter
                                               self.shutdown_timeout)
3838 4c4e4e1e Iustin Pop
      result.Raise("Could not shutdown instance for full reboot")
3839 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, instance)
3840 b9bddb6b Iustin Pop
      _StartInstanceDisks(self, instance, ignore_secondaries)
3841 0eca8e0c Iustin Pop
      result = self.rpc.call_instance_start(node_current, instance, None, None)
3842 4c4e4e1e Iustin Pop
      msg = result.fail_msg
3843 dd279568 Iustin Pop
      if msg:
3844 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
3845 dd279568 Iustin Pop
        raise errors.OpExecError("Could not start instance for"
3846 dd279568 Iustin Pop
                                 " full reboot: %s" % msg)
3847 bf6929a2 Alexander Schreiber
3848 bf6929a2 Alexander Schreiber
    self.cfg.MarkInstanceUp(instance.name)
3849 bf6929a2 Alexander Schreiber
3850 bf6929a2 Alexander Schreiber
3851 a8083063 Iustin Pop
class LUShutdownInstance(LogicalUnit):
3852 a8083063 Iustin Pop
  """Shutdown an instance.
3853 a8083063 Iustin Pop

3854 a8083063 Iustin Pop
  """
3855 a8083063 Iustin Pop
  HPATH = "instance-stop"
3856 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3857 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
3858 e873317a Guido Trotter
  REQ_BGL = False
3859 e873317a Guido Trotter
3860 6263189c Guido Trotter
  def CheckArguments(self):
3861 6263189c Guido Trotter
    """Check the arguments.
3862 6263189c Guido Trotter

3863 6263189c Guido Trotter
    """
3864 6263189c Guido Trotter
    self.timeout = getattr(self.op, "timeout",
3865 6263189c Guido Trotter
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
3866 6263189c Guido Trotter
3867 e873317a Guido Trotter
  def ExpandNames(self):
3868 e873317a Guido Trotter
    self._ExpandAndLockInstance()
3869 a8083063 Iustin Pop
3870 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3871 a8083063 Iustin Pop
    """Build hooks env.
3872 a8083063 Iustin Pop

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

3875 a8083063 Iustin Pop
    """
3876 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3877 6263189c Guido Trotter
    env["TIMEOUT"] = self.timeout
3878 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3879 a8083063 Iustin Pop
    return env, nl, nl
3880 a8083063 Iustin Pop
3881 a8083063 Iustin Pop
  def CheckPrereq(self):
3882 a8083063 Iustin Pop
    """Check prerequisites.
3883 a8083063 Iustin Pop

3884 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3885 a8083063 Iustin Pop

3886 a8083063 Iustin Pop
    """
3887 e873317a Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3888 e873317a Guido Trotter
    assert self.instance is not None, \
3889 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3890 43017d26 Iustin Pop
    _CheckNodeOnline(self, self.instance.primary_node)
3891 a8083063 Iustin Pop
3892 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3893 a8083063 Iustin Pop
    """Shutdown the instance.
3894 a8083063 Iustin Pop

3895 a8083063 Iustin Pop
    """
3896 a8083063 Iustin Pop
    instance = self.instance
3897 a8083063 Iustin Pop
    node_current = instance.primary_node
3898 6263189c Guido Trotter
    timeout = self.timeout
3899 fe482621 Iustin Pop
    self.cfg.MarkInstanceDown(instance.name)
3900 6263189c Guido Trotter
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
3901 4c4e4e1e Iustin Pop
    msg = result.fail_msg
3902 1fae010f Iustin Pop
    if msg:
3903 1fae010f Iustin Pop
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
3904 a8083063 Iustin Pop
3905 b9bddb6b Iustin Pop
    _ShutdownInstanceDisks(self, instance)
3906 a8083063 Iustin Pop
3907 a8083063 Iustin Pop
3908 fe7b0351 Michael Hanselmann
class LUReinstallInstance(LogicalUnit):
3909 fe7b0351 Michael Hanselmann
  """Reinstall an instance.
3910 fe7b0351 Michael Hanselmann

3911 fe7b0351 Michael Hanselmann
  """
3912 fe7b0351 Michael Hanselmann
  HPATH = "instance-reinstall"
3913 fe7b0351 Michael Hanselmann
  HTYPE = constants.HTYPE_INSTANCE
3914 fe7b0351 Michael Hanselmann
  _OP_REQP = ["instance_name"]
3915 4e0b4d2d Guido Trotter
  REQ_BGL = False
3916 4e0b4d2d Guido Trotter
3917 4e0b4d2d Guido Trotter
  def ExpandNames(self):
3918 4e0b4d2d Guido Trotter
    self._ExpandAndLockInstance()
3919 fe7b0351 Michael Hanselmann
3920 fe7b0351 Michael Hanselmann
  def BuildHooksEnv(self):
3921 fe7b0351 Michael Hanselmann
    """Build hooks env.
3922 fe7b0351 Michael Hanselmann

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

3925 fe7b0351 Michael Hanselmann
    """
3926 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3927 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
3928 fe7b0351 Michael Hanselmann
    return env, nl, nl
3929 fe7b0351 Michael Hanselmann
3930 fe7b0351 Michael Hanselmann
  def CheckPrereq(self):
3931 fe7b0351 Michael Hanselmann
    """Check prerequisites.
3932 fe7b0351 Michael Hanselmann

3933 fe7b0351 Michael Hanselmann
    This checks that the instance is in the cluster and is not running.
3934 fe7b0351 Michael Hanselmann

3935 fe7b0351 Michael Hanselmann
    """
3936 4e0b4d2d Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3937 4e0b4d2d Guido Trotter
    assert instance is not None, \
3938 4e0b4d2d Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3939 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
3940 4e0b4d2d Guido Trotter
3941 fe7b0351 Michael Hanselmann
    if instance.disk_template == constants.DT_DISKLESS:
3942 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' has no disks" %
3943 5c983ee5 Iustin Pop
                                 self.op.instance_name,
3944 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
3945 0d68c45d Iustin Pop
    if instance.admin_up:
3946 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
3947 5c983ee5 Iustin Pop
                                 self.op.instance_name,
3948 5c983ee5 Iustin Pop
                                 errors.ECODE_STATE)
3949 72737a7f Iustin Pop
    remote_info = self.rpc.call_instance_info(instance.primary_node,
3950 72737a7f Iustin Pop
                                              instance.name,
3951 72737a7f Iustin Pop
                                              instance.hypervisor)
3952 4c4e4e1e Iustin Pop
    remote_info.Raise("Error checking node %s" % instance.primary_node,
3953 045dd6d9 Iustin Pop
                      prereq=True, ecode=errors.ECODE_ENVIRON)
3954 7ad1af4a Iustin Pop
    if remote_info.payload:
3955 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
3956 3ecf6786 Iustin Pop
                                 (self.op.instance_name,
3957 5c983ee5 Iustin Pop
                                  instance.primary_node),
3958 5c983ee5 Iustin Pop
                                 errors.ECODE_STATE)
3959 d0834de3 Michael Hanselmann
3960 d0834de3 Michael Hanselmann
    self.op.os_type = getattr(self.op, "os_type", None)
3961 f2c05717 Guido Trotter
    self.op.force_variant = getattr(self.op, "force_variant", False)
3962 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
3963 d0834de3 Michael Hanselmann
      # OS verification
3964 d0834de3 Michael Hanselmann
      pnode = self.cfg.GetNodeInfo(
3965 d0834de3 Michael Hanselmann
        self.cfg.ExpandNodeName(instance.primary_node))
3966 d0834de3 Michael Hanselmann
      if pnode is None:
3967 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
3968 5c983ee5 Iustin Pop
                                   self.op.pnode, errors.ECODE_NOENT)
3969 781de953 Iustin Pop
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
3970 4c4e4e1e Iustin Pop
      result.Raise("OS '%s' not in supported OS list for primary node %s" %
3971 045dd6d9 Iustin Pop
                   (self.op.os_type, pnode.name),
3972 045dd6d9 Iustin Pop
                   prereq=True, ecode=errors.ECODE_INVAL)
3973 f2c05717 Guido Trotter
      if not self.op.force_variant:
3974 f2c05717 Guido Trotter
        _CheckOSVariant(result.payload, self.op.os_type)
3975 d0834de3 Michael Hanselmann
3976 fe7b0351 Michael Hanselmann
    self.instance = instance
3977 fe7b0351 Michael Hanselmann
3978 fe7b0351 Michael Hanselmann
  def Exec(self, feedback_fn):
3979 fe7b0351 Michael Hanselmann
    """Reinstall the instance.
3980 fe7b0351 Michael Hanselmann

3981 fe7b0351 Michael Hanselmann
    """
3982 fe7b0351 Michael Hanselmann
    inst = self.instance
3983 fe7b0351 Michael Hanselmann
3984 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
3985 d0834de3 Michael Hanselmann
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
3986 d0834de3 Michael Hanselmann
      inst.os = self.op.os_type
3987 a4eae71f Michael Hanselmann
      self.cfg.Update(inst, feedback_fn)
3988 d0834de3 Michael Hanselmann
3989 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, inst, None)
3990 fe7b0351 Michael Hanselmann
    try:
3991 fe7b0351 Michael Hanselmann
      feedback_fn("Running the instance OS create scripts...")
3992 e557bae9 Guido Trotter
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True)
3993 4c4e4e1e Iustin Pop
      result.Raise("Could not install OS for instance %s on node %s" %
3994 4c4e4e1e Iustin Pop
                   (inst.name, inst.primary_node))
3995 fe7b0351 Michael Hanselmann
    finally:
3996 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, inst)
3997 fe7b0351 Michael Hanselmann
3998 fe7b0351 Michael Hanselmann
3999 bd315bfa Iustin Pop
class LURecreateInstanceDisks(LogicalUnit):
4000 bd315bfa Iustin Pop
  """Recreate an instance's missing disks.
4001 bd315bfa Iustin Pop

4002 bd315bfa Iustin Pop
  """
4003 bd315bfa Iustin Pop
  HPATH = "instance-recreate-disks"
4004 bd315bfa Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4005 bd315bfa Iustin Pop
  _OP_REQP = ["instance_name", "disks"]
4006 bd315bfa Iustin Pop
  REQ_BGL = False
4007 bd315bfa Iustin Pop
4008 bd315bfa Iustin Pop
  def CheckArguments(self):
4009 bd315bfa Iustin Pop
    """Check the arguments.
4010 bd315bfa Iustin Pop

4011 bd315bfa Iustin Pop
    """
4012 bd315bfa Iustin Pop
    if not isinstance(self.op.disks, list):
4013 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
4014 bd315bfa Iustin Pop
    for item in self.op.disks:
4015 bd315bfa Iustin Pop
      if (not isinstance(item, int) or
4016 bd315bfa Iustin Pop
          item < 0):
4017 bd315bfa Iustin Pop
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
4018 5c983ee5 Iustin Pop
                                   str(item), errors.ECODE_INVAL)
4019 bd315bfa Iustin Pop
4020 bd315bfa Iustin Pop
  def ExpandNames(self):
4021 bd315bfa Iustin Pop
    self._ExpandAndLockInstance()
4022 bd315bfa Iustin Pop
4023 bd315bfa Iustin Pop
  def BuildHooksEnv(self):
4024 bd315bfa Iustin Pop
    """Build hooks env.
4025 bd315bfa Iustin Pop

4026 bd315bfa Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
4027 bd315bfa Iustin Pop

4028 bd315bfa Iustin Pop
    """
4029 bd315bfa Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4030 bd315bfa Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4031 bd315bfa Iustin Pop
    return env, nl, nl
4032 bd315bfa Iustin Pop
4033 bd315bfa Iustin Pop
  def CheckPrereq(self):
4034 bd315bfa Iustin Pop
    """Check prerequisites.
4035 bd315bfa Iustin Pop

4036 bd315bfa Iustin Pop
    This checks that the instance is in the cluster and is not running.
4037 bd315bfa Iustin Pop

4038 bd315bfa Iustin Pop
    """
4039 bd315bfa Iustin Pop
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4040 bd315bfa Iustin Pop
    assert instance is not None, \
4041 bd315bfa Iustin Pop
      "Cannot retrieve locked instance %s" % self.op.instance_name
4042 bd315bfa Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
4043 bd315bfa Iustin Pop
4044 bd315bfa Iustin Pop
    if instance.disk_template == constants.DT_DISKLESS:
4045 bd315bfa Iustin Pop
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4046 5c983ee5 Iustin Pop
                                 self.op.instance_name, errors.ECODE_INVAL)
4047 bd315bfa Iustin Pop
    if instance.admin_up:
4048 bd315bfa Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4049 5c983ee5 Iustin Pop
                                 self.op.instance_name, errors.ECODE_STATE)
4050 bd315bfa Iustin Pop
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4051 bd315bfa Iustin Pop
                                              instance.name,
4052 bd315bfa Iustin Pop
                                              instance.hypervisor)
4053 bd315bfa Iustin Pop
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4054 045dd6d9 Iustin Pop
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4055 bd315bfa Iustin Pop
    if remote_info.payload:
4056 bd315bfa Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4057 bd315bfa Iustin Pop
                                 (self.op.instance_name,
4058 5c983ee5 Iustin Pop
                                  instance.primary_node), errors.ECODE_STATE)
4059 bd315bfa Iustin Pop
4060 bd315bfa Iustin Pop
    if not self.op.disks:
4061 bd315bfa Iustin Pop
      self.op.disks = range(len(instance.disks))
4062 bd315bfa Iustin Pop
    else:
4063 bd315bfa Iustin Pop
      for idx in self.op.disks:
4064 bd315bfa Iustin Pop
        if idx >= len(instance.disks):
4065 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4066 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
4067 bd315bfa Iustin Pop
4068 bd315bfa Iustin Pop
    self.instance = instance
4069 bd315bfa Iustin Pop
4070 bd315bfa Iustin Pop
  def Exec(self, feedback_fn):
4071 bd315bfa Iustin Pop
    """Recreate the disks.
4072 bd315bfa Iustin Pop

4073 bd315bfa Iustin Pop
    """
4074 bd315bfa Iustin Pop
    to_skip = []
4075 1122eb25 Iustin Pop
    for idx, _ in enumerate(self.instance.disks):
4076 bd315bfa Iustin Pop
      if idx not in self.op.disks: # disk idx has not been passed in
4077 bd315bfa Iustin Pop
        to_skip.append(idx)
4078 bd315bfa Iustin Pop
        continue
4079 bd315bfa Iustin Pop
4080 bd315bfa Iustin Pop
    _CreateDisks(self, self.instance, to_skip=to_skip)
4081 bd315bfa Iustin Pop
4082 bd315bfa Iustin Pop
4083 decd5f45 Iustin Pop
class LURenameInstance(LogicalUnit):
4084 decd5f45 Iustin Pop
  """Rename an instance.
4085 decd5f45 Iustin Pop

4086 decd5f45 Iustin Pop
  """
4087 decd5f45 Iustin Pop
  HPATH = "instance-rename"
4088 decd5f45 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4089 decd5f45 Iustin Pop
  _OP_REQP = ["instance_name", "new_name"]
4090 decd5f45 Iustin Pop
4091 decd5f45 Iustin Pop
  def BuildHooksEnv(self):
4092 decd5f45 Iustin Pop
    """Build hooks env.
4093 decd5f45 Iustin Pop

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

4096 decd5f45 Iustin Pop
    """
4097 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4098 decd5f45 Iustin Pop
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4099 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4100 decd5f45 Iustin Pop
    return env, nl, nl
4101 decd5f45 Iustin Pop
4102 decd5f45 Iustin Pop
  def CheckPrereq(self):
4103 decd5f45 Iustin Pop
    """Check prerequisites.
4104 decd5f45 Iustin Pop

4105 decd5f45 Iustin Pop
    This checks that the instance is in the cluster and is not running.
4106 decd5f45 Iustin Pop

4107 decd5f45 Iustin Pop
    """
4108 decd5f45 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
4109 decd5f45 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
4110 decd5f45 Iustin Pop
    if instance is None:
4111 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
4112 5c983ee5 Iustin Pop
                                 self.op.instance_name, errors.ECODE_NOENT)
4113 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
4114 7527a8a4 Iustin Pop
4115 0d68c45d Iustin Pop
    if instance.admin_up:
4116 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
4117 5c983ee5 Iustin Pop
                                 self.op.instance_name, errors.ECODE_STATE)
4118 72737a7f Iustin Pop
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4119 72737a7f Iustin Pop
                                              instance.name,
4120 72737a7f Iustin Pop
                                              instance.hypervisor)
4121 4c4e4e1e Iustin Pop
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4122 045dd6d9 Iustin Pop
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4123 7ad1af4a Iustin Pop
    if remote_info.payload:
4124 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
4125 decd5f45 Iustin Pop
                                 (self.op.instance_name,
4126 5c983ee5 Iustin Pop
                                  instance.primary_node), errors.ECODE_STATE)
4127 decd5f45 Iustin Pop
    self.instance = instance
4128 decd5f45 Iustin Pop
4129 decd5f45 Iustin Pop
    # new name verification
4130 104f4ca1 Iustin Pop
    name_info = utils.GetHostInfo(self.op.new_name)
4131 decd5f45 Iustin Pop
4132 89e1fc26 Iustin Pop
    self.op.new_name = new_name = name_info.name
4133 7bde3275 Guido Trotter
    instance_list = self.cfg.GetInstanceList()
4134 7bde3275 Guido Trotter
    if new_name in instance_list:
4135 7bde3275 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4136 5c983ee5 Iustin Pop
                                 new_name, errors.ECODE_EXISTS)
4137 7bde3275 Guido Trotter
4138 decd5f45 Iustin Pop
    if not getattr(self.op, "ignore_ip", False):
4139 937f983d Guido Trotter
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4140 decd5f45 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4141 5c983ee5 Iustin Pop
                                   (name_info.ip, new_name),
4142 5c983ee5 Iustin Pop
                                   errors.ECODE_NOTUNIQUE)
4143 decd5f45 Iustin Pop
4144 decd5f45 Iustin Pop
4145 decd5f45 Iustin Pop
  def Exec(self, feedback_fn):
4146 decd5f45 Iustin Pop
    """Reinstall the instance.
4147 decd5f45 Iustin Pop

4148 decd5f45 Iustin Pop
    """
4149 decd5f45 Iustin Pop
    inst = self.instance
4150 decd5f45 Iustin Pop
    old_name = inst.name
4151 decd5f45 Iustin Pop
4152 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
4153 b23c4333 Manuel Franceschini
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4154 b23c4333 Manuel Franceschini
4155 decd5f45 Iustin Pop
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4156 74b5913f Guido Trotter
    # Change the instance lock. This is definitely safe while we hold the BGL
4157 cb4e8387 Iustin Pop
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4158 74b5913f Guido Trotter
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4159 decd5f45 Iustin Pop
4160 decd5f45 Iustin Pop
    # re-read the instance from the configuration after rename
4161 decd5f45 Iustin Pop
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4162 decd5f45 Iustin Pop
4163 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
4164 b23c4333 Manuel Franceschini
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4165 72737a7f Iustin Pop
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4166 72737a7f Iustin Pop
                                                     old_file_storage_dir,
4167 72737a7f Iustin Pop
                                                     new_file_storage_dir)
4168 4c4e4e1e Iustin Pop
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4169 4c4e4e1e Iustin Pop
                   " (but the instance has been renamed in Ganeti)" %
4170 4c4e4e1e Iustin Pop
                   (inst.primary_node, old_file_storage_dir,
4171 4c4e4e1e Iustin Pop
                    new_file_storage_dir))
4172 b23c4333 Manuel Franceschini
4173 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, inst, None)
4174 decd5f45 Iustin Pop
    try:
4175 781de953 Iustin Pop
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4176 781de953 Iustin Pop
                                                 old_name)
4177 4c4e4e1e Iustin Pop
      msg = result.fail_msg
4178 96841384 Iustin Pop
      if msg:
4179 6291574d Alexander Schreiber
        msg = ("Could not run OS rename script for instance %s on node %s"
4180 96841384 Iustin Pop
               " (but the instance has been renamed in Ganeti): %s" %
4181 96841384 Iustin Pop
               (inst.name, inst.primary_node, msg))
4182 86d9d3bb Iustin Pop
        self.proc.LogWarning(msg)
4183 decd5f45 Iustin Pop
    finally:
4184 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, inst)
4185 decd5f45 Iustin Pop
4186 decd5f45 Iustin Pop
4187 a8083063 Iustin Pop
class LURemoveInstance(LogicalUnit):
4188 a8083063 Iustin Pop
  """Remove an instance.
4189 a8083063 Iustin Pop

4190 a8083063 Iustin Pop
  """
4191 a8083063 Iustin Pop
  HPATH = "instance-remove"
4192 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4193 5c54b832 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_failures"]
4194 cf472233 Guido Trotter
  REQ_BGL = False
4195 cf472233 Guido Trotter
4196 17c3f802 Guido Trotter
  def CheckArguments(self):
4197 17c3f802 Guido Trotter
    """Check the arguments.
4198 17c3f802 Guido Trotter

4199 17c3f802 Guido Trotter
    """
4200 17c3f802 Guido Trotter
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4201 17c3f802 Guido Trotter
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4202 17c3f802 Guido Trotter
4203 cf472233 Guido Trotter
  def ExpandNames(self):
4204 cf472233 Guido Trotter
    self._ExpandAndLockInstance()
4205 cf472233 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
4206 cf472233 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4207 cf472233 Guido Trotter
4208 cf472233 Guido Trotter
  def DeclareLocks(self, level):
4209 cf472233 Guido Trotter
    if level == locking.LEVEL_NODE:
4210 cf472233 Guido Trotter
      self._LockInstancesNodes()
4211 a8083063 Iustin Pop
4212 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4213 a8083063 Iustin Pop
    """Build hooks env.
4214 a8083063 Iustin Pop

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

4217 a8083063 Iustin Pop
    """
4218 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4219 17c3f802 Guido Trotter
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4220 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()]
4221 a8083063 Iustin Pop
    return env, nl, nl
4222 a8083063 Iustin Pop
4223 a8083063 Iustin Pop
  def CheckPrereq(self):
4224 a8083063 Iustin Pop
    """Check prerequisites.
4225 a8083063 Iustin Pop

4226 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
4227 a8083063 Iustin Pop

4228 a8083063 Iustin Pop
    """
4229 cf472233 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4230 cf472233 Guido Trotter
    assert self.instance is not None, \
4231 cf472233 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4232 a8083063 Iustin Pop
4233 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4234 a8083063 Iustin Pop
    """Remove the instance.
4235 a8083063 Iustin Pop

4236 a8083063 Iustin Pop
    """
4237 a8083063 Iustin Pop
    instance = self.instance
4238 9a4f63d1 Iustin Pop
    logging.info("Shutting down instance %s on node %s",
4239 9a4f63d1 Iustin Pop
                 instance.name, instance.primary_node)
4240 a8083063 Iustin Pop
4241 17c3f802 Guido Trotter
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4242 17c3f802 Guido Trotter
                                             self.shutdown_timeout)
4243 4c4e4e1e Iustin Pop
    msg = result.fail_msg
4244 1fae010f Iustin Pop
    if msg:
4245 1d67656e Iustin Pop
      if self.op.ignore_failures:
4246 1fae010f Iustin Pop
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4247 1d67656e Iustin Pop
      else:
4248 1fae010f Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on"
4249 1fae010f Iustin Pop
                                 " node %s: %s" %
4250 1fae010f Iustin Pop
                                 (instance.name, instance.primary_node, msg))
4251 a8083063 Iustin Pop
4252 9a4f63d1 Iustin Pop
    logging.info("Removing block devices for instance %s", instance.name)
4253 a8083063 Iustin Pop
4254 b9bddb6b Iustin Pop
    if not _RemoveDisks(self, instance):
4255 1d67656e Iustin Pop
      if self.op.ignore_failures:
4256 1d67656e Iustin Pop
        feedback_fn("Warning: can't remove instance's disks")
4257 1d67656e Iustin Pop
      else:
4258 1d67656e Iustin Pop
        raise errors.OpExecError("Can't remove instance's disks")
4259 a8083063 Iustin Pop
4260 9a4f63d1 Iustin Pop
    logging.info("Removing instance %s out of cluster config", instance.name)
4261 a8083063 Iustin Pop
4262 a8083063 Iustin Pop
    self.cfg.RemoveInstance(instance.name)
4263 cf472233 Guido Trotter
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4264 a8083063 Iustin Pop
4265 a8083063 Iustin Pop
4266 a8083063 Iustin Pop
class LUQueryInstances(NoHooksLU):
4267 a8083063 Iustin Pop
  """Logical unit for querying instances.
4268 a8083063 Iustin Pop

4269 a8083063 Iustin Pop
  """
4270 7260cfbe Iustin Pop
  # pylint: disable-msg=W0142
4271 ec79568d Iustin Pop
  _OP_REQP = ["output_fields", "names", "use_locking"]
4272 7eb9d8f7 Guido Trotter
  REQ_BGL = False
4273 19bed813 Iustin Pop
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4274 19bed813 Iustin Pop
                    "serial_no", "ctime", "mtime", "uuid"]
4275 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4276 5b460366 Iustin Pop
                                    "admin_state",
4277 a2d2e1a7 Iustin Pop
                                    "disk_template", "ip", "mac", "bridge",
4278 638c6349 Guido Trotter
                                    "nic_mode", "nic_link",
4279 a2d2e1a7 Iustin Pop
                                    "sda_size", "sdb_size", "vcpus", "tags",
4280 a2d2e1a7 Iustin Pop
                                    "network_port", "beparams",
4281 8aec325c Iustin Pop
                                    r"(disk)\.(size)/([0-9]+)",
4282 8aec325c Iustin Pop
                                    r"(disk)\.(sizes)", "disk_usage",
4283 638c6349 Guido Trotter
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4284 638c6349 Guido Trotter
                                    r"(nic)\.(bridge)/([0-9]+)",
4285 638c6349 Guido Trotter
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4286 8aec325c Iustin Pop
                                    r"(disk|nic)\.(count)",
4287 19bed813 Iustin Pop
                                    "hvparams",
4288 19bed813 Iustin Pop
                                    ] + _SIMPLE_FIELDS +
4289 a2d2e1a7 Iustin Pop
                                  ["hv/%s" % name
4290 7736a5f2 Iustin Pop
                                   for name in constants.HVS_PARAMETERS
4291 7736a5f2 Iustin Pop
                                   if name not in constants.HVC_GLOBALS] +
4292 a2d2e1a7 Iustin Pop
                                  ["be/%s" % name
4293 a2d2e1a7 Iustin Pop
                                   for name in constants.BES_PARAMETERS])
4294 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4295 31bf511f Iustin Pop
4296 a8083063 Iustin Pop
4297 7eb9d8f7 Guido Trotter
  def ExpandNames(self):
4298 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
4299 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
4300 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
4301 a8083063 Iustin Pop
4302 7eb9d8f7 Guido Trotter
    self.needed_locks = {}
4303 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4304 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
4305 7eb9d8f7 Guido Trotter
4306 57a2fb91 Iustin Pop
    if self.op.names:
4307 57a2fb91 Iustin Pop
      self.wanted = _GetWantedInstances(self, self.op.names)
4308 7eb9d8f7 Guido Trotter
    else:
4309 57a2fb91 Iustin Pop
      self.wanted = locking.ALL_SET
4310 7eb9d8f7 Guido Trotter
4311 ec79568d Iustin Pop
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4312 ec79568d Iustin Pop
    self.do_locking = self.do_node_query and self.op.use_locking
4313 57a2fb91 Iustin Pop
    if self.do_locking:
4314 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4315 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = []
4316 57a2fb91 Iustin Pop
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4317 7eb9d8f7 Guido Trotter
4318 7eb9d8f7 Guido Trotter
  def DeclareLocks(self, level):
4319 57a2fb91 Iustin Pop
    if level == locking.LEVEL_NODE and self.do_locking:
4320 7eb9d8f7 Guido Trotter
      self._LockInstancesNodes()
4321 7eb9d8f7 Guido Trotter
4322 7eb9d8f7 Guido Trotter
  def CheckPrereq(self):
4323 7eb9d8f7 Guido Trotter
    """Check prerequisites.
4324 7eb9d8f7 Guido Trotter

4325 7eb9d8f7 Guido Trotter
    """
4326 57a2fb91 Iustin Pop
    pass
4327 069dcc86 Iustin Pop
4328 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4329 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
4330 a8083063 Iustin Pop

4331 a8083063 Iustin Pop
    """
4332 7260cfbe Iustin Pop
    # pylint: disable-msg=R0912
4333 7260cfbe Iustin Pop
    # way too many branches here
4334 57a2fb91 Iustin Pop
    all_info = self.cfg.GetAllInstancesInfo()
4335 a7f5dc98 Iustin Pop
    if self.wanted == locking.ALL_SET:
4336 a7f5dc98 Iustin Pop
      # caller didn't specify instance names, so ordering is not important
4337 a7f5dc98 Iustin Pop
      if self.do_locking:
4338 a7f5dc98 Iustin Pop
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4339 a7f5dc98 Iustin Pop
      else:
4340 a7f5dc98 Iustin Pop
        instance_names = all_info.keys()
4341 a7f5dc98 Iustin Pop
      instance_names = utils.NiceSort(instance_names)
4342 57a2fb91 Iustin Pop
    else:
4343 a7f5dc98 Iustin Pop
      # caller did specify names, so we must keep the ordering
4344 a7f5dc98 Iustin Pop
      if self.do_locking:
4345 a7f5dc98 Iustin Pop
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4346 a7f5dc98 Iustin Pop
      else:
4347 a7f5dc98 Iustin Pop
        tgt_set = all_info.keys()
4348 a7f5dc98 Iustin Pop
      missing = set(self.wanted).difference(tgt_set)
4349 a7f5dc98 Iustin Pop
      if missing:
4350 a7f5dc98 Iustin Pop
        raise errors.OpExecError("Some instances were removed before"
4351 a7f5dc98 Iustin Pop
                                 " retrieving their data: %s" % missing)
4352 a7f5dc98 Iustin Pop
      instance_names = self.wanted
4353 c1f1cbb2 Iustin Pop
4354 57a2fb91 Iustin Pop
    instance_list = [all_info[iname] for iname in instance_names]
4355 a8083063 Iustin Pop
4356 a8083063 Iustin Pop
    # begin data gathering
4357 a8083063 Iustin Pop
4358 a8083063 Iustin Pop
    nodes = frozenset([inst.primary_node for inst in instance_list])
4359 e69d05fd Iustin Pop
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4360 a8083063 Iustin Pop
4361 a8083063 Iustin Pop
    bad_nodes = []
4362 cbfc4681 Iustin Pop
    off_nodes = []
4363 ec79568d Iustin Pop
    if self.do_node_query:
4364 a8083063 Iustin Pop
      live_data = {}
4365 72737a7f Iustin Pop
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4366 a8083063 Iustin Pop
      for name in nodes:
4367 a8083063 Iustin Pop
        result = node_data[name]
4368 cbfc4681 Iustin Pop
        if result.offline:
4369 cbfc4681 Iustin Pop
          # offline nodes will be in both lists
4370 cbfc4681 Iustin Pop
          off_nodes.append(name)
4371 3cebe102 Michael Hanselmann
        if result.fail_msg:
4372 a8083063 Iustin Pop
          bad_nodes.append(name)
4373 781de953 Iustin Pop
        else:
4374 2fa74ef4 Iustin Pop
          if result.payload:
4375 2fa74ef4 Iustin Pop
            live_data.update(result.payload)
4376 2fa74ef4 Iustin Pop
          # else no instance is alive
4377 a8083063 Iustin Pop
    else:
4378 a8083063 Iustin Pop
      live_data = dict([(name, {}) for name in instance_names])
4379 a8083063 Iustin Pop
4380 a8083063 Iustin Pop
    # end data gathering
4381 a8083063 Iustin Pop
4382 5018a335 Iustin Pop
    HVPREFIX = "hv/"
4383 338e51e8 Iustin Pop
    BEPREFIX = "be/"
4384 a8083063 Iustin Pop
    output = []
4385 638c6349 Guido Trotter
    cluster = self.cfg.GetClusterInfo()
4386 a8083063 Iustin Pop
    for instance in instance_list:
4387 a8083063 Iustin Pop
      iout = []
4388 7736a5f2 Iustin Pop
      i_hv = cluster.FillHV(instance, skip_globals=True)
4389 638c6349 Guido Trotter
      i_be = cluster.FillBE(instance)
4390 638c6349 Guido Trotter
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4391 638c6349 Guido Trotter
                                 nic.nicparams) for nic in instance.nics]
4392 a8083063 Iustin Pop
      for field in self.op.output_fields:
4393 71c1af58 Iustin Pop
        st_match = self._FIELDS_STATIC.Matches(field)
4394 19bed813 Iustin Pop
        if field in self._SIMPLE_FIELDS:
4395 19bed813 Iustin Pop
          val = getattr(instance, field)
4396 a8083063 Iustin Pop
        elif field == "pnode":
4397 a8083063 Iustin Pop
          val = instance.primary_node
4398 a8083063 Iustin Pop
        elif field == "snodes":
4399 8a23d2d3 Iustin Pop
          val = list(instance.secondary_nodes)
4400 a8083063 Iustin Pop
        elif field == "admin_state":
4401 0d68c45d Iustin Pop
          val = instance.admin_up
4402 a8083063 Iustin Pop
        elif field == "oper_state":
4403 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
4404 8a23d2d3 Iustin Pop
            val = None
4405 a8083063 Iustin Pop
          else:
4406 8a23d2d3 Iustin Pop
            val = bool(live_data.get(instance.name))
4407 d8052456 Iustin Pop
        elif field == "status":
4408 cbfc4681 Iustin Pop
          if instance.primary_node in off_nodes:
4409 cbfc4681 Iustin Pop
            val = "ERROR_nodeoffline"
4410 cbfc4681 Iustin Pop
          elif instance.primary_node in bad_nodes:
4411 d8052456 Iustin Pop
            val = "ERROR_nodedown"
4412 d8052456 Iustin Pop
          else:
4413 d8052456 Iustin Pop
            running = bool(live_data.get(instance.name))
4414 d8052456 Iustin Pop
            if running:
4415 0d68c45d Iustin Pop
              if instance.admin_up:
4416 d8052456 Iustin Pop
                val = "running"
4417 d8052456 Iustin Pop
              else:
4418 d8052456 Iustin Pop
                val = "ERROR_up"
4419 d8052456 Iustin Pop
            else:
4420 0d68c45d Iustin Pop
              if instance.admin_up:
4421 d8052456 Iustin Pop
                val = "ERROR_down"
4422 d8052456 Iustin Pop
              else:
4423 d8052456 Iustin Pop
                val = "ADMIN_down"
4424 a8083063 Iustin Pop
        elif field == "oper_ram":
4425 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
4426 8a23d2d3 Iustin Pop
            val = None
4427 a8083063 Iustin Pop
          elif instance.name in live_data:
4428 a8083063 Iustin Pop
            val = live_data[instance.name].get("memory", "?")
4429 a8083063 Iustin Pop
          else:
4430 a8083063 Iustin Pop
            val = "-"
4431 c1ce76bb Iustin Pop
        elif field == "vcpus":
4432 c1ce76bb Iustin Pop
          val = i_be[constants.BE_VCPUS]
4433 a8083063 Iustin Pop
        elif field == "disk_template":
4434 a8083063 Iustin Pop
          val = instance.disk_template
4435 a8083063 Iustin Pop
        elif field == "ip":
4436 39a02558 Guido Trotter
          if instance.nics:
4437 39a02558 Guido Trotter
            val = instance.nics[0].ip
4438 39a02558 Guido Trotter
          else:
4439 39a02558 Guido Trotter
            val = None
4440 638c6349 Guido Trotter
        elif field == "nic_mode":
4441 638c6349 Guido Trotter
          if instance.nics:
4442 638c6349 Guido Trotter
            val = i_nicp[0][constants.NIC_MODE]
4443 638c6349 Guido Trotter
          else:
4444 638c6349 Guido Trotter
            val = None
4445 638c6349 Guido Trotter
        elif field == "nic_link":
4446 39a02558 Guido Trotter
          if instance.nics:
4447 638c6349 Guido Trotter
            val = i_nicp[0][constants.NIC_LINK]
4448 638c6349 Guido Trotter
          else:
4449 638c6349 Guido Trotter
            val = None
4450 638c6349 Guido Trotter
        elif field == "bridge":
4451 638c6349 Guido Trotter
          if (instance.nics and
4452 638c6349 Guido Trotter
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4453 638c6349 Guido Trotter
            val = i_nicp[0][constants.NIC_LINK]
4454 39a02558 Guido Trotter
          else:
4455 39a02558 Guido Trotter
            val = None
4456 a8083063 Iustin Pop
        elif field == "mac":
4457 39a02558 Guido Trotter
          if instance.nics:
4458 39a02558 Guido Trotter
            val = instance.nics[0].mac
4459 39a02558 Guido Trotter
          else:
4460 39a02558 Guido Trotter
            val = None
4461 644eeef9 Iustin Pop
        elif field == "sda_size" or field == "sdb_size":
4462 ad24e046 Iustin Pop
          idx = ord(field[2]) - ord('a')
4463 ad24e046 Iustin Pop
          try:
4464 ad24e046 Iustin Pop
            val = instance.FindDisk(idx).size
4465 ad24e046 Iustin Pop
          except errors.OpPrereqError:
4466 8a23d2d3 Iustin Pop
            val = None
4467 024e157f Iustin Pop
        elif field == "disk_usage": # total disk usage per node
4468 024e157f Iustin Pop
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4469 024e157f Iustin Pop
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4470 130a6a6f Iustin Pop
        elif field == "tags":
4471 130a6a6f Iustin Pop
          val = list(instance.GetTags())
4472 338e51e8 Iustin Pop
        elif field == "hvparams":
4473 338e51e8 Iustin Pop
          val = i_hv
4474 5018a335 Iustin Pop
        elif (field.startswith(HVPREFIX) and
4475 7736a5f2 Iustin Pop
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
4476 7736a5f2 Iustin Pop
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
4477 5018a335 Iustin Pop
          val = i_hv.get(field[len(HVPREFIX):], None)
4478 338e51e8 Iustin Pop
        elif field == "beparams":
4479 338e51e8 Iustin Pop
          val = i_be
4480 338e51e8 Iustin Pop
        elif (field.startswith(BEPREFIX) and
4481 338e51e8 Iustin Pop
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4482 338e51e8 Iustin Pop
          val = i_be.get(field[len(BEPREFIX):], None)
4483 71c1af58 Iustin Pop
        elif st_match and st_match.groups():
4484 71c1af58 Iustin Pop
          # matches a variable list
4485 71c1af58 Iustin Pop
          st_groups = st_match.groups()
4486 71c1af58 Iustin Pop
          if st_groups and st_groups[0] == "disk":
4487 71c1af58 Iustin Pop
            if st_groups[1] == "count":
4488 71c1af58 Iustin Pop
              val = len(instance.disks)
4489 41a776da Iustin Pop
            elif st_groups[1] == "sizes":
4490 41a776da Iustin Pop
              val = [disk.size for disk in instance.disks]
4491 71c1af58 Iustin Pop
            elif st_groups[1] == "size":
4492 3e0cea06 Iustin Pop
              try:
4493 3e0cea06 Iustin Pop
                val = instance.FindDisk(st_groups[2]).size
4494 3e0cea06 Iustin Pop
              except errors.OpPrereqError:
4495 71c1af58 Iustin Pop
                val = None
4496 71c1af58 Iustin Pop
            else:
4497 71c1af58 Iustin Pop
              assert False, "Unhandled disk parameter"
4498 71c1af58 Iustin Pop
          elif st_groups[0] == "nic":
4499 71c1af58 Iustin Pop
            if st_groups[1] == "count":
4500 71c1af58 Iustin Pop
              val = len(instance.nics)
4501 41a776da Iustin Pop
            elif st_groups[1] == "macs":
4502 41a776da Iustin Pop
              val = [nic.mac for nic in instance.nics]
4503 41a776da Iustin Pop
            elif st_groups[1] == "ips":
4504 41a776da Iustin Pop
              val = [nic.ip for nic in instance.nics]
4505 638c6349 Guido Trotter
            elif st_groups[1] == "modes":
4506 638c6349 Guido Trotter
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4507 638c6349 Guido Trotter
            elif st_groups[1] == "links":
4508 638c6349 Guido Trotter
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4509 41a776da Iustin Pop
            elif st_groups[1] == "bridges":
4510 638c6349 Guido Trotter
              val = []
4511 638c6349 Guido Trotter
              for nicp in i_nicp:
4512 638c6349 Guido Trotter
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4513 638c6349 Guido Trotter
                  val.append(nicp[constants.NIC_LINK])
4514 638c6349 Guido Trotter
                else:
4515 638c6349 Guido Trotter
                  val.append(None)
4516 71c1af58 Iustin Pop
            else:
4517 71c1af58 Iustin Pop
              # index-based item
4518 71c1af58 Iustin Pop
              nic_idx = int(st_groups[2])
4519 71c1af58 Iustin Pop
              if nic_idx >= len(instance.nics):
4520 71c1af58 Iustin Pop
                val = None
4521 71c1af58 Iustin Pop
              else:
4522 71c1af58 Iustin Pop
                if st_groups[1] == "mac":
4523 71c1af58 Iustin Pop
                  val = instance.nics[nic_idx].mac
4524 71c1af58 Iustin Pop
                elif st_groups[1] == "ip":
4525 71c1af58 Iustin Pop
                  val = instance.nics[nic_idx].ip
4526 638c6349 Guido Trotter
                elif st_groups[1] == "mode":
4527 638c6349 Guido Trotter
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4528 638c6349 Guido Trotter
                elif st_groups[1] == "link":
4529 638c6349 Guido Trotter
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4530 71c1af58 Iustin Pop
                elif st_groups[1] == "bridge":
4531 638c6349 Guido Trotter
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4532 638c6349 Guido Trotter
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4533 638c6349 Guido Trotter
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4534 638c6349 Guido Trotter
                  else:
4535 638c6349 Guido Trotter
                    val = None
4536 71c1af58 Iustin Pop
                else:
4537 71c1af58 Iustin Pop
                  assert False, "Unhandled NIC parameter"
4538 71c1af58 Iustin Pop
          else:
4539 c1ce76bb Iustin Pop
            assert False, ("Declared but unhandled variable parameter '%s'" %
4540 c1ce76bb Iustin Pop
                           field)
4541 a8083063 Iustin Pop
        else:
4542 c1ce76bb Iustin Pop
          assert False, "Declared but unhandled parameter '%s'" % field
4543 a8083063 Iustin Pop
        iout.append(val)
4544 a8083063 Iustin Pop
      output.append(iout)
4545 a8083063 Iustin Pop
4546 a8083063 Iustin Pop
    return output
4547 a8083063 Iustin Pop
4548 a8083063 Iustin Pop
4549 a8083063 Iustin Pop
class LUFailoverInstance(LogicalUnit):
4550 a8083063 Iustin Pop
  """Failover an instance.
4551 a8083063 Iustin Pop

4552 a8083063 Iustin Pop
  """
4553 a8083063 Iustin Pop
  HPATH = "instance-failover"
4554 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4555 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_consistency"]
4556 c9e5c064 Guido Trotter
  REQ_BGL = False
4557 c9e5c064 Guido Trotter
4558 17c3f802 Guido Trotter
  def CheckArguments(self):
4559 17c3f802 Guido Trotter
    """Check the arguments.
4560 17c3f802 Guido Trotter

4561 17c3f802 Guido Trotter
    """
4562 17c3f802 Guido Trotter
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4563 17c3f802 Guido Trotter
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4564 17c3f802 Guido Trotter
4565 c9e5c064 Guido Trotter
  def ExpandNames(self):
4566 c9e5c064 Guido Trotter
    self._ExpandAndLockInstance()
4567 c9e5c064 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
4568 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4569 c9e5c064 Guido Trotter
4570 c9e5c064 Guido Trotter
  def DeclareLocks(self, level):
4571 c9e5c064 Guido Trotter
    if level == locking.LEVEL_NODE:
4572 c9e5c064 Guido Trotter
      self._LockInstancesNodes()
4573 a8083063 Iustin Pop
4574 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4575 a8083063 Iustin Pop
    """Build hooks env.
4576 a8083063 Iustin Pop

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

4579 a8083063 Iustin Pop
    """
4580 a8083063 Iustin Pop
    env = {
4581 a8083063 Iustin Pop
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4582 17c3f802 Guido Trotter
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4583 a8083063 Iustin Pop
      }
4584 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4585 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
4586 a8083063 Iustin Pop
    return env, nl, nl
4587 a8083063 Iustin Pop
4588 a8083063 Iustin Pop
  def CheckPrereq(self):
4589 a8083063 Iustin Pop
    """Check prerequisites.
4590 a8083063 Iustin Pop

4591 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
4592 a8083063 Iustin Pop

4593 a8083063 Iustin Pop
    """
4594 c9e5c064 Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4595 c9e5c064 Guido Trotter
    assert self.instance is not None, \
4596 c9e5c064 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4597 a8083063 Iustin Pop
4598 338e51e8 Iustin Pop
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4599 a1f445d3 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
4600 2a710df1 Michael Hanselmann
      raise errors.OpPrereqError("Instance's disk layout is not"
4601 5c983ee5 Iustin Pop
                                 " network mirrored, cannot failover.",
4602 5c983ee5 Iustin Pop
                                 errors.ECODE_STATE)
4603 2a710df1 Michael Hanselmann
4604 2a710df1 Michael Hanselmann
    secondary_nodes = instance.secondary_nodes
4605 2a710df1 Michael Hanselmann
    if not secondary_nodes:
4606 2a710df1 Michael Hanselmann
      raise errors.ProgrammerError("no secondary node but using "
4607 abdf0113 Iustin Pop
                                   "a mirrored disk template")
4608 2a710df1 Michael Hanselmann
4609 2a710df1 Michael Hanselmann
    target_node = secondary_nodes[0]
4610 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, target_node)
4611 733a2b6a Iustin Pop
    _CheckNodeNotDrained(self, target_node)
4612 d27776f0 Iustin Pop
    if instance.admin_up:
4613 d27776f0 Iustin Pop
      # check memory requirements on the secondary node
4614 d27776f0 Iustin Pop
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4615 d27776f0 Iustin Pop
                           instance.name, bep[constants.BE_MEMORY],
4616 d27776f0 Iustin Pop
                           instance.hypervisor)
4617 d27776f0 Iustin Pop
    else:
4618 d27776f0 Iustin Pop
      self.LogInfo("Not checking memory on the secondary node as"
4619 d27776f0 Iustin Pop
                   " instance will not be started")
4620 3a7c308e Guido Trotter
4621 a8083063 Iustin Pop
    # check bridge existance
4622 b165e77e Guido Trotter
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4623 a8083063 Iustin Pop
4624 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4625 a8083063 Iustin Pop
    """Failover an instance.
4626 a8083063 Iustin Pop

4627 a8083063 Iustin Pop
    The failover is done by shutting it down on its present node and
4628 a8083063 Iustin Pop
    starting it on the secondary.
4629 a8083063 Iustin Pop

4630 a8083063 Iustin Pop
    """
4631 a8083063 Iustin Pop
    instance = self.instance
4632 a8083063 Iustin Pop
4633 a8083063 Iustin Pop
    source_node = instance.primary_node
4634 a8083063 Iustin Pop
    target_node = instance.secondary_nodes[0]
4635 a8083063 Iustin Pop
4636 1df79ce6 Michael Hanselmann
    if instance.admin_up:
4637 1df79ce6 Michael Hanselmann
      feedback_fn("* checking disk consistency between source and target")
4638 1df79ce6 Michael Hanselmann
      for dev in instance.disks:
4639 1df79ce6 Michael Hanselmann
        # for drbd, these are drbd over lvm
4640 1df79ce6 Michael Hanselmann
        if not _CheckDiskConsistency(self, dev, target_node, False):
4641 1df79ce6 Michael Hanselmann
          if not self.op.ignore_consistency:
4642 1df79ce6 Michael Hanselmann
            raise errors.OpExecError("Disk %s is degraded on target node,"
4643 1df79ce6 Michael Hanselmann
                                     " aborting failover." % dev.iv_name)
4644 1df79ce6 Michael Hanselmann
    else:
4645 1df79ce6 Michael Hanselmann
      feedback_fn("* not checking disk consistency as instance is not running")
4646 a8083063 Iustin Pop
4647 a8083063 Iustin Pop
    feedback_fn("* shutting down instance on source node")
4648 9a4f63d1 Iustin Pop
    logging.info("Shutting down instance %s on node %s",
4649 9a4f63d1 Iustin Pop
                 instance.name, source_node)
4650 a8083063 Iustin Pop
4651 17c3f802 Guido Trotter
    result = self.rpc.call_instance_shutdown(source_node, instance,
4652 17c3f802 Guido Trotter
                                             self.shutdown_timeout)
4653 4c4e4e1e Iustin Pop
    msg = result.fail_msg
4654 1fae010f Iustin Pop
    if msg:
4655 24a40d57 Iustin Pop
      if self.op.ignore_consistency:
4656 86d9d3bb Iustin Pop
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4657 1fae010f Iustin Pop
                             " Proceeding anyway. Please make sure node"
4658 1fae010f Iustin Pop
                             " %s is down. Error details: %s",
4659 1fae010f Iustin Pop
                             instance.name, source_node, source_node, msg)
4660 24a40d57 Iustin Pop
      else:
4661 1fae010f Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on"
4662 1fae010f Iustin Pop
                                 " node %s: %s" %
4663 1fae010f Iustin Pop
                                 (instance.name, source_node, msg))
4664 a8083063 Iustin Pop
4665 a8083063 Iustin Pop
    feedback_fn("* deactivating the instance's disks on source node")
4666 b9bddb6b Iustin Pop
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
4667 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't shut down the instance's disks.")
4668 a8083063 Iustin Pop
4669 a8083063 Iustin Pop
    instance.primary_node = target_node
4670 a8083063 Iustin Pop
    # distribute new instance config to the other nodes
4671 a4eae71f Michael Hanselmann
    self.cfg.Update(instance, feedback_fn)
4672 a8083063 Iustin Pop
4673 12a0cfbe Guido Trotter
    # Only start the instance if it's marked as up
4674 0d68c45d Iustin Pop
    if instance.admin_up:
4675 12a0cfbe Guido Trotter
      feedback_fn("* activating the instance's disks on target node")
4676 9a4f63d1 Iustin Pop
      logging.info("Starting instance %s on node %s",
4677 9a4f63d1 Iustin Pop
                   instance.name, target_node)
4678 12a0cfbe Guido Trotter
4679 7c4d6c7b Michael Hanselmann
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4680 12a0cfbe Guido Trotter
                                               ignore_secondaries=True)
4681 12a0cfbe Guido Trotter
      if not disks_ok:
4682 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
4683 12a0cfbe Guido Trotter
        raise errors.OpExecError("Can't activate the instance's disks")
4684 a8083063 Iustin Pop
4685 12a0cfbe Guido Trotter
      feedback_fn("* starting the instance on the target node")
4686 0eca8e0c Iustin Pop
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4687 4c4e4e1e Iustin Pop
      msg = result.fail_msg
4688 dd279568 Iustin Pop
      if msg:
4689 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
4690 dd279568 Iustin Pop
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4691 dd279568 Iustin Pop
                                 (instance.name, target_node, msg))
4692 a8083063 Iustin Pop
4693 a8083063 Iustin Pop
4694 53c776b5 Iustin Pop
class LUMigrateInstance(LogicalUnit):
4695 53c776b5 Iustin Pop
  """Migrate an instance.
4696 53c776b5 Iustin Pop

4697 53c776b5 Iustin Pop
  This is migration without shutting down, compared to the failover,
4698 53c776b5 Iustin Pop
  which is done with shutdown.
4699 53c776b5 Iustin Pop

4700 53c776b5 Iustin Pop
  """
4701 53c776b5 Iustin Pop
  HPATH = "instance-migrate"
4702 53c776b5 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4703 53c776b5 Iustin Pop
  _OP_REQP = ["instance_name", "live", "cleanup"]
4704 53c776b5 Iustin Pop
4705 53c776b5 Iustin Pop
  REQ_BGL = False
4706 53c776b5 Iustin Pop
4707 53c776b5 Iustin Pop
  def ExpandNames(self):
4708 53c776b5 Iustin Pop
    self._ExpandAndLockInstance()
4709 3e06e001 Michael Hanselmann
4710 53c776b5 Iustin Pop
    self.needed_locks[locking.LEVEL_NODE] = []
4711 53c776b5 Iustin Pop
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4712 53c776b5 Iustin Pop
4713 3e06e001 Michael Hanselmann
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
4714 3e06e001 Michael Hanselmann
                                       self.op.live, self.op.cleanup)
4715 3a012b41 Michael Hanselmann
    self.tasklets = [self._migrater]
4716 3e06e001 Michael Hanselmann
4717 53c776b5 Iustin Pop
  def DeclareLocks(self, level):
4718 53c776b5 Iustin Pop
    if level == locking.LEVEL_NODE:
4719 53c776b5 Iustin Pop
      self._LockInstancesNodes()
4720 53c776b5 Iustin Pop
4721 53c776b5 Iustin Pop
  def BuildHooksEnv(self):
4722 53c776b5 Iustin Pop
    """Build hooks env.
4723 53c776b5 Iustin Pop

4724 53c776b5 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
4725 53c776b5 Iustin Pop

4726 53c776b5 Iustin Pop
    """
4727 3e06e001 Michael Hanselmann
    instance = self._migrater.instance
4728 3e06e001 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self, instance)
4729 2c2690c9 Iustin Pop
    env["MIGRATE_LIVE"] = self.op.live
4730 2c2690c9 Iustin Pop
    env["MIGRATE_CLEANUP"] = self.op.cleanup
4731 3e06e001 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4732 53c776b5 Iustin Pop
    return env, nl, nl
4733 53c776b5 Iustin Pop
4734 3e06e001 Michael Hanselmann
4735 313bcead Iustin Pop
class LUMoveInstance(LogicalUnit):
4736 313bcead Iustin Pop
  """Move an instance by data-copying.
4737 313bcead Iustin Pop

4738 313bcead Iustin Pop
  """
4739 313bcead Iustin Pop
  HPATH = "instance-move"
4740 313bcead Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4741 313bcead Iustin Pop
  _OP_REQP = ["instance_name", "target_node"]
4742 313bcead Iustin Pop
  REQ_BGL = False
4743 313bcead Iustin Pop
4744 17c3f802 Guido Trotter
  def CheckArguments(self):
4745 17c3f802 Guido Trotter
    """Check the arguments.
4746 17c3f802 Guido Trotter

4747 17c3f802 Guido Trotter
    """
4748 17c3f802 Guido Trotter
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4749 17c3f802 Guido Trotter
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4750 17c3f802 Guido Trotter
4751 313bcead Iustin Pop
  def ExpandNames(self):
4752 313bcead Iustin Pop
    self._ExpandAndLockInstance()
4753 313bcead Iustin Pop
    target_node = self.cfg.ExpandNodeName(self.op.target_node)
4754 313bcead Iustin Pop
    if target_node is None:
4755 313bcead Iustin Pop
      raise errors.OpPrereqError("Node '%s' not known" %
4756 5c983ee5 Iustin Pop
                                  self.op.target_node, errors.ECODE_NOENT)
4757 313bcead Iustin Pop
    self.op.target_node = target_node
4758 313bcead Iustin Pop
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
4759 313bcead Iustin Pop
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4760 313bcead Iustin Pop
4761 313bcead Iustin Pop
  def DeclareLocks(self, level):
4762 313bcead Iustin Pop
    if level == locking.LEVEL_NODE:
4763 313bcead Iustin Pop
      self._LockInstancesNodes(primary_only=True)
4764 313bcead Iustin Pop
4765 313bcead Iustin Pop
  def BuildHooksEnv(self):
4766 313bcead Iustin Pop
    """Build hooks env.
4767 313bcead Iustin Pop

4768 313bcead Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
4769 313bcead Iustin Pop

4770 313bcead Iustin Pop
    """
4771 313bcead Iustin Pop
    env = {
4772 313bcead Iustin Pop
      "TARGET_NODE": self.op.target_node,
4773 17c3f802 Guido Trotter
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4774 313bcead Iustin Pop
      }
4775 313bcead Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4776 313bcead Iustin Pop
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
4777 313bcead Iustin Pop
                                       self.op.target_node]
4778 313bcead Iustin Pop
    return env, nl, nl
4779 313bcead Iustin Pop
4780 313bcead Iustin Pop
  def CheckPrereq(self):
4781 313bcead Iustin Pop
    """Check prerequisites.
4782 313bcead Iustin Pop

4783 313bcead Iustin Pop
    This checks that the instance is in the cluster.
4784 313bcead Iustin Pop

4785 313bcead Iustin Pop
    """
4786 313bcead Iustin Pop
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4787 313bcead Iustin Pop
    assert self.instance is not None, \
4788 313bcead Iustin Pop
      "Cannot retrieve locked instance %s" % self.op.instance_name
4789 313bcead Iustin Pop
4790 313bcead Iustin Pop
    node = self.cfg.GetNodeInfo(self.op.target_node)
4791 313bcead Iustin Pop
    assert node is not None, \
4792 313bcead Iustin Pop
      "Cannot retrieve locked node %s" % self.op.target_node
4793 313bcead Iustin Pop
4794 313bcead Iustin Pop
    self.target_node = target_node = node.name
4795 313bcead Iustin Pop
4796 313bcead Iustin Pop
    if target_node == instance.primary_node:
4797 313bcead Iustin Pop
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
4798 5c983ee5 Iustin Pop
                                 (instance.name, target_node),
4799 5c983ee5 Iustin Pop
                                 errors.ECODE_STATE)
4800 313bcead Iustin Pop
4801 313bcead Iustin Pop
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4802 313bcead Iustin Pop
4803 313bcead Iustin Pop
    for idx, dsk in enumerate(instance.disks):
4804 313bcead Iustin Pop
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
4805 313bcead Iustin Pop
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
4806 d1b83918 Iustin Pop
                                   " cannot copy" % idx, errors.ECODE_STATE)
4807 313bcead Iustin Pop
4808 313bcead Iustin Pop
    _CheckNodeOnline(self, target_node)
4809 313bcead Iustin Pop
    _CheckNodeNotDrained(self, target_node)
4810 313bcead Iustin Pop
4811 313bcead Iustin Pop
    if instance.admin_up:
4812 313bcead Iustin Pop
      # check memory requirements on the secondary node
4813 313bcead Iustin Pop
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
4814 313bcead Iustin Pop
                           instance.name, bep[constants.BE_MEMORY],
4815 313bcead Iustin Pop
                           instance.hypervisor)
4816 313bcead Iustin Pop
    else:
4817 313bcead Iustin Pop
      self.LogInfo("Not checking memory on the secondary node as"
4818 313bcead Iustin Pop
                   " instance will not be started")
4819 313bcead Iustin Pop
4820 313bcead Iustin Pop
    # check bridge existance
4821 313bcead Iustin Pop
    _CheckInstanceBridgesExist(self, instance, node=target_node)
4822 313bcead Iustin Pop
4823 313bcead Iustin Pop
  def Exec(self, feedback_fn):
4824 313bcead Iustin Pop
    """Move an instance.
4825 313bcead Iustin Pop

4826 313bcead Iustin Pop
    The move is done by shutting it down on its present node, copying
4827 313bcead Iustin Pop
    the data over (slow) and starting it on the new node.
4828 313bcead Iustin Pop

4829 313bcead Iustin Pop
    """
4830 313bcead Iustin Pop
    instance = self.instance
4831 313bcead Iustin Pop
4832 313bcead Iustin Pop
    source_node = instance.primary_node
4833 313bcead Iustin Pop
    target_node = self.target_node
4834 313bcead Iustin Pop
4835 313bcead Iustin Pop
    self.LogInfo("Shutting down instance %s on source node %s",
4836 313bcead Iustin Pop
                 instance.name, source_node)
4837 313bcead Iustin Pop
4838 17c3f802 Guido Trotter
    result = self.rpc.call_instance_shutdown(source_node, instance,
4839 17c3f802 Guido Trotter
                                             self.shutdown_timeout)
4840 313bcead Iustin Pop
    msg = result.fail_msg
4841 313bcead Iustin Pop
    if msg:
4842 313bcead Iustin Pop
      if self.op.ignore_consistency:
4843 313bcead Iustin Pop
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
4844 313bcead Iustin Pop
                             " Proceeding anyway. Please make sure node"
4845 313bcead Iustin Pop
                             " %s is down. Error details: %s",
4846 313bcead Iustin Pop
                             instance.name, source_node, source_node, msg)
4847 313bcead Iustin Pop
      else:
4848 313bcead Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on"
4849 313bcead Iustin Pop
                                 " node %s: %s" %
4850 313bcead Iustin Pop
                                 (instance.name, source_node, msg))
4851 313bcead Iustin Pop
4852 313bcead Iustin Pop
    # create the target disks
4853 313bcead Iustin Pop
    try:
4854 313bcead Iustin Pop
      _CreateDisks(self, instance, target_node=target_node)
4855 313bcead Iustin Pop
    except errors.OpExecError:
4856 313bcead Iustin Pop
      self.LogWarning("Device creation failed, reverting...")
4857 313bcead Iustin Pop
      try:
4858 313bcead Iustin Pop
        _RemoveDisks(self, instance, target_node=target_node)
4859 313bcead Iustin Pop
      finally:
4860 313bcead Iustin Pop
        self.cfg.ReleaseDRBDMinors(instance.name)
4861 313bcead Iustin Pop
        raise
4862 313bcead Iustin Pop
4863 313bcead Iustin Pop
    cluster_name = self.cfg.GetClusterInfo().cluster_name
4864 313bcead Iustin Pop
4865 313bcead Iustin Pop
    errs = []
4866 313bcead Iustin Pop
    # activate, get path, copy the data over
4867 313bcead Iustin Pop
    for idx, disk in enumerate(instance.disks):
4868 313bcead Iustin Pop
      self.LogInfo("Copying data for disk %d", idx)
4869 313bcead Iustin Pop
      result = self.rpc.call_blockdev_assemble(target_node, disk,
4870 313bcead Iustin Pop
                                               instance.name, True)
4871 313bcead Iustin Pop
      if result.fail_msg:
4872 313bcead Iustin Pop
        self.LogWarning("Can't assemble newly created disk %d: %s",
4873 313bcead Iustin Pop
                        idx, result.fail_msg)
4874 313bcead Iustin Pop
        errs.append(result.fail_msg)
4875 313bcead Iustin Pop
        break
4876 313bcead Iustin Pop
      dev_path = result.payload
4877 313bcead Iustin Pop
      result = self.rpc.call_blockdev_export(source_node, disk,
4878 313bcead Iustin Pop
                                             target_node, dev_path,
4879 313bcead Iustin Pop
                                             cluster_name)
4880 313bcead Iustin Pop
      if result.fail_msg:
4881 313bcead Iustin Pop
        self.LogWarning("Can't copy data over for disk %d: %s",
4882 313bcead Iustin Pop
                        idx, result.fail_msg)
4883 313bcead Iustin Pop
        errs.append(result.fail_msg)
4884 313bcead Iustin Pop
        break
4885 313bcead Iustin Pop
4886 313bcead Iustin Pop
    if errs:
4887 313bcead Iustin Pop
      self.LogWarning("Some disks failed to copy, aborting")
4888 313bcead Iustin Pop
      try:
4889 313bcead Iustin Pop
        _RemoveDisks(self, instance, target_node=target_node)
4890 313bcead Iustin Pop
      finally:
4891 313bcead Iustin Pop
        self.cfg.ReleaseDRBDMinors(instance.name)
4892 313bcead Iustin Pop
        raise errors.OpExecError("Errors during disk copy: %s" %
4893 313bcead Iustin Pop
                                 (",".join(errs),))
4894 313bcead Iustin Pop
4895 313bcead Iustin Pop
    instance.primary_node = target_node
4896 a4eae71f Michael Hanselmann
    self.cfg.Update(instance, feedback_fn)
4897 313bcead Iustin Pop
4898 313bcead Iustin Pop
    self.LogInfo("Removing the disks on the original node")
4899 313bcead Iustin Pop
    _RemoveDisks(self, instance, target_node=source_node)
4900 313bcead Iustin Pop
4901 313bcead Iustin Pop
    # Only start the instance if it's marked as up
4902 313bcead Iustin Pop
    if instance.admin_up:
4903 313bcead Iustin Pop
      self.LogInfo("Starting instance %s on node %s",
4904 313bcead Iustin Pop
                   instance.name, target_node)
4905 313bcead Iustin Pop
4906 313bcead Iustin Pop
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
4907 313bcead Iustin Pop
                                           ignore_secondaries=True)
4908 313bcead Iustin Pop
      if not disks_ok:
4909 313bcead Iustin Pop
        _ShutdownInstanceDisks(self, instance)
4910 313bcead Iustin Pop
        raise errors.OpExecError("Can't activate the instance's disks")
4911 313bcead Iustin Pop
4912 313bcead Iustin Pop
      result = self.rpc.call_instance_start(target_node, instance, None, None)
4913 313bcead Iustin Pop
      msg = result.fail_msg
4914 313bcead Iustin Pop
      if msg:
4915 313bcead Iustin Pop
        _ShutdownInstanceDisks(self, instance)
4916 313bcead Iustin Pop
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
4917 313bcead Iustin Pop
                                 (instance.name, target_node, msg))
4918 313bcead Iustin Pop
4919 313bcead Iustin Pop
4920 80cb875c Michael Hanselmann
class LUMigrateNode(LogicalUnit):
4921 80cb875c Michael Hanselmann
  """Migrate all instances from a node.
4922 80cb875c Michael Hanselmann

4923 80cb875c Michael Hanselmann
  """
4924 80cb875c Michael Hanselmann
  HPATH = "node-migrate"
4925 80cb875c Michael Hanselmann
  HTYPE = constants.HTYPE_NODE
4926 80cb875c Michael Hanselmann
  _OP_REQP = ["node_name", "live"]
4927 80cb875c Michael Hanselmann
  REQ_BGL = False
4928 80cb875c Michael Hanselmann
4929 80cb875c Michael Hanselmann
  def ExpandNames(self):
4930 80cb875c Michael Hanselmann
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
4931 80cb875c Michael Hanselmann
    if self.op.node_name is None:
4932 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
4933 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
4934 80cb875c Michael Hanselmann
4935 80cb875c Michael Hanselmann
    self.needed_locks = {
4936 80cb875c Michael Hanselmann
      locking.LEVEL_NODE: [self.op.node_name],
4937 80cb875c Michael Hanselmann
      }
4938 80cb875c Michael Hanselmann
4939 80cb875c Michael Hanselmann
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4940 80cb875c Michael Hanselmann
4941 80cb875c Michael Hanselmann
    # Create tasklets for migrating instances for all instances on this node
4942 80cb875c Michael Hanselmann
    names = []
4943 80cb875c Michael Hanselmann
    tasklets = []
4944 80cb875c Michael Hanselmann
4945 80cb875c Michael Hanselmann
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
4946 80cb875c Michael Hanselmann
      logging.debug("Migrating instance %s", inst.name)
4947 80cb875c Michael Hanselmann
      names.append(inst.name)
4948 80cb875c Michael Hanselmann
4949 80cb875c Michael Hanselmann
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
4950 80cb875c Michael Hanselmann
4951 80cb875c Michael Hanselmann
    self.tasklets = tasklets
4952 80cb875c Michael Hanselmann
4953 80cb875c Michael Hanselmann
    # Declare instance locks
4954 80cb875c Michael Hanselmann
    self.needed_locks[locking.LEVEL_INSTANCE] = names
4955 80cb875c Michael Hanselmann
4956 80cb875c Michael Hanselmann
  def DeclareLocks(self, level):
4957 80cb875c Michael Hanselmann
    if level == locking.LEVEL_NODE:
4958 80cb875c Michael Hanselmann
      self._LockInstancesNodes()
4959 80cb875c Michael Hanselmann
4960 80cb875c Michael Hanselmann
  def BuildHooksEnv(self):
4961 80cb875c Michael Hanselmann
    """Build hooks env.
4962 80cb875c Michael Hanselmann

4963 80cb875c Michael Hanselmann
    This runs on the master, the primary and all the secondaries.
4964 80cb875c Michael Hanselmann

4965 80cb875c Michael Hanselmann
    """
4966 80cb875c Michael Hanselmann
    env = {
4967 80cb875c Michael Hanselmann
      "NODE_NAME": self.op.node_name,
4968 80cb875c Michael Hanselmann
      }
4969 80cb875c Michael Hanselmann
4970 80cb875c Michael Hanselmann
    nl = [self.cfg.GetMasterNode()]
4971 80cb875c Michael Hanselmann
4972 80cb875c Michael Hanselmann
    return (env, nl, nl)
4973 80cb875c Michael Hanselmann
4974 80cb875c Michael Hanselmann
4975 3e06e001 Michael Hanselmann
class TLMigrateInstance(Tasklet):
4976 3e06e001 Michael Hanselmann
  def __init__(self, lu, instance_name, live, cleanup):
4977 3e06e001 Michael Hanselmann
    """Initializes this class.
4978 3e06e001 Michael Hanselmann

4979 3e06e001 Michael Hanselmann
    """
4980 464243a7 Michael Hanselmann
    Tasklet.__init__(self, lu)
4981 464243a7 Michael Hanselmann
4982 3e06e001 Michael Hanselmann
    # Parameters
4983 3e06e001 Michael Hanselmann
    self.instance_name = instance_name
4984 3e06e001 Michael Hanselmann
    self.live = live
4985 3e06e001 Michael Hanselmann
    self.cleanup = cleanup
4986 3e06e001 Michael Hanselmann
4987 53c776b5 Iustin Pop
  def CheckPrereq(self):
4988 53c776b5 Iustin Pop
    """Check prerequisites.
4989 53c776b5 Iustin Pop

4990 53c776b5 Iustin Pop
    This checks that the instance is in the cluster.
4991 53c776b5 Iustin Pop

4992 53c776b5 Iustin Pop
    """
4993 53c776b5 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
4994 3e06e001 Michael Hanselmann
      self.cfg.ExpandInstanceName(self.instance_name))
4995 53c776b5 Iustin Pop
    if instance is None:
4996 53c776b5 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
4997 5c983ee5 Iustin Pop
                                 self.instance_name, errors.ECODE_NOENT)
4998 53c776b5 Iustin Pop
4999 53c776b5 Iustin Pop
    if instance.disk_template != constants.DT_DRBD8:
5000 53c776b5 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout is not"
5001 5c983ee5 Iustin Pop
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5002 53c776b5 Iustin Pop
5003 53c776b5 Iustin Pop
    secondary_nodes = instance.secondary_nodes
5004 53c776b5 Iustin Pop
    if not secondary_nodes:
5005 733a2b6a Iustin Pop
      raise errors.ConfigurationError("No secondary node but using"
5006 733a2b6a Iustin Pop
                                      " drbd8 disk template")
5007 53c776b5 Iustin Pop
5008 53c776b5 Iustin Pop
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5009 53c776b5 Iustin Pop
5010 53c776b5 Iustin Pop
    target_node = secondary_nodes[0]
5011 53c776b5 Iustin Pop
    # check memory requirements on the secondary node
5012 53c776b5 Iustin Pop
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
5013 53c776b5 Iustin Pop
                         instance.name, i_be[constants.BE_MEMORY],
5014 53c776b5 Iustin Pop
                         instance.hypervisor)
5015 53c776b5 Iustin Pop
5016 53c776b5 Iustin Pop
    # check bridge existance
5017 b165e77e Guido Trotter
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5018 53c776b5 Iustin Pop
5019 3e06e001 Michael Hanselmann
    if not self.cleanup:
5020 733a2b6a Iustin Pop
      _CheckNodeNotDrained(self, target_node)
5021 53c776b5 Iustin Pop
      result = self.rpc.call_instance_migratable(instance.primary_node,
5022 53c776b5 Iustin Pop
                                                 instance)
5023 045dd6d9 Iustin Pop
      result.Raise("Can't migrate, please use failover",
5024 045dd6d9 Iustin Pop
                   prereq=True, ecode=errors.ECODE_STATE)
5025 53c776b5 Iustin Pop
5026 53c776b5 Iustin Pop
    self.instance = instance
5027 53c776b5 Iustin Pop
5028 53c776b5 Iustin Pop
  def _WaitUntilSync(self):
5029 53c776b5 Iustin Pop
    """Poll with custom rpc for disk sync.
5030 53c776b5 Iustin Pop

5031 53c776b5 Iustin Pop
    This uses our own step-based rpc call.
5032 53c776b5 Iustin Pop

5033 53c776b5 Iustin Pop
    """
5034 53c776b5 Iustin Pop
    self.feedback_fn("* wait until resync is done")
5035 53c776b5 Iustin Pop
    all_done = False
5036 53c776b5 Iustin Pop
    while not all_done:
5037 53c776b5 Iustin Pop
      all_done = True
5038 53c776b5 Iustin Pop
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5039 53c776b5 Iustin Pop
                                            self.nodes_ip,
5040 53c776b5 Iustin Pop
                                            self.instance.disks)
5041 53c776b5 Iustin Pop
      min_percent = 100
5042 53c776b5 Iustin Pop
      for node, nres in result.items():
5043 4c4e4e1e Iustin Pop
        nres.Raise("Cannot resync disks on node %s" % node)
5044 0959c824 Iustin Pop
        node_done, node_percent = nres.payload
5045 53c776b5 Iustin Pop
        all_done = all_done and node_done
5046 53c776b5 Iustin Pop
        if node_percent is not None:
5047 53c776b5 Iustin Pop
          min_percent = min(min_percent, node_percent)
5048 53c776b5 Iustin Pop
      if not all_done:
5049 53c776b5 Iustin Pop
        if min_percent < 100:
5050 53c776b5 Iustin Pop
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5051 53c776b5 Iustin Pop
        time.sleep(2)
5052 53c776b5 Iustin Pop
5053 53c776b5 Iustin Pop
  def _EnsureSecondary(self, node):
5054 53c776b5 Iustin Pop
    """Demote a node to secondary.
5055 53c776b5 Iustin Pop

5056 53c776b5 Iustin Pop
    """
5057 53c776b5 Iustin Pop
    self.feedback_fn("* switching node %s to secondary mode" % node)
5058 53c776b5 Iustin Pop
5059 53c776b5 Iustin Pop
    for dev in self.instance.disks:
5060 53c776b5 Iustin Pop
      self.cfg.SetDiskID(dev, node)
5061 53c776b5 Iustin Pop
5062 53c776b5 Iustin Pop
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5063 53c776b5 Iustin Pop
                                          self.instance.disks)
5064 4c4e4e1e Iustin Pop
    result.Raise("Cannot change disk to secondary on node %s" % node)
5065 53c776b5 Iustin Pop
5066 53c776b5 Iustin Pop
  def _GoStandalone(self):
5067 53c776b5 Iustin Pop
    """Disconnect from the network.
5068 53c776b5 Iustin Pop

5069 53c776b5 Iustin Pop
    """
5070 53c776b5 Iustin Pop
    self.feedback_fn("* changing into standalone mode")
5071 53c776b5 Iustin Pop
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5072 53c776b5 Iustin Pop
                                               self.instance.disks)
5073 53c776b5 Iustin Pop
    for node, nres in result.items():
5074 4c4e4e1e Iustin Pop
      nres.Raise("Cannot disconnect disks node %s" % node)
5075 53c776b5 Iustin Pop
5076 53c776b5 Iustin Pop
  def _GoReconnect(self, multimaster):
5077 53c776b5 Iustin Pop
    """Reconnect to the network.
5078 53c776b5 Iustin Pop

5079 53c776b5 Iustin Pop
    """
5080 53c776b5 Iustin Pop
    if multimaster:
5081 53c776b5 Iustin Pop
      msg = "dual-master"
5082 53c776b5 Iustin Pop
    else:
5083 53c776b5 Iustin Pop
      msg = "single-master"
5084 53c776b5 Iustin Pop
    self.feedback_fn("* changing disks into %s mode" % msg)
5085 53c776b5 Iustin Pop
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5086 53c776b5 Iustin Pop
                                           self.instance.disks,
5087 53c776b5 Iustin Pop
                                           self.instance.name, multimaster)
5088 53c776b5 Iustin Pop
    for node, nres in result.items():
5089 4c4e4e1e Iustin Pop
      nres.Raise("Cannot change disks config on node %s" % node)
5090 53c776b5 Iustin Pop
5091 53c776b5 Iustin Pop
  def _ExecCleanup(self):
5092 53c776b5 Iustin Pop
    """Try to cleanup after a failed migration.
5093 53c776b5 Iustin Pop

5094 53c776b5 Iustin Pop
    The cleanup is done by:
5095 53c776b5 Iustin Pop
      - check that the instance is running only on one node
5096 53c776b5 Iustin Pop
        (and update the config if needed)
5097 53c776b5 Iustin Pop
      - change disks on its secondary node to secondary
5098 53c776b5 Iustin Pop
      - wait until disks are fully synchronized
5099 53c776b5 Iustin Pop
      - disconnect from the network
5100 53c776b5 Iustin Pop
      - change disks into single-master mode
5101 53c776b5 Iustin Pop
      - wait again until disks are fully synchronized
5102 53c776b5 Iustin Pop

5103 53c776b5 Iustin Pop
    """
5104 53c776b5 Iustin Pop
    instance = self.instance
5105 53c776b5 Iustin Pop
    target_node = self.target_node
5106 53c776b5 Iustin Pop
    source_node = self.source_node
5107 53c776b5 Iustin Pop
5108 53c776b5 Iustin Pop
    # check running on only one node
5109 53c776b5 Iustin Pop
    self.feedback_fn("* checking where the instance actually runs"
5110 53c776b5 Iustin Pop
                     " (if this hangs, the hypervisor might be in"
5111 53c776b5 Iustin Pop
                     " a bad state)")
5112 53c776b5 Iustin Pop
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5113 53c776b5 Iustin Pop
    for node, result in ins_l.items():
5114 4c4e4e1e Iustin Pop
      result.Raise("Can't contact node %s" % node)
5115 53c776b5 Iustin Pop
5116 aca13712 Iustin Pop
    runningon_source = instance.name in ins_l[source_node].payload
5117 aca13712 Iustin Pop
    runningon_target = instance.name in ins_l[target_node].payload
5118 53c776b5 Iustin Pop
5119 53c776b5 Iustin Pop
    if runningon_source and runningon_target:
5120 53c776b5 Iustin Pop
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5121 53c776b5 Iustin Pop
                               " or the hypervisor is confused. You will have"
5122 53c776b5 Iustin Pop
                               " to ensure manually that it runs only on one"
5123 53c776b5 Iustin Pop
                               " and restart this operation.")
5124 53c776b5 Iustin Pop
5125 53c776b5 Iustin Pop
    if not (runningon_source or runningon_target):
5126 53c776b5 Iustin Pop
      raise errors.OpExecError("Instance does not seem to be running at all."
5127 53c776b5 Iustin Pop
                               " In this case, it's safer to repair by"
5128 53c776b5 Iustin Pop
                               " running 'gnt-instance stop' to ensure disk"
5129 53c776b5 Iustin Pop
                               " shutdown, and then restarting it.")
5130 53c776b5 Iustin Pop
5131 53c776b5 Iustin Pop
    if runningon_target:
5132 53c776b5 Iustin Pop
      # the migration has actually succeeded, we need to update the config
5133 53c776b5 Iustin Pop
      self.feedback_fn("* instance running on secondary node (%s),"
5134 53c776b5 Iustin Pop
                       " updating config" % target_node)
5135 53c776b5 Iustin Pop
      instance.primary_node = target_node
5136 a4eae71f Michael Hanselmann
      self.cfg.Update(instance, self.feedback_fn)
5137 53c776b5 Iustin Pop
      demoted_node = source_node
5138 53c776b5 Iustin Pop
    else:
5139 53c776b5 Iustin Pop
      self.feedback_fn("* instance confirmed to be running on its"
5140 53c776b5 Iustin Pop
                       " primary node (%s)" % source_node)
5141 53c776b5 Iustin Pop
      demoted_node = target_node
5142 53c776b5 Iustin Pop
5143 53c776b5 Iustin Pop
    self._EnsureSecondary(demoted_node)
5144 53c776b5 Iustin Pop
    try:
5145 53c776b5 Iustin Pop
      self._WaitUntilSync()
5146 53c776b5 Iustin Pop
    except errors.OpExecError:
5147 53c776b5 Iustin Pop
      # we ignore here errors, since if the device is standalone, it
5148 53c776b5 Iustin Pop
      # won't be able to sync
5149 53c776b5 Iustin Pop
      pass
5150 53c776b5 Iustin Pop
    self._GoStandalone()
5151 53c776b5 Iustin Pop
    self._GoReconnect(False)
5152 53c776b5 Iustin Pop
    self._WaitUntilSync()
5153 53c776b5 Iustin Pop
5154 53c776b5 Iustin Pop
    self.feedback_fn("* done")
5155 53c776b5 Iustin Pop
5156 6906a9d8 Guido Trotter
  def _RevertDiskStatus(self):
5157 6906a9d8 Guido Trotter
    """Try to revert the disk status after a failed migration.
5158 6906a9d8 Guido Trotter

5159 6906a9d8 Guido Trotter
    """
5160 6906a9d8 Guido Trotter
    target_node = self.target_node
5161 6906a9d8 Guido Trotter
    try:
5162 6906a9d8 Guido Trotter
      self._EnsureSecondary(target_node)
5163 6906a9d8 Guido Trotter
      self._GoStandalone()
5164 6906a9d8 Guido Trotter
      self._GoReconnect(False)
5165 6906a9d8 Guido Trotter
      self._WaitUntilSync()
5166 6906a9d8 Guido Trotter
    except errors.OpExecError, err:
5167 3e06e001 Michael Hanselmann
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5168 3e06e001 Michael Hanselmann
                         " drives: error '%s'\n"
5169 3e06e001 Michael Hanselmann
                         "Please look and recover the instance status" %
5170 3e06e001 Michael Hanselmann
                         str(err))
5171 6906a9d8 Guido Trotter
5172 6906a9d8 Guido Trotter
  def _AbortMigration(self):
5173 6906a9d8 Guido Trotter
    """Call the hypervisor code to abort a started migration.
5174 6906a9d8 Guido Trotter

5175 6906a9d8 Guido Trotter
    """
5176 6906a9d8 Guido Trotter
    instance = self.instance
5177 6906a9d8 Guido Trotter
    target_node = self.target_node
5178 6906a9d8 Guido Trotter
    migration_info = self.migration_info
5179 6906a9d8 Guido Trotter
5180 6906a9d8 Guido Trotter
    abort_result = self.rpc.call_finalize_migration(target_node,
5181 6906a9d8 Guido Trotter
                                                    instance,
5182 6906a9d8 Guido Trotter
                                                    migration_info,
5183 6906a9d8 Guido Trotter
                                                    False)
5184 4c4e4e1e Iustin Pop
    abort_msg = abort_result.fail_msg
5185 6906a9d8 Guido Trotter
    if abort_msg:
5186 099c52ad Iustin Pop
      logging.error("Aborting migration failed on target node %s: %s",
5187 099c52ad Iustin Pop
                    target_node, abort_msg)
5188 6906a9d8 Guido Trotter
      # Don't raise an exception here, as we stil have to try to revert the
5189 6906a9d8 Guido Trotter
      # disk status, even if this step failed.
5190 6906a9d8 Guido Trotter
5191 53c776b5 Iustin Pop
  def _ExecMigration(self):
5192 53c776b5 Iustin Pop
    """Migrate an instance.
5193 53c776b5 Iustin Pop

5194 53c776b5 Iustin Pop
    The migrate is done by:
5195 53c776b5 Iustin Pop
      - change the disks into dual-master mode
5196 53c776b5 Iustin Pop
      - wait until disks are fully synchronized again
5197 53c776b5 Iustin Pop
      - migrate the instance
5198 53c776b5 Iustin Pop
      - change disks on the new secondary node (the old primary) to secondary
5199 53c776b5 Iustin Pop
      - wait until disks are fully synchronized
5200 53c776b5 Iustin Pop
      - change disks into single-master mode
5201 53c776b5 Iustin Pop

5202 53c776b5 Iustin Pop
    """
5203 53c776b5 Iustin Pop
    instance = self.instance
5204 53c776b5 Iustin Pop
    target_node = self.target_node
5205 53c776b5 Iustin Pop
    source_node = self.source_node
5206 53c776b5 Iustin Pop
5207 53c776b5 Iustin Pop
    self.feedback_fn("* checking disk consistency between source and target")
5208 53c776b5 Iustin Pop
    for dev in instance.disks:
5209 53c776b5 Iustin Pop
      if not _CheckDiskConsistency(self, dev, target_node, False):
5210 53c776b5 Iustin Pop
        raise errors.OpExecError("Disk %s is degraded or not fully"
5211 53c776b5 Iustin Pop
                                 " synchronized on target node,"
5212 53c776b5 Iustin Pop
                                 " aborting migrate." % dev.iv_name)
5213 53c776b5 Iustin Pop
5214 6906a9d8 Guido Trotter
    # First get the migration information from the remote node
5215 6906a9d8 Guido Trotter
    result = self.rpc.call_migration_info(source_node, instance)
5216 4c4e4e1e Iustin Pop
    msg = result.fail_msg
5217 6906a9d8 Guido Trotter
    if msg:
5218 6906a9d8 Guido Trotter
      log_err = ("Failed fetching source migration information from %s: %s" %
5219 0959c824 Iustin Pop
                 (source_node, msg))
5220 6906a9d8 Guido Trotter
      logging.error(log_err)
5221 6906a9d8 Guido Trotter
      raise errors.OpExecError(log_err)
5222 6906a9d8 Guido Trotter
5223 0959c824 Iustin Pop
    self.migration_info = migration_info = result.payload
5224 6906a9d8 Guido Trotter
5225 6906a9d8 Guido Trotter
    # Then switch the disks to master/master mode
5226 53c776b5 Iustin Pop
    self._EnsureSecondary(target_node)
5227 53c776b5 Iustin Pop
    self._GoStandalone()
5228 53c776b5 Iustin Pop
    self._GoReconnect(True)
5229 53c776b5 Iustin Pop
    self._WaitUntilSync()
5230 53c776b5 Iustin Pop
5231 6906a9d8 Guido Trotter
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5232 6906a9d8 Guido Trotter
    result = self.rpc.call_accept_instance(target_node,
5233 6906a9d8 Guido Trotter
                                           instance,
5234 6906a9d8 Guido Trotter
                                           migration_info,
5235 6906a9d8 Guido Trotter
                                           self.nodes_ip[target_node])
5236 6906a9d8 Guido Trotter
5237 4c4e4e1e Iustin Pop
    msg = result.fail_msg
5238 6906a9d8 Guido Trotter
    if msg:
5239 6906a9d8 Guido Trotter
      logging.error("Instance pre-migration failed, trying to revert"
5240 6906a9d8 Guido Trotter
                    " disk status: %s", msg)
5241 78212a5d Iustin Pop
      self.feedback_fn("Pre-migration failed, aborting")
5242 6906a9d8 Guido Trotter
      self._AbortMigration()
5243 6906a9d8 Guido Trotter
      self._RevertDiskStatus()
5244 6906a9d8 Guido Trotter
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5245 6906a9d8 Guido Trotter
                               (instance.name, msg))
5246 6906a9d8 Guido Trotter
5247 53c776b5 Iustin Pop
    self.feedback_fn("* migrating instance to %s" % target_node)
5248 53c776b5 Iustin Pop
    time.sleep(10)
5249 53c776b5 Iustin Pop
    result = self.rpc.call_instance_migrate(source_node, instance,
5250 53c776b5 Iustin Pop
                                            self.nodes_ip[target_node],
5251 3e06e001 Michael Hanselmann
                                            self.live)
5252 4c4e4e1e Iustin Pop
    msg = result.fail_msg
5253 53c776b5 Iustin Pop
    if msg:
5254 53c776b5 Iustin Pop
      logging.error("Instance migration failed, trying to revert"
5255 53c776b5 Iustin Pop
                    " disk status: %s", msg)
5256 78212a5d Iustin Pop
      self.feedback_fn("Migration failed, aborting")
5257 6906a9d8 Guido Trotter
      self._AbortMigration()
5258 6906a9d8 Guido Trotter
      self._RevertDiskStatus()
5259 53c776b5 Iustin Pop
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5260 53c776b5 Iustin Pop
                               (instance.name, msg))
5261 53c776b5 Iustin Pop
    time.sleep(10)
5262 53c776b5 Iustin Pop
5263 53c776b5 Iustin Pop
    instance.primary_node = target_node
5264 53c776b5 Iustin Pop
    # distribute new instance config to the other nodes
5265 a4eae71f Michael Hanselmann
    self.cfg.Update(instance, self.feedback_fn)
5266 53c776b5 Iustin Pop
5267 6906a9d8 Guido Trotter
    result = self.rpc.call_finalize_migration(target_node,
5268 6906a9d8 Guido Trotter
                                              instance,
5269 6906a9d8 Guido Trotter
                                              migration_info,
5270 6906a9d8 Guido Trotter
                                              True)
5271 4c4e4e1e Iustin Pop
    msg = result.fail_msg
5272 6906a9d8 Guido Trotter
    if msg:
5273 6906a9d8 Guido Trotter
      logging.error("Instance migration succeeded, but finalization failed:"
5274 099c52ad Iustin Pop
                    " %s", msg)
5275 6906a9d8 Guido Trotter
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5276 6906a9d8 Guido Trotter
                               msg)
5277 6906a9d8 Guido Trotter
5278 53c776b5 Iustin Pop
    self._EnsureSecondary(source_node)
5279 53c776b5 Iustin Pop
    self._WaitUntilSync()
5280 53c776b5 Iustin Pop
    self._GoStandalone()
5281 53c776b5 Iustin Pop
    self._GoReconnect(False)
5282 53c776b5 Iustin Pop
    self._WaitUntilSync()
5283 53c776b5 Iustin Pop
5284 53c776b5 Iustin Pop
    self.feedback_fn("* done")
5285 53c776b5 Iustin Pop
5286 53c776b5 Iustin Pop
  def Exec(self, feedback_fn):
5287 53c776b5 Iustin Pop
    """Perform the migration.
5288 53c776b5 Iustin Pop

5289 53c776b5 Iustin Pop
    """
5290 80cb875c Michael Hanselmann
    feedback_fn("Migrating instance %s" % self.instance.name)
5291 80cb875c Michael Hanselmann
5292 53c776b5 Iustin Pop
    self.feedback_fn = feedback_fn
5293 53c776b5 Iustin Pop
5294 53c776b5 Iustin Pop
    self.source_node = self.instance.primary_node
5295 53c776b5 Iustin Pop
    self.target_node = self.instance.secondary_nodes[0]
5296 53c776b5 Iustin Pop
    self.all_nodes = [self.source_node, self.target_node]
5297 53c776b5 Iustin Pop
    self.nodes_ip = {
5298 53c776b5 Iustin Pop
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5299 53c776b5 Iustin Pop
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5300 53c776b5 Iustin Pop
      }
5301 3e06e001 Michael Hanselmann
5302 3e06e001 Michael Hanselmann
    if self.cleanup:
5303 53c776b5 Iustin Pop
      return self._ExecCleanup()
5304 53c776b5 Iustin Pop
    else:
5305 53c776b5 Iustin Pop
      return self._ExecMigration()
5306 53c776b5 Iustin Pop
5307 53c776b5 Iustin Pop
5308 428958aa Iustin Pop
def _CreateBlockDev(lu, node, instance, device, force_create,
5309 428958aa Iustin Pop
                    info, force_open):
5310 428958aa Iustin Pop
  """Create a tree of block devices on a given node.
5311 a8083063 Iustin Pop

5312 a8083063 Iustin Pop
  If this device type has to be created on secondaries, create it and
5313 a8083063 Iustin Pop
  all its children.
5314 a8083063 Iustin Pop

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

5317 428958aa Iustin Pop
  @param lu: the lu on whose behalf we execute
5318 428958aa Iustin Pop
  @param node: the node on which to create the device
5319 428958aa Iustin Pop
  @type instance: L{objects.Instance}
5320 428958aa Iustin Pop
  @param instance: the instance which owns the device
5321 428958aa Iustin Pop
  @type device: L{objects.Disk}
5322 428958aa Iustin Pop
  @param device: the device to create
5323 428958aa Iustin Pop
  @type force_create: boolean
5324 428958aa Iustin Pop
  @param force_create: whether to force creation of this device; this
5325 428958aa Iustin Pop
      will be change to True whenever we find a device which has
5326 428958aa Iustin Pop
      CreateOnSecondary() attribute
5327 428958aa Iustin Pop
  @param info: the extra 'metadata' we should attach to the device
5328 428958aa Iustin Pop
      (this will be represented as a LVM tag)
5329 428958aa Iustin Pop
  @type force_open: boolean
5330 428958aa Iustin Pop
  @param force_open: this parameter will be passes to the
5331 821d1bd1 Iustin Pop
      L{backend.BlockdevCreate} function where it specifies
5332 428958aa Iustin Pop
      whether we run on primary or not, and it affects both
5333 428958aa Iustin Pop
      the child assembly and the device own Open() execution
5334 428958aa Iustin Pop

5335 a8083063 Iustin Pop
  """
5336 a8083063 Iustin Pop
  if device.CreateOnSecondary():
5337 428958aa Iustin Pop
    force_create = True
5338 796cab27 Iustin Pop
5339 a8083063 Iustin Pop
  if device.children:
5340 a8083063 Iustin Pop
    for child in device.children:
5341 428958aa Iustin Pop
      _CreateBlockDev(lu, node, instance, child, force_create,
5342 428958aa Iustin Pop
                      info, force_open)
5343 a8083063 Iustin Pop
5344 428958aa Iustin Pop
  if not force_create:
5345 796cab27 Iustin Pop
    return
5346 796cab27 Iustin Pop
5347 de12473a Iustin Pop
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5348 de12473a Iustin Pop
5349 de12473a Iustin Pop
5350 de12473a Iustin Pop
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5351 de12473a Iustin Pop
  """Create a single block device on a given node.
5352 de12473a Iustin Pop

5353 de12473a Iustin Pop
  This will not recurse over children of the device, so they must be
5354 de12473a Iustin Pop
  created in advance.
5355 de12473a Iustin Pop

5356 de12473a Iustin Pop
  @param lu: the lu on whose behalf we execute
5357 de12473a Iustin Pop
  @param node: the node on which to create the device
5358 de12473a Iustin Pop
  @type instance: L{objects.Instance}
5359 de12473a Iustin Pop
  @param instance: the instance which owns the device
5360 de12473a Iustin Pop
  @type device: L{objects.Disk}
5361 de12473a Iustin Pop
  @param device: the device to create
5362 de12473a Iustin Pop
  @param info: the extra 'metadata' we should attach to the device
5363 de12473a Iustin Pop
      (this will be represented as a LVM tag)
5364 de12473a Iustin Pop
  @type force_open: boolean
5365 de12473a Iustin Pop
  @param force_open: this parameter will be passes to the
5366 821d1bd1 Iustin Pop
      L{backend.BlockdevCreate} function where it specifies
5367 de12473a Iustin Pop
      whether we run on primary or not, and it affects both
5368 de12473a Iustin Pop
      the child assembly and the device own Open() execution
5369 de12473a Iustin Pop

5370 de12473a Iustin Pop
  """
5371 b9bddb6b Iustin Pop
  lu.cfg.SetDiskID(device, node)
5372 7d81697f Iustin Pop
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5373 428958aa Iustin Pop
                                       instance.name, force_open, info)
5374 4c4e4e1e Iustin Pop
  result.Raise("Can't create block device %s on"
5375 4c4e4e1e Iustin Pop
               " node %s for instance %s" % (device, node, instance.name))
5376 a8083063 Iustin Pop
  if device.physical_id is None:
5377 0959c824 Iustin Pop
    device.physical_id = result.payload
5378 a8083063 Iustin Pop
5379 a8083063 Iustin Pop
5380 b9bddb6b Iustin Pop
def _GenerateUniqueNames(lu, exts):
5381 923b1523 Iustin Pop
  """Generate a suitable LV name.
5382 923b1523 Iustin Pop

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

5385 923b1523 Iustin Pop
  """
5386 923b1523 Iustin Pop
  results = []
5387 923b1523 Iustin Pop
  for val in exts:
5388 4fae38c5 Guido Trotter
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
5389 923b1523 Iustin Pop
    results.append("%s%s" % (new_id, val))
5390 923b1523 Iustin Pop
  return results
5391 923b1523 Iustin Pop
5392 923b1523 Iustin Pop
5393 b9bddb6b Iustin Pop
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5394 ffa1c0dc Iustin Pop
                         p_minor, s_minor):
5395 a1f445d3 Iustin Pop
  """Generate a drbd8 device complete with its children.
5396 a1f445d3 Iustin Pop

5397 a1f445d3 Iustin Pop
  """
5398 b9bddb6b Iustin Pop
  port = lu.cfg.AllocatePort()
5399 b9bddb6b Iustin Pop
  vgname = lu.cfg.GetVGName()
5400 afa1386e Guido Trotter
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
5401 a1f445d3 Iustin Pop
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5402 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[0]))
5403 a1f445d3 Iustin Pop
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5404 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[1]))
5405 a1f445d3 Iustin Pop
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5406 ffa1c0dc Iustin Pop
                          logical_id=(primary, secondary, port,
5407 f9518d38 Iustin Pop
                                      p_minor, s_minor,
5408 f9518d38 Iustin Pop
                                      shared_secret),
5409 ffa1c0dc Iustin Pop
                          children=[dev_data, dev_meta],
5410 a1f445d3 Iustin Pop
                          iv_name=iv_name)
5411 a1f445d3 Iustin Pop
  return drbd_dev
5412 a1f445d3 Iustin Pop
5413 7c0d6283 Michael Hanselmann
5414 b9bddb6b Iustin Pop
def _GenerateDiskTemplate(lu, template_name,
5415 a8083063 Iustin Pop
                          instance_name, primary_node,
5416 08db7c5c Iustin Pop
                          secondary_nodes, disk_info,
5417 e2a65344 Iustin Pop
                          file_storage_dir, file_driver,
5418 e2a65344 Iustin Pop
                          base_index):
5419 a8083063 Iustin Pop
  """Generate the entire disk layout for a given template type.
5420 a8083063 Iustin Pop

5421 a8083063 Iustin Pop
  """
5422 a8083063 Iustin Pop
  #TODO: compute space requirements
5423 a8083063 Iustin Pop
5424 b9bddb6b Iustin Pop
  vgname = lu.cfg.GetVGName()
5425 08db7c5c Iustin Pop
  disk_count = len(disk_info)
5426 08db7c5c Iustin Pop
  disks = []
5427 3517d9b9 Manuel Franceschini
  if template_name == constants.DT_DISKLESS:
5428 08db7c5c Iustin Pop
    pass
5429 3517d9b9 Manuel Franceschini
  elif template_name == constants.DT_PLAIN:
5430 a8083063 Iustin Pop
    if len(secondary_nodes) != 0:
5431 a8083063 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
5432 923b1523 Iustin Pop
5433 fb4b324b Guido Trotter
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5434 08db7c5c Iustin Pop
                                      for i in range(disk_count)])
5435 08db7c5c Iustin Pop
    for idx, disk in enumerate(disk_info):
5436 e2a65344 Iustin Pop
      disk_index = idx + base_index
5437 08db7c5c Iustin Pop
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5438 08db7c5c Iustin Pop
                              logical_id=(vgname, names[idx]),
5439 6ec66eae Iustin Pop
                              iv_name="disk/%d" % disk_index,
5440 6ec66eae Iustin Pop
                              mode=disk["mode"])
5441 08db7c5c Iustin Pop
      disks.append(disk_dev)
5442 a1f445d3 Iustin Pop
  elif template_name == constants.DT_DRBD8:
5443 a1f445d3 Iustin Pop
    if len(secondary_nodes) != 1:
5444 a1f445d3 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
5445 a1f445d3 Iustin Pop
    remote_node = secondary_nodes[0]
5446 08db7c5c Iustin Pop
    minors = lu.cfg.AllocateDRBDMinor(
5447 08db7c5c Iustin Pop
      [primary_node, remote_node] * len(disk_info), instance_name)
5448 08db7c5c Iustin Pop
5449 e6c1ff2f Iustin Pop
    names = []
5450 fb4b324b Guido Trotter
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5451 e6c1ff2f Iustin Pop
                                               for i in range(disk_count)]):
5452 e6c1ff2f Iustin Pop
      names.append(lv_prefix + "_data")
5453 e6c1ff2f Iustin Pop
      names.append(lv_prefix + "_meta")
5454 08db7c5c Iustin Pop
    for idx, disk in enumerate(disk_info):
5455 112050d9 Iustin Pop
      disk_index = idx + base_index
5456 08db7c5c Iustin Pop
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5457 08db7c5c Iustin Pop
                                      disk["size"], names[idx*2:idx*2+2],
5458 e2a65344 Iustin Pop
                                      "disk/%d" % disk_index,
5459 08db7c5c Iustin Pop
                                      minors[idx*2], minors[idx*2+1])
5460 6ec66eae Iustin Pop
      disk_dev.mode = disk["mode"]
5461 08db7c5c Iustin Pop
      disks.append(disk_dev)
5462 0f1a06e3 Manuel Franceschini
  elif template_name == constants.DT_FILE:
5463 0f1a06e3 Manuel Franceschini
    if len(secondary_nodes) != 0:
5464 0f1a06e3 Manuel Franceschini
      raise errors.ProgrammerError("Wrong template configuration")
5465 0f1a06e3 Manuel Franceschini
5466 08db7c5c Iustin Pop
    for idx, disk in enumerate(disk_info):
5467 112050d9 Iustin Pop
      disk_index = idx + base_index
5468 08db7c5c Iustin Pop
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5469 e2a65344 Iustin Pop
                              iv_name="disk/%d" % disk_index,
5470 08db7c5c Iustin Pop
                              logical_id=(file_driver,
5471 08db7c5c Iustin Pop
                                          "%s/disk%d" % (file_storage_dir,
5472 43e99cff Guido Trotter
                                                         disk_index)),
5473 6ec66eae Iustin Pop
                              mode=disk["mode"])
5474 08db7c5c Iustin Pop
      disks.append(disk_dev)
5475 a8083063 Iustin Pop
  else:
5476 a8083063 Iustin Pop
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5477 a8083063 Iustin Pop
  return disks
5478 a8083063 Iustin Pop
5479 a8083063 Iustin Pop
5480 a0c3fea1 Michael Hanselmann
def _GetInstanceInfoText(instance):
5481 3ecf6786 Iustin Pop
  """Compute that text that should be added to the disk's metadata.
5482 3ecf6786 Iustin Pop

5483 3ecf6786 Iustin Pop
  """
5484 a0c3fea1 Michael Hanselmann
  return "originstname+%s" % instance.name
5485 a0c3fea1 Michael Hanselmann
5486 a0c3fea1 Michael Hanselmann
5487 621b7678 Iustin Pop
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5488 a8083063 Iustin Pop
  """Create all disks for an instance.
5489 a8083063 Iustin Pop

5490 a8083063 Iustin Pop
  This abstracts away some work from AddInstance.
5491 a8083063 Iustin Pop

5492 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
5493 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
5494 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
5495 e4376078 Iustin Pop
  @param instance: the instance whose disks we should create
5496 bd315bfa Iustin Pop
  @type to_skip: list
5497 bd315bfa Iustin Pop
  @param to_skip: list of indices to skip
5498 621b7678 Iustin Pop
  @type target_node: string
5499 621b7678 Iustin Pop
  @param target_node: if passed, overrides the target node for creation
5500 e4376078 Iustin Pop
  @rtype: boolean
5501 e4376078 Iustin Pop
  @return: the success of the creation
5502 a8083063 Iustin Pop

5503 a8083063 Iustin Pop
  """
5504 a0c3fea1 Michael Hanselmann
  info = _GetInstanceInfoText(instance)
5505 621b7678 Iustin Pop
  if target_node is None:
5506 621b7678 Iustin Pop
    pnode = instance.primary_node
5507 621b7678 Iustin Pop
    all_nodes = instance.all_nodes
5508 621b7678 Iustin Pop
  else:
5509 621b7678 Iustin Pop
    pnode = target_node
5510 621b7678 Iustin Pop
    all_nodes = [pnode]
5511 a0c3fea1 Michael Hanselmann
5512 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
5513 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5514 428958aa Iustin Pop
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5515 0f1a06e3 Manuel Franceschini
5516 4c4e4e1e Iustin Pop
    result.Raise("Failed to create directory '%s' on"
5517 9b4127eb Guido Trotter
                 " node %s" % (file_storage_dir, pnode))
5518 0f1a06e3 Manuel Franceschini
5519 24991749 Iustin Pop
  # Note: this needs to be kept in sync with adding of disks in
5520 24991749 Iustin Pop
  # LUSetInstanceParams
5521 bd315bfa Iustin Pop
  for idx, device in enumerate(instance.disks):
5522 bd315bfa Iustin Pop
    if to_skip and idx in to_skip:
5523 bd315bfa Iustin Pop
      continue
5524 9a4f63d1 Iustin Pop
    logging.info("Creating volume %s for instance %s",
5525 9a4f63d1 Iustin Pop
                 device.iv_name, instance.name)
5526 a8083063 Iustin Pop
    #HARDCODE
5527 621b7678 Iustin Pop
    for node in all_nodes:
5528 428958aa Iustin Pop
      f_create = node == pnode
5529 428958aa Iustin Pop
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5530 a8083063 Iustin Pop
5531 a8083063 Iustin Pop
5532 621b7678 Iustin Pop
def _RemoveDisks(lu, instance, target_node=None):
5533 a8083063 Iustin Pop
  """Remove all disks for an instance.
5534 a8083063 Iustin Pop

5535 a8083063 Iustin Pop
  This abstracts away some work from `AddInstance()` and
5536 a8083063 Iustin Pop
  `RemoveInstance()`. Note that in case some of the devices couldn't
5537 1d67656e Iustin Pop
  be removed, the removal will continue with the other ones (compare
5538 a8083063 Iustin Pop
  with `_CreateDisks()`).
5539 a8083063 Iustin Pop

5540 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
5541 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
5542 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
5543 e4376078 Iustin Pop
  @param instance: the instance whose disks we should remove
5544 621b7678 Iustin Pop
  @type target_node: string
5545 621b7678 Iustin Pop
  @param target_node: used to override the node on which to remove the disks
5546 e4376078 Iustin Pop
  @rtype: boolean
5547 e4376078 Iustin Pop
  @return: the success of the removal
5548 a8083063 Iustin Pop

5549 a8083063 Iustin Pop
  """
5550 9a4f63d1 Iustin Pop
  logging.info("Removing block devices for instance %s", instance.name)
5551 a8083063 Iustin Pop
5552 e1bc0878 Iustin Pop
  all_result = True
5553 a8083063 Iustin Pop
  for device in instance.disks:
5554 621b7678 Iustin Pop
    if target_node:
5555 621b7678 Iustin Pop
      edata = [(target_node, device)]
5556 621b7678 Iustin Pop
    else:
5557 621b7678 Iustin Pop
      edata = device.ComputeNodeTree(instance.primary_node)
5558 621b7678 Iustin Pop
    for node, disk in edata:
5559 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(disk, node)
5560 4c4e4e1e Iustin Pop
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5561 e1bc0878 Iustin Pop
      if msg:
5562 e1bc0878 Iustin Pop
        lu.LogWarning("Could not remove block device %s on node %s,"
5563 e1bc0878 Iustin Pop
                      " continuing anyway: %s", device.iv_name, node, msg)
5564 e1bc0878 Iustin Pop
        all_result = False
5565 0f1a06e3 Manuel Franceschini
5566 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
5567 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5568 dfc2a24c Guido Trotter
    if target_node:
5569 dfc2a24c Guido Trotter
      tgt = target_node
5570 621b7678 Iustin Pop
    else:
5571 dfc2a24c Guido Trotter
      tgt = instance.primary_node
5572 621b7678 Iustin Pop
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5573 621b7678 Iustin Pop
    if result.fail_msg:
5574 b2b8bcce Iustin Pop
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5575 621b7678 Iustin Pop
                    file_storage_dir, instance.primary_node, result.fail_msg)
5576 e1bc0878 Iustin Pop
      all_result = False
5577 0f1a06e3 Manuel Franceschini
5578 e1bc0878 Iustin Pop
  return all_result
5579 a8083063 Iustin Pop
5580 a8083063 Iustin Pop
5581 08db7c5c Iustin Pop
def _ComputeDiskSize(disk_template, disks):
5582 e2fe6369 Iustin Pop
  """Compute disk size requirements in the volume group
5583 e2fe6369 Iustin Pop

5584 e2fe6369 Iustin Pop
  """
5585 e2fe6369 Iustin Pop
  # Required free disk space as a function of disk and swap space
5586 e2fe6369 Iustin Pop
  req_size_dict = {
5587 e2fe6369 Iustin Pop
    constants.DT_DISKLESS: None,
5588 08db7c5c Iustin Pop
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5589 08db7c5c Iustin Pop
    # 128 MB are added for drbd metadata for each disk
5590 08db7c5c Iustin Pop
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
5591 e2fe6369 Iustin Pop
    constants.DT_FILE: None,
5592 e2fe6369 Iustin Pop
  }
5593 e2fe6369 Iustin Pop
5594 e2fe6369 Iustin Pop
  if disk_template not in req_size_dict:
5595 e2fe6369 Iustin Pop
    raise errors.ProgrammerError("Disk template '%s' size requirement"
5596 e2fe6369 Iustin Pop
                                 " is unknown" %  disk_template)
5597 e2fe6369 Iustin Pop
5598 e2fe6369 Iustin Pop
  return req_size_dict[disk_template]
5599 e2fe6369 Iustin Pop
5600 e2fe6369 Iustin Pop
5601 74409b12 Iustin Pop
def _CheckHVParams(lu, nodenames, hvname, hvparams):
5602 74409b12 Iustin Pop
  """Hypervisor parameter validation.
5603 74409b12 Iustin Pop

5604 74409b12 Iustin Pop
  This function abstract the hypervisor parameter validation to be
5605 74409b12 Iustin Pop
  used in both instance create and instance modify.
5606 74409b12 Iustin Pop

5607 74409b12 Iustin Pop
  @type lu: L{LogicalUnit}
5608 74409b12 Iustin Pop
  @param lu: the logical unit for which we check
5609 74409b12 Iustin Pop
  @type nodenames: list
5610 74409b12 Iustin Pop
  @param nodenames: the list of nodes on which we should check
5611 74409b12 Iustin Pop
  @type hvname: string
5612 74409b12 Iustin Pop
  @param hvname: the name of the hypervisor we should use
5613 74409b12 Iustin Pop
  @type hvparams: dict
5614 74409b12 Iustin Pop
  @param hvparams: the parameters which we need to check
5615 74409b12 Iustin Pop
  @raise errors.OpPrereqError: if the parameters are not valid
5616 74409b12 Iustin Pop

5617 74409b12 Iustin Pop
  """
5618 74409b12 Iustin Pop
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
5619 74409b12 Iustin Pop
                                                  hvname,
5620 74409b12 Iustin Pop
                                                  hvparams)
5621 74409b12 Iustin Pop
  for node in nodenames:
5622 781de953 Iustin Pop
    info = hvinfo[node]
5623 68c6f21c Iustin Pop
    if info.offline:
5624 68c6f21c Iustin Pop
      continue
5625 4c4e4e1e Iustin Pop
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
5626 74409b12 Iustin Pop
5627 74409b12 Iustin Pop
5628 a8083063 Iustin Pop
class LUCreateInstance(LogicalUnit):
5629 a8083063 Iustin Pop
  """Create an instance.
5630 a8083063 Iustin Pop

5631 a8083063 Iustin Pop
  """
5632 a8083063 Iustin Pop
  HPATH = "instance-add"
5633 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
5634 08db7c5c Iustin Pop
  _OP_REQP = ["instance_name", "disks", "disk_template",
5635 08db7c5c Iustin Pop
              "mode", "start",
5636 08db7c5c Iustin Pop
              "wait_for_sync", "ip_check", "nics",
5637 338e51e8 Iustin Pop
              "hvparams", "beparams"]
5638 7baf741d Guido Trotter
  REQ_BGL = False
5639 7baf741d Guido Trotter
5640 5f23e043 Iustin Pop
  def CheckArguments(self):
5641 5f23e043 Iustin Pop
    """Check arguments.
5642 5f23e043 Iustin Pop

5643 5f23e043 Iustin Pop
    """
5644 5f23e043 Iustin Pop
    # do not require name_check to ease forward/backward compatibility
5645 5f23e043 Iustin Pop
    # for tools
5646 5f23e043 Iustin Pop
    if not hasattr(self.op, "name_check"):
5647 5f23e043 Iustin Pop
      self.op.name_check = True
5648 5f23e043 Iustin Pop
    if self.op.ip_check and not self.op.name_check:
5649 5f23e043 Iustin Pop
      # TODO: make the ip check more flexible and not depend on the name check
5650 5f23e043 Iustin Pop
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
5651 5f23e043 Iustin Pop
                                 errors.ECODE_INVAL)
5652 5f23e043 Iustin Pop
5653 7baf741d Guido Trotter
  def _ExpandNode(self, node):
5654 7baf741d Guido Trotter
    """Expands and checks one node name.
5655 7baf741d Guido Trotter

5656 7baf741d Guido Trotter
    """
5657 7baf741d Guido Trotter
    node_full = self.cfg.ExpandNodeName(node)
5658 7baf741d Guido Trotter
    if node_full is None:
5659 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Unknown node %s" % node, errors.ECODE_NOENT)
5660 7baf741d Guido Trotter
    return node_full
5661 7baf741d Guido Trotter
5662 7baf741d Guido Trotter
  def ExpandNames(self):
5663 7baf741d Guido Trotter
    """ExpandNames for CreateInstance.
5664 7baf741d Guido Trotter

5665 7baf741d Guido Trotter
    Figure out the right locks for instance creation.
5666 7baf741d Guido Trotter

5667 7baf741d Guido Trotter
    """
5668 7baf741d Guido Trotter
    self.needed_locks = {}
5669 7baf741d Guido Trotter
5670 7baf741d Guido Trotter
    # set optional parameters to none if they don't exist
5671 6785674e Iustin Pop
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
5672 7baf741d Guido Trotter
      if not hasattr(self.op, attr):
5673 7baf741d Guido Trotter
        setattr(self.op, attr, None)
5674 7baf741d Guido Trotter
5675 4b2f38dd Iustin Pop
    # cheap checks, mostly valid constants given
5676 4b2f38dd Iustin Pop
5677 7baf741d Guido Trotter
    # verify creation mode
5678 7baf741d Guido Trotter
    if self.op.mode not in (constants.INSTANCE_CREATE,
5679 7baf741d Guido Trotter
                            constants.INSTANCE_IMPORT):
5680 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
5681 5c983ee5 Iustin Pop
                                 self.op.mode, errors.ECODE_INVAL)
5682 4b2f38dd Iustin Pop
5683 7baf741d Guido Trotter
    # disk template and mirror node verification
5684 7baf741d Guido Trotter
    if self.op.disk_template not in constants.DISK_TEMPLATES:
5685 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid disk template name",
5686 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
5687 7baf741d Guido Trotter
5688 4b2f38dd Iustin Pop
    if self.op.hypervisor is None:
5689 4b2f38dd Iustin Pop
      self.op.hypervisor = self.cfg.GetHypervisorType()
5690 4b2f38dd Iustin Pop
5691 8705eb96 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
5692 8705eb96 Iustin Pop
    enabled_hvs = cluster.enabled_hypervisors
5693 4b2f38dd Iustin Pop
    if self.op.hypervisor not in enabled_hvs:
5694 4b2f38dd Iustin Pop
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
5695 4b2f38dd Iustin Pop
                                 " cluster (%s)" % (self.op.hypervisor,
5696 5c983ee5 Iustin Pop
                                  ",".join(enabled_hvs)),
5697 5c983ee5 Iustin Pop
                                 errors.ECODE_STATE)
5698 4b2f38dd Iustin Pop
5699 6785674e Iustin Pop
    # check hypervisor parameter syntax (locally)
5700 a5728081 Guido Trotter
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5701 abe609b2 Guido Trotter
    filled_hvp = objects.FillDict(cluster.hvparams[self.op.hypervisor],
5702 8705eb96 Iustin Pop
                                  self.op.hvparams)
5703 6785674e Iustin Pop
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
5704 8705eb96 Iustin Pop
    hv_type.CheckParameterSyntax(filled_hvp)
5705 67fc3042 Iustin Pop
    self.hv_full = filled_hvp
5706 7736a5f2 Iustin Pop
    # check that we don't specify global parameters on an instance
5707 7736a5f2 Iustin Pop
    _CheckGlobalHvParams(self.op.hvparams)
5708 6785674e Iustin Pop
5709 338e51e8 Iustin Pop
    # fill and remember the beparams dict
5710 a5728081 Guido Trotter
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5711 4ef7f423 Guido Trotter
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
5712 338e51e8 Iustin Pop
                                    self.op.beparams)
5713 338e51e8 Iustin Pop
5714 7baf741d Guido Trotter
    #### instance parameters check
5715 7baf741d Guido Trotter
5716 7baf741d Guido Trotter
    # instance name verification
5717 5f23e043 Iustin Pop
    if self.op.name_check:
5718 5f23e043 Iustin Pop
      hostname1 = utils.GetHostInfo(self.op.instance_name)
5719 5f23e043 Iustin Pop
      self.op.instance_name = instance_name = hostname1.name
5720 5f23e043 Iustin Pop
      # used in CheckPrereq for ip ping check
5721 5f23e043 Iustin Pop
      self.check_ip = hostname1.ip
5722 5f23e043 Iustin Pop
    else:
5723 5f23e043 Iustin Pop
      instance_name = self.op.instance_name
5724 5f23e043 Iustin Pop
      self.check_ip = None
5725 7baf741d Guido Trotter
5726 7baf741d Guido Trotter
    # this is just a preventive check, but someone might still add this
5727 7baf741d Guido Trotter
    # instance in the meantime, and creation will fail at lock-add time
5728 7baf741d Guido Trotter
    if instance_name in self.cfg.GetInstanceList():
5729 7baf741d Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5730 5c983ee5 Iustin Pop
                                 instance_name, errors.ECODE_EXISTS)
5731 7baf741d Guido Trotter
5732 7baf741d Guido Trotter
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
5733 7baf741d Guido Trotter
5734 08db7c5c Iustin Pop
    # NIC buildup
5735 08db7c5c Iustin Pop
    self.nics = []
5736 9dce4771 Guido Trotter
    for idx, nic in enumerate(self.op.nics):
5737 9dce4771 Guido Trotter
      nic_mode_req = nic.get("mode", None)
5738 9dce4771 Guido Trotter
      nic_mode = nic_mode_req
5739 9dce4771 Guido Trotter
      if nic_mode is None:
5740 9dce4771 Guido Trotter
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
5741 9dce4771 Guido Trotter
5742 9dce4771 Guido Trotter
      # in routed mode, for the first nic, the default ip is 'auto'
5743 9dce4771 Guido Trotter
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
5744 9dce4771 Guido Trotter
        default_ip_mode = constants.VALUE_AUTO
5745 9dce4771 Guido Trotter
      else:
5746 9dce4771 Guido Trotter
        default_ip_mode = constants.VALUE_NONE
5747 9dce4771 Guido Trotter
5748 08db7c5c Iustin Pop
      # ip validity checks
5749 9dce4771 Guido Trotter
      ip = nic.get("ip", default_ip_mode)
5750 9dce4771 Guido Trotter
      if ip is None or ip.lower() == constants.VALUE_NONE:
5751 08db7c5c Iustin Pop
        nic_ip = None
5752 08db7c5c Iustin Pop
      elif ip.lower() == constants.VALUE_AUTO:
5753 5f23e043 Iustin Pop
        if not self.op.name_check:
5754 5f23e043 Iustin Pop
          raise errors.OpPrereqError("IP address set to auto but name checks"
5755 5f23e043 Iustin Pop
                                     " have been skipped. Aborting.",
5756 5f23e043 Iustin Pop
                                     errors.ECODE_INVAL)
5757 08db7c5c Iustin Pop
        nic_ip = hostname1.ip
5758 08db7c5c Iustin Pop
      else:
5759 08db7c5c Iustin Pop
        if not utils.IsValidIP(ip):
5760 08db7c5c Iustin Pop
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
5761 5c983ee5 Iustin Pop
                                     " like a valid IP" % ip,
5762 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
5763 08db7c5c Iustin Pop
        nic_ip = ip
5764 08db7c5c Iustin Pop
5765 b8716596 Michael Hanselmann
      # TODO: check the ip address for uniqueness
5766 9dce4771 Guido Trotter
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
5767 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
5768 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
5769 9dce4771 Guido Trotter
5770 08db7c5c Iustin Pop
      # MAC address verification
5771 08db7c5c Iustin Pop
      mac = nic.get("mac", constants.VALUE_AUTO)
5772 08db7c5c Iustin Pop
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5773 08db7c5c Iustin Pop
        if not utils.IsValidMac(mac.lower()):
5774 08db7c5c Iustin Pop
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
5775 5c983ee5 Iustin Pop
                                     mac, errors.ECODE_INVAL)
5776 87e43988 Iustin Pop
        else:
5777 36b66e6e Guido Trotter
          try:
5778 36b66e6e Guido Trotter
            self.cfg.ReserveMAC(mac, self.proc.GetECId())
5779 36b66e6e Guido Trotter
          except errors.ReservationError:
5780 87e43988 Iustin Pop
            raise errors.OpPrereqError("MAC address %s already in use"
5781 5c983ee5 Iustin Pop
                                       " in cluster" % mac,
5782 5c983ee5 Iustin Pop
                                       errors.ECODE_NOTUNIQUE)
5783 87e43988 Iustin Pop
5784 08db7c5c Iustin Pop
      # bridge verification
5785 9939547b Iustin Pop
      bridge = nic.get("bridge", None)
5786 9dce4771 Guido Trotter
      link = nic.get("link", None)
5787 9dce4771 Guido Trotter
      if bridge and link:
5788 29921401 Iustin Pop
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
5789 5c983ee5 Iustin Pop
                                   " at the same time", errors.ECODE_INVAL)
5790 9dce4771 Guido Trotter
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
5791 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
5792 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
5793 9dce4771 Guido Trotter
      elif bridge:
5794 9dce4771 Guido Trotter
        link = bridge
5795 9dce4771 Guido Trotter
5796 9dce4771 Guido Trotter
      nicparams = {}
5797 9dce4771 Guido Trotter
      if nic_mode_req:
5798 9dce4771 Guido Trotter
        nicparams[constants.NIC_MODE] = nic_mode_req
5799 9dce4771 Guido Trotter
      if link:
5800 9dce4771 Guido Trotter
        nicparams[constants.NIC_LINK] = link
5801 9dce4771 Guido Trotter
5802 9dce4771 Guido Trotter
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
5803 9dce4771 Guido Trotter
                                      nicparams)
5804 9dce4771 Guido Trotter
      objects.NIC.CheckParameterSyntax(check_params)
5805 9dce4771 Guido Trotter
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
5806 08db7c5c Iustin Pop
5807 08db7c5c Iustin Pop
    # disk checks/pre-build
5808 08db7c5c Iustin Pop
    self.disks = []
5809 08db7c5c Iustin Pop
    for disk in self.op.disks:
5810 08db7c5c Iustin Pop
      mode = disk.get("mode", constants.DISK_RDWR)
5811 08db7c5c Iustin Pop
      if mode not in constants.DISK_ACCESS_SET:
5812 08db7c5c Iustin Pop
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
5813 5c983ee5 Iustin Pop
                                   mode, errors.ECODE_INVAL)
5814 08db7c5c Iustin Pop
      size = disk.get("size", None)
5815 08db7c5c Iustin Pop
      if size is None:
5816 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
5817 08db7c5c Iustin Pop
      try:
5818 08db7c5c Iustin Pop
        size = int(size)
5819 08db7c5c Iustin Pop
      except ValueError:
5820 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
5821 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
5822 08db7c5c Iustin Pop
      self.disks.append({"size": size, "mode": mode})
5823 08db7c5c Iustin Pop
5824 7baf741d Guido Trotter
    # file storage checks
5825 7baf741d Guido Trotter
    if (self.op.file_driver and
5826 7baf741d Guido Trotter
        not self.op.file_driver in constants.FILE_DRIVER):
5827 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
5828 5c983ee5 Iustin Pop
                                 self.op.file_driver, errors.ECODE_INVAL)
5829 7baf741d Guido Trotter
5830 7baf741d Guido Trotter
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
5831 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("File storage directory path not absolute",
5832 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
5833 7baf741d Guido Trotter
5834 7baf741d Guido Trotter
    ### Node/iallocator related checks
5835 7baf741d Guido Trotter
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
5836 7baf741d Guido Trotter
      raise errors.OpPrereqError("One and only one of iallocator and primary"
5837 5c983ee5 Iustin Pop
                                 " node must be given",
5838 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
5839 7baf741d Guido Trotter
5840 7baf741d Guido Trotter
    if self.op.iallocator:
5841 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5842 7baf741d Guido Trotter
    else:
5843 7baf741d Guido Trotter
      self.op.pnode = self._ExpandNode(self.op.pnode)
5844 7baf741d Guido Trotter
      nodelist = [self.op.pnode]
5845 7baf741d Guido Trotter
      if self.op.snode is not None:
5846 7baf741d Guido Trotter
        self.op.snode = self._ExpandNode(self.op.snode)
5847 7baf741d Guido Trotter
        nodelist.append(self.op.snode)
5848 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = nodelist
5849 7baf741d Guido Trotter
5850 7baf741d Guido Trotter
    # in case of import lock the source node too
5851 7baf741d Guido Trotter
    if self.op.mode == constants.INSTANCE_IMPORT:
5852 7baf741d Guido Trotter
      src_node = getattr(self.op, "src_node", None)
5853 7baf741d Guido Trotter
      src_path = getattr(self.op, "src_path", None)
5854 7baf741d Guido Trotter
5855 b9322a9f Guido Trotter
      if src_path is None:
5856 b9322a9f Guido Trotter
        self.op.src_path = src_path = self.op.instance_name
5857 b9322a9f Guido Trotter
5858 b9322a9f Guido Trotter
      if src_node is None:
5859 b9322a9f Guido Trotter
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5860 b9322a9f Guido Trotter
        self.op.src_node = None
5861 b9322a9f Guido Trotter
        if os.path.isabs(src_path):
5862 b9322a9f Guido Trotter
          raise errors.OpPrereqError("Importing an instance from an absolute"
5863 5c983ee5 Iustin Pop
                                     " path requires a source node option.",
5864 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
5865 b9322a9f Guido Trotter
      else:
5866 b9322a9f Guido Trotter
        self.op.src_node = src_node = self._ExpandNode(src_node)
5867 b9322a9f Guido Trotter
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5868 b9322a9f Guido Trotter
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
5869 b9322a9f Guido Trotter
        if not os.path.isabs(src_path):
5870 b9322a9f Guido Trotter
          self.op.src_path = src_path = \
5871 b9322a9f Guido Trotter
            os.path.join(constants.EXPORT_DIR, src_path)
5872 7baf741d Guido Trotter
5873 f2c05717 Guido Trotter
      # On import force_variant must be True, because if we forced it at
5874 f2c05717 Guido Trotter
      # initial install, our only chance when importing it back is that it
5875 f2c05717 Guido Trotter
      # works again!
5876 f2c05717 Guido Trotter
      self.op.force_variant = True
5877 f2c05717 Guido Trotter
5878 7baf741d Guido Trotter
    else: # INSTANCE_CREATE
5879 7baf741d Guido Trotter
      if getattr(self.op, "os_type", None) is None:
5880 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("No guest OS specified",
5881 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
5882 f2c05717 Guido Trotter
      self.op.force_variant = getattr(self.op, "force_variant", False)
5883 a8083063 Iustin Pop
5884 538475ca Iustin Pop
  def _RunAllocator(self):
5885 538475ca Iustin Pop
    """Run the allocator based on input opcode.
5886 538475ca Iustin Pop

5887 538475ca Iustin Pop
    """
5888 08db7c5c Iustin Pop
    nics = [n.ToDict() for n in self.nics]
5889 923ddac0 Michael Hanselmann
    ial = IAllocator(self.cfg, self.rpc,
5890 29859cb7 Iustin Pop
                     mode=constants.IALLOCATOR_MODE_ALLOC,
5891 d1c2dd75 Iustin Pop
                     name=self.op.instance_name,
5892 d1c2dd75 Iustin Pop
                     disk_template=self.op.disk_template,
5893 d1c2dd75 Iustin Pop
                     tags=[],
5894 d1c2dd75 Iustin Pop
                     os=self.op.os_type,
5895 338e51e8 Iustin Pop
                     vcpus=self.be_full[constants.BE_VCPUS],
5896 338e51e8 Iustin Pop
                     mem_size=self.be_full[constants.BE_MEMORY],
5897 08db7c5c Iustin Pop
                     disks=self.disks,
5898 d1c2dd75 Iustin Pop
                     nics=nics,
5899 8cc7e742 Guido Trotter
                     hypervisor=self.op.hypervisor,
5900 29859cb7 Iustin Pop
                     )
5901 d1c2dd75 Iustin Pop
5902 d1c2dd75 Iustin Pop
    ial.Run(self.op.iallocator)
5903 d1c2dd75 Iustin Pop
5904 d1c2dd75 Iustin Pop
    if not ial.success:
5905 538475ca Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
5906 5c983ee5 Iustin Pop
                                 " iallocator '%s': %s" %
5907 5c983ee5 Iustin Pop
                                 (self.op.iallocator, ial.info),
5908 5c983ee5 Iustin Pop
                                 errors.ECODE_NORES)
5909 27579978 Iustin Pop
    if len(ial.nodes) != ial.required_nodes:
5910 538475ca Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5911 538475ca Iustin Pop
                                 " of nodes (%s), required %s" %
5912 97abc79f Iustin Pop
                                 (self.op.iallocator, len(ial.nodes),
5913 5c983ee5 Iustin Pop
                                  ial.required_nodes), errors.ECODE_FAULT)
5914 d1c2dd75 Iustin Pop
    self.op.pnode = ial.nodes[0]
5915 86d9d3bb Iustin Pop
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5916 86d9d3bb Iustin Pop
                 self.op.instance_name, self.op.iallocator,
5917 1f864b60 Iustin Pop
                 utils.CommaJoin(ial.nodes))
5918 27579978 Iustin Pop
    if ial.required_nodes == 2:
5919 d1c2dd75 Iustin Pop
      self.op.snode = ial.nodes[1]
5920 538475ca Iustin Pop
5921 a8083063 Iustin Pop
  def BuildHooksEnv(self):
5922 a8083063 Iustin Pop
    """Build hooks env.
5923 a8083063 Iustin Pop

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

5926 a8083063 Iustin Pop
    """
5927 a8083063 Iustin Pop
    env = {
5928 2c2690c9 Iustin Pop
      "ADD_MODE": self.op.mode,
5929 a8083063 Iustin Pop
      }
5930 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
5931 2c2690c9 Iustin Pop
      env["SRC_NODE"] = self.op.src_node
5932 2c2690c9 Iustin Pop
      env["SRC_PATH"] = self.op.src_path
5933 2c2690c9 Iustin Pop
      env["SRC_IMAGES"] = self.src_images
5934 396e1b78 Michael Hanselmann
5935 2c2690c9 Iustin Pop
    env.update(_BuildInstanceHookEnv(
5936 2c2690c9 Iustin Pop
      name=self.op.instance_name,
5937 396e1b78 Michael Hanselmann
      primary_node=self.op.pnode,
5938 396e1b78 Michael Hanselmann
      secondary_nodes=self.secondaries,
5939 4978db17 Iustin Pop
      status=self.op.start,
5940 ecb215b5 Michael Hanselmann
      os_type=self.op.os_type,
5941 338e51e8 Iustin Pop
      memory=self.be_full[constants.BE_MEMORY],
5942 338e51e8 Iustin Pop
      vcpus=self.be_full[constants.BE_VCPUS],
5943 f9b10246 Guido Trotter
      nics=_NICListToTuple(self, self.nics),
5944 2c2690c9 Iustin Pop
      disk_template=self.op.disk_template,
5945 2c2690c9 Iustin Pop
      disks=[(d["size"], d["mode"]) for d in self.disks],
5946 67fc3042 Iustin Pop
      bep=self.be_full,
5947 67fc3042 Iustin Pop
      hvp=self.hv_full,
5948 3df6e710 Iustin Pop
      hypervisor_name=self.op.hypervisor,
5949 396e1b78 Michael Hanselmann
    ))
5950 a8083063 Iustin Pop
5951 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
5952 a8083063 Iustin Pop
          self.secondaries)
5953 a8083063 Iustin Pop
    return env, nl, nl
5954 a8083063 Iustin Pop
5955 a8083063 Iustin Pop
5956 a8083063 Iustin Pop
  def CheckPrereq(self):
5957 a8083063 Iustin Pop
    """Check prerequisites.
5958 a8083063 Iustin Pop

5959 a8083063 Iustin Pop
    """
5960 eedc99de Manuel Franceschini
    if (not self.cfg.GetVGName() and
5961 eedc99de Manuel Franceschini
        self.op.disk_template not in constants.DTS_NOT_LVM):
5962 eedc99de Manuel Franceschini
      raise errors.OpPrereqError("Cluster does not support lvm-based"
5963 5c983ee5 Iustin Pop
                                 " instances", errors.ECODE_STATE)
5964 eedc99de Manuel Franceschini
5965 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
5966 7baf741d Guido Trotter
      src_node = self.op.src_node
5967 7baf741d Guido Trotter
      src_path = self.op.src_path
5968 a8083063 Iustin Pop
5969 c0cbdc67 Guido Trotter
      if src_node is None:
5970 1b7bfbb7 Iustin Pop
        locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
5971 1b7bfbb7 Iustin Pop
        exp_list = self.rpc.call_export_list(locked_nodes)
5972 c0cbdc67 Guido Trotter
        found = False
5973 c0cbdc67 Guido Trotter
        for node in exp_list:
5974 4c4e4e1e Iustin Pop
          if exp_list[node].fail_msg:
5975 1b7bfbb7 Iustin Pop
            continue
5976 1b7bfbb7 Iustin Pop
          if src_path in exp_list[node].payload:
5977 c0cbdc67 Guido Trotter
            found = True
5978 c0cbdc67 Guido Trotter
            self.op.src_node = src_node = node
5979 c0cbdc67 Guido Trotter
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
5980 c0cbdc67 Guido Trotter
                                                       src_path)
5981 c0cbdc67 Guido Trotter
            break
5982 c0cbdc67 Guido Trotter
        if not found:
5983 c0cbdc67 Guido Trotter
          raise errors.OpPrereqError("No export found for relative path %s" %
5984 5c983ee5 Iustin Pop
                                      src_path, errors.ECODE_INVAL)
5985 c0cbdc67 Guido Trotter
5986 7527a8a4 Iustin Pop
      _CheckNodeOnline(self, src_node)
5987 781de953 Iustin Pop
      result = self.rpc.call_export_info(src_node, src_path)
5988 4c4e4e1e Iustin Pop
      result.Raise("No export or invalid export found in dir %s" % src_path)
5989 a8083063 Iustin Pop
5990 3eccac06 Iustin Pop
      export_info = objects.SerializableConfigParser.Loads(str(result.payload))
5991 a8083063 Iustin Pop
      if not export_info.has_section(constants.INISECT_EXP):
5992 5c983ee5 Iustin Pop
        raise errors.ProgrammerError("Corrupted export config",
5993 5c983ee5 Iustin Pop
                                     errors.ECODE_ENVIRON)
5994 a8083063 Iustin Pop
5995 a8083063 Iustin Pop
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
5996 a8083063 Iustin Pop
      if (int(ei_version) != constants.EXPORT_VERSION):
5997 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
5998 5c983ee5 Iustin Pop
                                   (ei_version, constants.EXPORT_VERSION),
5999 5c983ee5 Iustin Pop
                                   errors.ECODE_ENVIRON)
6000 a8083063 Iustin Pop
6001 09acf207 Guido Trotter
      # Check that the new instance doesn't have less disks than the export
6002 08db7c5c Iustin Pop
      instance_disks = len(self.disks)
6003 09acf207 Guido Trotter
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6004 09acf207 Guido Trotter
      if instance_disks < export_disks:
6005 09acf207 Guido Trotter
        raise errors.OpPrereqError("Not enough disks to import."
6006 09acf207 Guido Trotter
                                   " (instance: %d, export: %d)" %
6007 5c983ee5 Iustin Pop
                                   (instance_disks, export_disks),
6008 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
6009 a8083063 Iustin Pop
6010 a8083063 Iustin Pop
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
6011 09acf207 Guido Trotter
      disk_images = []
6012 09acf207 Guido Trotter
      for idx in range(export_disks):
6013 09acf207 Guido Trotter
        option = 'disk%d_dump' % idx
6014 09acf207 Guido Trotter
        if export_info.has_option(constants.INISECT_INS, option):
6015 09acf207 Guido Trotter
          # FIXME: are the old os-es, disk sizes, etc. useful?
6016 09acf207 Guido Trotter
          export_name = export_info.get(constants.INISECT_INS, option)
6017 09acf207 Guido Trotter
          image = os.path.join(src_path, export_name)
6018 09acf207 Guido Trotter
          disk_images.append(image)
6019 09acf207 Guido Trotter
        else:
6020 09acf207 Guido Trotter
          disk_images.append(False)
6021 09acf207 Guido Trotter
6022 09acf207 Guido Trotter
      self.src_images = disk_images
6023 901a65c1 Iustin Pop
6024 b4364a6b Guido Trotter
      old_name = export_info.get(constants.INISECT_INS, 'name')
6025 b4364a6b Guido Trotter
      # FIXME: int() here could throw a ValueError on broken exports
6026 b4364a6b Guido Trotter
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
6027 b4364a6b Guido Trotter
      if self.op.instance_name == old_name:
6028 b4364a6b Guido Trotter
        for idx, nic in enumerate(self.nics):
6029 b4364a6b Guido Trotter
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6030 b4364a6b Guido Trotter
            nic_mac_ini = 'nic%d_mac' % idx
6031 b4364a6b Guido Trotter
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6032 bc89efc3 Guido Trotter
6033 295728df Guido Trotter
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6034 901a65c1 Iustin Pop
6035 18c8f361 Iustin Pop
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6036 901a65c1 Iustin Pop
    if self.op.ip_check:
6037 7baf741d Guido Trotter
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6038 901a65c1 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6039 5c983ee5 Iustin Pop
                                   (self.check_ip, self.op.instance_name),
6040 5c983ee5 Iustin Pop
                                   errors.ECODE_NOTUNIQUE)
6041 901a65c1 Iustin Pop
6042 295728df Guido Trotter
    #### mac address generation
6043 295728df Guido Trotter
    # By generating here the mac address both the allocator and the hooks get
6044 295728df Guido Trotter
    # the real final mac address rather than the 'auto' or 'generate' value.
6045 295728df Guido Trotter
    # There is a race condition between the generation and the instance object
6046 295728df Guido Trotter
    # creation, which means that we know the mac is valid now, but we're not
6047 295728df Guido Trotter
    # sure it will be when we actually add the instance. If things go bad
6048 295728df Guido Trotter
    # adding the instance will abort because of a duplicate mac, and the
6049 295728df Guido Trotter
    # creation job will fail.
6050 295728df Guido Trotter
    for nic in self.nics:
6051 295728df Guido Trotter
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6052 36b66e6e Guido Trotter
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6053 295728df Guido Trotter
6054 538475ca Iustin Pop
    #### allocator run
6055 538475ca Iustin Pop
6056 538475ca Iustin Pop
    if self.op.iallocator is not None:
6057 538475ca Iustin Pop
      self._RunAllocator()
6058 0f1a06e3 Manuel Franceschini
6059 901a65c1 Iustin Pop
    #### node related checks
6060 901a65c1 Iustin Pop
6061 901a65c1 Iustin Pop
    # check primary node
6062 7baf741d Guido Trotter
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6063 7baf741d Guido Trotter
    assert self.pnode is not None, \
6064 7baf741d Guido Trotter
      "Cannot retrieve locked node %s" % self.op.pnode
6065 7527a8a4 Iustin Pop
    if pnode.offline:
6066 7527a8a4 Iustin Pop
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6067 5c983ee5 Iustin Pop
                                 pnode.name, errors.ECODE_STATE)
6068 733a2b6a Iustin Pop
    if pnode.drained:
6069 733a2b6a Iustin Pop
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6070 5c983ee5 Iustin Pop
                                 pnode.name, errors.ECODE_STATE)
6071 7527a8a4 Iustin Pop
6072 901a65c1 Iustin Pop
    self.secondaries = []
6073 901a65c1 Iustin Pop
6074 901a65c1 Iustin Pop
    # mirror node verification
6075 a1f445d3 Iustin Pop
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6076 7baf741d Guido Trotter
      if self.op.snode is None:
6077 a1f445d3 Iustin Pop
        raise errors.OpPrereqError("The networked disk templates need"
6078 5c983ee5 Iustin Pop
                                   " a mirror node", errors.ECODE_INVAL)
6079 7baf741d Guido Trotter
      if self.op.snode == pnode.name:
6080 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("The secondary node cannot be the"
6081 5c983ee5 Iustin Pop
                                   " primary node.", errors.ECODE_INVAL)
6082 7527a8a4 Iustin Pop
      _CheckNodeOnline(self, self.op.snode)
6083 733a2b6a Iustin Pop
      _CheckNodeNotDrained(self, self.op.snode)
6084 733a2b6a Iustin Pop
      self.secondaries.append(self.op.snode)
6085 a8083063 Iustin Pop
6086 6785674e Iustin Pop
    nodenames = [pnode.name] + self.secondaries
6087 6785674e Iustin Pop
6088 e2fe6369 Iustin Pop
    req_size = _ComputeDiskSize(self.op.disk_template,
6089 08db7c5c Iustin Pop
                                self.disks)
6090 ed1ebc60 Guido Trotter
6091 8d75db10 Iustin Pop
    # Check lv size requirements
6092 8d75db10 Iustin Pop
    if req_size is not None:
6093 72737a7f Iustin Pop
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
6094 72737a7f Iustin Pop
                                         self.op.hypervisor)
6095 8d75db10 Iustin Pop
      for node in nodenames:
6096 781de953 Iustin Pop
        info = nodeinfo[node]
6097 4c4e4e1e Iustin Pop
        info.Raise("Cannot get current information from node %s" % node)
6098 070e998b Iustin Pop
        info = info.payload
6099 8d75db10 Iustin Pop
        vg_free = info.get('vg_free', None)
6100 8d75db10 Iustin Pop
        if not isinstance(vg_free, int):
6101 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Can't compute free disk space on"
6102 5c983ee5 Iustin Pop
                                     " node %s" % node, errors.ECODE_ENVIRON)
6103 070e998b Iustin Pop
        if req_size > vg_free:
6104 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Not enough disk space on target node %s."
6105 8d75db10 Iustin Pop
                                     " %d MB available, %d MB required" %
6106 5c983ee5 Iustin Pop
                                     (node, vg_free, req_size),
6107 5c983ee5 Iustin Pop
                                     errors.ECODE_NORES)
6108 ed1ebc60 Guido Trotter
6109 74409b12 Iustin Pop
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6110 6785674e Iustin Pop
6111 a8083063 Iustin Pop
    # os verification
6112 781de953 Iustin Pop
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
6113 4c4e4e1e Iustin Pop
    result.Raise("OS '%s' not in supported os list for primary node %s" %
6114 045dd6d9 Iustin Pop
                 (self.op.os_type, pnode.name),
6115 045dd6d9 Iustin Pop
                 prereq=True, ecode=errors.ECODE_INVAL)
6116 f2c05717 Guido Trotter
    if not self.op.force_variant:
6117 f2c05717 Guido Trotter
      _CheckOSVariant(result.payload, self.op.os_type)
6118 a8083063 Iustin Pop
6119 b165e77e Guido Trotter
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6120 a8083063 Iustin Pop
6121 49ce1563 Iustin Pop
    # memory check on primary node
6122 49ce1563 Iustin Pop
    if self.op.start:
6123 b9bddb6b Iustin Pop
      _CheckNodeFreeMemory(self, self.pnode.name,
6124 49ce1563 Iustin Pop
                           "creating instance %s" % self.op.instance_name,
6125 338e51e8 Iustin Pop
                           self.be_full[constants.BE_MEMORY],
6126 338e51e8 Iustin Pop
                           self.op.hypervisor)
6127 49ce1563 Iustin Pop
6128 08896026 Iustin Pop
    self.dry_run_result = list(nodenames)
6129 08896026 Iustin Pop
6130 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
6131 a8083063 Iustin Pop
    """Create and add the instance to the cluster.
6132 a8083063 Iustin Pop

6133 a8083063 Iustin Pop
    """
6134 a8083063 Iustin Pop
    instance = self.op.instance_name
6135 a8083063 Iustin Pop
    pnode_name = self.pnode.name
6136 a8083063 Iustin Pop
6137 e69d05fd Iustin Pop
    ht_kind = self.op.hypervisor
6138 2a6469d5 Alexander Schreiber
    if ht_kind in constants.HTS_REQ_PORT:
6139 2a6469d5 Alexander Schreiber
      network_port = self.cfg.AllocatePort()
6140 2a6469d5 Alexander Schreiber
    else:
6141 2a6469d5 Alexander Schreiber
      network_port = None
6142 58acb49d Alexander Schreiber
6143 6785674e Iustin Pop
    ##if self.op.vnc_bind_address is None:
6144 6785674e Iustin Pop
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
6145 31a853d2 Iustin Pop
6146 2c313123 Manuel Franceschini
    # this is needed because os.path.join does not accept None arguments
6147 2c313123 Manuel Franceschini
    if self.op.file_storage_dir is None:
6148 2c313123 Manuel Franceschini
      string_file_storage_dir = ""
6149 2c313123 Manuel Franceschini
    else:
6150 2c313123 Manuel Franceschini
      string_file_storage_dir = self.op.file_storage_dir
6151 2c313123 Manuel Franceschini
6152 0f1a06e3 Manuel Franceschini
    # build the full file storage dir path
6153 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.normpath(os.path.join(
6154 d6a02168 Michael Hanselmann
                                        self.cfg.GetFileStorageDir(),
6155 2c313123 Manuel Franceschini
                                        string_file_storage_dir, instance))
6156 0f1a06e3 Manuel Franceschini
6157 0f1a06e3 Manuel Franceschini
6158 b9bddb6b Iustin Pop
    disks = _GenerateDiskTemplate(self,
6159 a8083063 Iustin Pop
                                  self.op.disk_template,
6160 a8083063 Iustin Pop
                                  instance, pnode_name,
6161 08db7c5c Iustin Pop
                                  self.secondaries,
6162 08db7c5c Iustin Pop
                                  self.disks,
6163 0f1a06e3 Manuel Franceschini
                                  file_storage_dir,
6164 e2a65344 Iustin Pop
                                  self.op.file_driver,
6165 e2a65344 Iustin Pop
                                  0)
6166 a8083063 Iustin Pop
6167 a8083063 Iustin Pop
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6168 a8083063 Iustin Pop
                            primary_node=pnode_name,
6169 08db7c5c Iustin Pop
                            nics=self.nics, disks=disks,
6170 a8083063 Iustin Pop
                            disk_template=self.op.disk_template,
6171 4978db17 Iustin Pop
                            admin_up=False,
6172 58acb49d Alexander Schreiber
                            network_port=network_port,
6173 338e51e8 Iustin Pop
                            beparams=self.op.beparams,
6174 6785674e Iustin Pop
                            hvparams=self.op.hvparams,
6175 e69d05fd Iustin Pop
                            hypervisor=self.op.hypervisor,
6176 a8083063 Iustin Pop
                            )
6177 a8083063 Iustin Pop
6178 a8083063 Iustin Pop
    feedback_fn("* creating instance disks...")
6179 796cab27 Iustin Pop
    try:
6180 796cab27 Iustin Pop
      _CreateDisks(self, iobj)
6181 796cab27 Iustin Pop
    except errors.OpExecError:
6182 796cab27 Iustin Pop
      self.LogWarning("Device creation failed, reverting...")
6183 796cab27 Iustin Pop
      try:
6184 796cab27 Iustin Pop
        _RemoveDisks(self, iobj)
6185 796cab27 Iustin Pop
      finally:
6186 796cab27 Iustin Pop
        self.cfg.ReleaseDRBDMinors(instance)
6187 796cab27 Iustin Pop
        raise
6188 a8083063 Iustin Pop
6189 a8083063 Iustin Pop
    feedback_fn("adding instance %s to cluster config" % instance)
6190 a8083063 Iustin Pop
6191 0debfb35 Guido Trotter
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6192 0debfb35 Guido Trotter
6193 7baf741d Guido Trotter
    # Declare that we don't want to remove the instance lock anymore, as we've
6194 7baf741d Guido Trotter
    # added the instance to the config
6195 7baf741d Guido Trotter
    del self.remove_locks[locking.LEVEL_INSTANCE]
6196 e36e96b4 Guido Trotter
    # Unlock all the nodes
6197 9c8971d7 Guido Trotter
    if self.op.mode == constants.INSTANCE_IMPORT:
6198 9c8971d7 Guido Trotter
      nodes_keep = [self.op.src_node]
6199 9c8971d7 Guido Trotter
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6200 9c8971d7 Guido Trotter
                       if node != self.op.src_node]
6201 9c8971d7 Guido Trotter
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6202 9c8971d7 Guido Trotter
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6203 9c8971d7 Guido Trotter
    else:
6204 9c8971d7 Guido Trotter
      self.context.glm.release(locking.LEVEL_NODE)
6205 9c8971d7 Guido Trotter
      del self.acquired_locks[locking.LEVEL_NODE]
6206 a8083063 Iustin Pop
6207 a8083063 Iustin Pop
    if self.op.wait_for_sync:
6208 b9bddb6b Iustin Pop
      disk_abort = not _WaitForSync(self, iobj)
6209 a1f445d3 Iustin Pop
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6210 a8083063 Iustin Pop
      # make sure the disks are not degraded (still sync-ing is ok)
6211 a8083063 Iustin Pop
      time.sleep(15)
6212 a8083063 Iustin Pop
      feedback_fn("* checking mirrors status")
6213 b9bddb6b Iustin Pop
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6214 a8083063 Iustin Pop
    else:
6215 a8083063 Iustin Pop
      disk_abort = False
6216 a8083063 Iustin Pop
6217 a8083063 Iustin Pop
    if disk_abort:
6218 b9bddb6b Iustin Pop
      _RemoveDisks(self, iobj)
6219 a8083063 Iustin Pop
      self.cfg.RemoveInstance(iobj.name)
6220 7baf741d Guido Trotter
      # Make sure the instance lock gets removed
6221 7baf741d Guido Trotter
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6222 3ecf6786 Iustin Pop
      raise errors.OpExecError("There are some degraded disks for"
6223 3ecf6786 Iustin Pop
                               " this instance")
6224 a8083063 Iustin Pop
6225 a8083063 Iustin Pop
    feedback_fn("creating os for instance %s on node %s" %
6226 a8083063 Iustin Pop
                (instance, pnode_name))
6227 a8083063 Iustin Pop
6228 a8083063 Iustin Pop
    if iobj.disk_template != constants.DT_DISKLESS:
6229 a8083063 Iustin Pop
      if self.op.mode == constants.INSTANCE_CREATE:
6230 a8083063 Iustin Pop
        feedback_fn("* running the instance OS create scripts...")
6231 e557bae9 Guido Trotter
        result = self.rpc.call_instance_os_add(pnode_name, iobj, False)
6232 4c4e4e1e Iustin Pop
        result.Raise("Could not add os for instance %s"
6233 4c4e4e1e Iustin Pop
                     " on node %s" % (instance, pnode_name))
6234 a8083063 Iustin Pop
6235 a8083063 Iustin Pop
      elif self.op.mode == constants.INSTANCE_IMPORT:
6236 a8083063 Iustin Pop
        feedback_fn("* running the instance OS import scripts...")
6237 a8083063 Iustin Pop
        src_node = self.op.src_node
6238 09acf207 Guido Trotter
        src_images = self.src_images
6239 62c9ec92 Iustin Pop
        cluster_name = self.cfg.GetClusterName()
6240 6c0af70e Guido Trotter
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
6241 09acf207 Guido Trotter
                                                         src_node, src_images,
6242 6c0af70e Guido Trotter
                                                         cluster_name)
6243 4c4e4e1e Iustin Pop
        msg = import_result.fail_msg
6244 944bf548 Iustin Pop
        if msg:
6245 944bf548 Iustin Pop
          self.LogWarning("Error while importing the disk images for instance"
6246 944bf548 Iustin Pop
                          " %s on node %s: %s" % (instance, pnode_name, msg))
6247 a8083063 Iustin Pop
      else:
6248 a8083063 Iustin Pop
        # also checked in the prereq part
6249 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6250 3ecf6786 Iustin Pop
                                     % self.op.mode)
6251 a8083063 Iustin Pop
6252 a8083063 Iustin Pop
    if self.op.start:
6253 4978db17 Iustin Pop
      iobj.admin_up = True
6254 a4eae71f Michael Hanselmann
      self.cfg.Update(iobj, feedback_fn)
6255 9a4f63d1 Iustin Pop
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6256 a8083063 Iustin Pop
      feedback_fn("* starting instance...")
6257 0eca8e0c Iustin Pop
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6258 4c4e4e1e Iustin Pop
      result.Raise("Could not start instance")
6259 a8083063 Iustin Pop
6260 08896026 Iustin Pop
    return list(iobj.all_nodes)
6261 08896026 Iustin Pop
6262 a8083063 Iustin Pop
6263 a8083063 Iustin Pop
class LUConnectConsole(NoHooksLU):
6264 a8083063 Iustin Pop
  """Connect to an instance's console.
6265 a8083063 Iustin Pop

6266 a8083063 Iustin Pop
  This is somewhat special in that it returns the command line that
6267 a8083063 Iustin Pop
  you need to run on the master node in order to connect to the
6268 a8083063 Iustin Pop
  console.
6269 a8083063 Iustin Pop

6270 a8083063 Iustin Pop
  """
6271 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
6272 8659b73e Guido Trotter
  REQ_BGL = False
6273 8659b73e Guido Trotter
6274 8659b73e Guido Trotter
  def ExpandNames(self):
6275 8659b73e Guido Trotter
    self._ExpandAndLockInstance()
6276 a8083063 Iustin Pop
6277 a8083063 Iustin Pop
  def CheckPrereq(self):
6278 a8083063 Iustin Pop
    """Check prerequisites.
6279 a8083063 Iustin Pop

6280 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
6281 a8083063 Iustin Pop

6282 a8083063 Iustin Pop
    """
6283 8659b73e Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6284 8659b73e Guido Trotter
    assert self.instance is not None, \
6285 8659b73e Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
6286 513e896d Guido Trotter
    _CheckNodeOnline(self, self.instance.primary_node)
6287 a8083063 Iustin Pop
6288 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
6289 a8083063 Iustin Pop
    """Connect to the console of an instance
6290 a8083063 Iustin Pop

6291 a8083063 Iustin Pop
    """
6292 a8083063 Iustin Pop
    instance = self.instance
6293 a8083063 Iustin Pop
    node = instance.primary_node
6294 a8083063 Iustin Pop
6295 72737a7f Iustin Pop
    node_insts = self.rpc.call_instance_list([node],
6296 72737a7f Iustin Pop
                                             [instance.hypervisor])[node]
6297 4c4e4e1e Iustin Pop
    node_insts.Raise("Can't get node information from %s" % node)
6298 a8083063 Iustin Pop
6299 aca13712 Iustin Pop
    if instance.name not in node_insts.payload:
6300 3ecf6786 Iustin Pop
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6301 a8083063 Iustin Pop
6302 9a4f63d1 Iustin Pop
    logging.debug("Connecting to console of %s on %s", instance.name, node)
6303 a8083063 Iustin Pop
6304 e69d05fd Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6305 5431b2e4 Guido Trotter
    cluster = self.cfg.GetClusterInfo()
6306 5431b2e4 Guido Trotter
    # beparams and hvparams are passed separately, to avoid editing the
6307 5431b2e4 Guido Trotter
    # instance and then saving the defaults in the instance itself.
6308 5431b2e4 Guido Trotter
    hvparams = cluster.FillHV(instance)
6309 5431b2e4 Guido Trotter
    beparams = cluster.FillBE(instance)
6310 5431b2e4 Guido Trotter
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6311 b047857b Michael Hanselmann
6312 82122173 Iustin Pop
    # build ssh cmdline
6313 0a80a26f Michael Hanselmann
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6314 a8083063 Iustin Pop
6315 a8083063 Iustin Pop
6316 a8083063 Iustin Pop
class LUReplaceDisks(LogicalUnit):
6317 a8083063 Iustin Pop
  """Replace the disks of an instance.
6318 a8083063 Iustin Pop

6319 a8083063 Iustin Pop
  """
6320 a8083063 Iustin Pop
  HPATH = "mirrors-replace"
6321 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
6322 a9e0c397 Iustin Pop
  _OP_REQP = ["instance_name", "mode", "disks"]
6323 efd990e4 Guido Trotter
  REQ_BGL = False
6324 efd990e4 Guido Trotter
6325 7e9366f7 Iustin Pop
  def CheckArguments(self):
6326 efd990e4 Guido Trotter
    if not hasattr(self.op, "remote_node"):
6327 efd990e4 Guido Trotter
      self.op.remote_node = None
6328 7e9366f7 Iustin Pop
    if not hasattr(self.op, "iallocator"):
6329 7e9366f7 Iustin Pop
      self.op.iallocator = None
6330 7e9366f7 Iustin Pop
6331 c68174b6 Michael Hanselmann
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6332 c68174b6 Michael Hanselmann
                                  self.op.iallocator)
6333 7e9366f7 Iustin Pop
6334 7e9366f7 Iustin Pop
  def ExpandNames(self):
6335 7e9366f7 Iustin Pop
    self._ExpandAndLockInstance()
6336 7e9366f7 Iustin Pop
6337 7e9366f7 Iustin Pop
    if self.op.iallocator is not None:
6338 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6339 2bb5c911 Michael Hanselmann
6340 efd990e4 Guido Trotter
    elif self.op.remote_node is not None:
6341 efd990e4 Guido Trotter
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6342 efd990e4 Guido Trotter
      if remote_node is None:
6343 efd990e4 Guido Trotter
        raise errors.OpPrereqError("Node '%s' not known" %
6344 5c983ee5 Iustin Pop
                                   self.op.remote_node, errors.ECODE_NOENT)
6345 2bb5c911 Michael Hanselmann
6346 efd990e4 Guido Trotter
      self.op.remote_node = remote_node
6347 2bb5c911 Michael Hanselmann
6348 3b559640 Iustin Pop
      # Warning: do not remove the locking of the new secondary here
6349 3b559640 Iustin Pop
      # unless DRBD8.AddChildren is changed to work in parallel;
6350 3b559640 Iustin Pop
      # currently it doesn't since parallel invocations of
6351 3b559640 Iustin Pop
      # FindUnusedMinor will conflict
6352 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6353 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6354 2bb5c911 Michael Hanselmann
6355 efd990e4 Guido Trotter
    else:
6356 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = []
6357 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6358 efd990e4 Guido Trotter
6359 c68174b6 Michael Hanselmann
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6360 c68174b6 Michael Hanselmann
                                   self.op.iallocator, self.op.remote_node,
6361 c68174b6 Michael Hanselmann
                                   self.op.disks)
6362 c68174b6 Michael Hanselmann
6363 3a012b41 Michael Hanselmann
    self.tasklets = [self.replacer]
6364 2bb5c911 Michael Hanselmann
6365 efd990e4 Guido Trotter
  def DeclareLocks(self, level):
6366 efd990e4 Guido Trotter
    # If we're not already locking all nodes in the set we have to declare the
6367 efd990e4 Guido Trotter
    # instance's primary/secondary nodes.
6368 efd990e4 Guido Trotter
    if (level == locking.LEVEL_NODE and
6369 efd990e4 Guido Trotter
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6370 efd990e4 Guido Trotter
      self._LockInstancesNodes()
6371 a8083063 Iustin Pop
6372 a8083063 Iustin Pop
  def BuildHooksEnv(self):
6373 a8083063 Iustin Pop
    """Build hooks env.
6374 a8083063 Iustin Pop

6375 a8083063 Iustin Pop
    This runs on the master, the primary and all the secondaries.
6376 a8083063 Iustin Pop

6377 a8083063 Iustin Pop
    """
6378 2bb5c911 Michael Hanselmann
    instance = self.replacer.instance
6379 a8083063 Iustin Pop
    env = {
6380 a9e0c397 Iustin Pop
      "MODE": self.op.mode,
6381 a8083063 Iustin Pop
      "NEW_SECONDARY": self.op.remote_node,
6382 2bb5c911 Michael Hanselmann
      "OLD_SECONDARY": instance.secondary_nodes[0],
6383 a8083063 Iustin Pop
      }
6384 2bb5c911 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6385 0834c866 Iustin Pop
    nl = [
6386 d6a02168 Michael Hanselmann
      self.cfg.GetMasterNode(),
6387 2bb5c911 Michael Hanselmann
      instance.primary_node,
6388 0834c866 Iustin Pop
      ]
6389 0834c866 Iustin Pop
    if self.op.remote_node is not None:
6390 0834c866 Iustin Pop
      nl.append(self.op.remote_node)
6391 a8083063 Iustin Pop
    return env, nl, nl
6392 a8083063 Iustin Pop
6393 2bb5c911 Michael Hanselmann
6394 7ffc5a86 Michael Hanselmann
class LUEvacuateNode(LogicalUnit):
6395 7ffc5a86 Michael Hanselmann
  """Relocate the secondary instances from a node.
6396 7ffc5a86 Michael Hanselmann

6397 7ffc5a86 Michael Hanselmann
  """
6398 7ffc5a86 Michael Hanselmann
  HPATH = "node-evacuate"
6399 7ffc5a86 Michael Hanselmann
  HTYPE = constants.HTYPE_NODE
6400 7ffc5a86 Michael Hanselmann
  _OP_REQP = ["node_name"]
6401 7ffc5a86 Michael Hanselmann
  REQ_BGL = False
6402 7ffc5a86 Michael Hanselmann
6403 7ffc5a86 Michael Hanselmann
  def CheckArguments(self):
6404 7ffc5a86 Michael Hanselmann
    if not hasattr(self.op, "remote_node"):
6405 7ffc5a86 Michael Hanselmann
      self.op.remote_node = None
6406 7ffc5a86 Michael Hanselmann
    if not hasattr(self.op, "iallocator"):
6407 7ffc5a86 Michael Hanselmann
      self.op.iallocator = None
6408 7ffc5a86 Michael Hanselmann
6409 7ffc5a86 Michael Hanselmann
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6410 7ffc5a86 Michael Hanselmann
                                  self.op.remote_node,
6411 7ffc5a86 Michael Hanselmann
                                  self.op.iallocator)
6412 7ffc5a86 Michael Hanselmann
6413 7ffc5a86 Michael Hanselmann
  def ExpandNames(self):
6414 7ffc5a86 Michael Hanselmann
    self.op.node_name = self.cfg.ExpandNodeName(self.op.node_name)
6415 7ffc5a86 Michael Hanselmann
    if self.op.node_name is None:
6416 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Node '%s' not known" % self.op.node_name,
6417 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
6418 7ffc5a86 Michael Hanselmann
6419 7ffc5a86 Michael Hanselmann
    self.needed_locks = {}
6420 7ffc5a86 Michael Hanselmann
6421 7ffc5a86 Michael Hanselmann
    # Declare node locks
6422 7ffc5a86 Michael Hanselmann
    if self.op.iallocator is not None:
6423 7ffc5a86 Michael Hanselmann
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6424 7ffc5a86 Michael Hanselmann
6425 7ffc5a86 Michael Hanselmann
    elif self.op.remote_node is not None:
6426 7ffc5a86 Michael Hanselmann
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
6427 7ffc5a86 Michael Hanselmann
      if remote_node is None:
6428 7ffc5a86 Michael Hanselmann
        raise errors.OpPrereqError("Node '%s' not known" %
6429 5c983ee5 Iustin Pop
                                   self.op.remote_node, errors.ECODE_NOENT)
6430 7ffc5a86 Michael Hanselmann
6431 7ffc5a86 Michael Hanselmann
      self.op.remote_node = remote_node
6432 7ffc5a86 Michael Hanselmann
6433 7ffc5a86 Michael Hanselmann
      # Warning: do not remove the locking of the new secondary here
6434 7ffc5a86 Michael Hanselmann
      # unless DRBD8.AddChildren is changed to work in parallel;
6435 7ffc5a86 Michael Hanselmann
      # currently it doesn't since parallel invocations of
6436 7ffc5a86 Michael Hanselmann
      # FindUnusedMinor will conflict
6437 7ffc5a86 Michael Hanselmann
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6438 7ffc5a86 Michael Hanselmann
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6439 7ffc5a86 Michael Hanselmann
6440 7ffc5a86 Michael Hanselmann
    else:
6441 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
6442 7ffc5a86 Michael Hanselmann
6443 7ffc5a86 Michael Hanselmann
    # Create tasklets for replacing disks for all secondary instances on this
6444 7ffc5a86 Michael Hanselmann
    # node
6445 7ffc5a86 Michael Hanselmann
    names = []
6446 3a012b41 Michael Hanselmann
    tasklets = []
6447 7ffc5a86 Michael Hanselmann
6448 7ffc5a86 Michael Hanselmann
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
6449 7ffc5a86 Michael Hanselmann
      logging.debug("Replacing disks for instance %s", inst.name)
6450 7ffc5a86 Michael Hanselmann
      names.append(inst.name)
6451 7ffc5a86 Michael Hanselmann
6452 7ffc5a86 Michael Hanselmann
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
6453 7ffc5a86 Michael Hanselmann
                                self.op.iallocator, self.op.remote_node, [])
6454 3a012b41 Michael Hanselmann
      tasklets.append(replacer)
6455 7ffc5a86 Michael Hanselmann
6456 3a012b41 Michael Hanselmann
    self.tasklets = tasklets
6457 7ffc5a86 Michael Hanselmann
    self.instance_names = names
6458 7ffc5a86 Michael Hanselmann
6459 7ffc5a86 Michael Hanselmann
    # Declare instance locks
6460 7ffc5a86 Michael Hanselmann
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
6461 7ffc5a86 Michael Hanselmann
6462 7ffc5a86 Michael Hanselmann
  def DeclareLocks(self, level):
6463 7ffc5a86 Michael Hanselmann
    # If we're not already locking all nodes in the set we have to declare the
6464 7ffc5a86 Michael Hanselmann
    # instance's primary/secondary nodes.
6465 7ffc5a86 Michael Hanselmann
    if (level == locking.LEVEL_NODE and
6466 7ffc5a86 Michael Hanselmann
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6467 7ffc5a86 Michael Hanselmann
      self._LockInstancesNodes()
6468 7ffc5a86 Michael Hanselmann
6469 7ffc5a86 Michael Hanselmann
  def BuildHooksEnv(self):
6470 7ffc5a86 Michael Hanselmann
    """Build hooks env.
6471 7ffc5a86 Michael Hanselmann

6472 7ffc5a86 Michael Hanselmann
    This runs on the master, the primary and all the secondaries.
6473 7ffc5a86 Michael Hanselmann

6474 7ffc5a86 Michael Hanselmann
    """
6475 7ffc5a86 Michael Hanselmann
    env = {
6476 7ffc5a86 Michael Hanselmann
      "NODE_NAME": self.op.node_name,
6477 7ffc5a86 Michael Hanselmann
      }
6478 7ffc5a86 Michael Hanselmann
6479 7ffc5a86 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()]
6480 7ffc5a86 Michael Hanselmann
6481 7ffc5a86 Michael Hanselmann
    if self.op.remote_node is not None:
6482 7ffc5a86 Michael Hanselmann
      env["NEW_SECONDARY"] = self.op.remote_node
6483 7ffc5a86 Michael Hanselmann
      nl.append(self.op.remote_node)
6484 7ffc5a86 Michael Hanselmann
6485 7ffc5a86 Michael Hanselmann
    return (env, nl, nl)
6486 7ffc5a86 Michael Hanselmann
6487 7ffc5a86 Michael Hanselmann
6488 c68174b6 Michael Hanselmann
class TLReplaceDisks(Tasklet):
6489 2bb5c911 Michael Hanselmann
  """Replaces disks for an instance.
6490 2bb5c911 Michael Hanselmann

6491 2bb5c911 Michael Hanselmann
  Note: Locking is not within the scope of this class.
6492 2bb5c911 Michael Hanselmann

6493 2bb5c911 Michael Hanselmann
  """
6494 2bb5c911 Michael Hanselmann
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
6495 2bb5c911 Michael Hanselmann
               disks):
6496 2bb5c911 Michael Hanselmann
    """Initializes this class.
6497 2bb5c911 Michael Hanselmann

6498 2bb5c911 Michael Hanselmann
    """
6499 464243a7 Michael Hanselmann
    Tasklet.__init__(self, lu)
6500 464243a7 Michael Hanselmann
6501 2bb5c911 Michael Hanselmann
    # Parameters
6502 2bb5c911 Michael Hanselmann
    self.instance_name = instance_name
6503 2bb5c911 Michael Hanselmann
    self.mode = mode
6504 2bb5c911 Michael Hanselmann
    self.iallocator_name = iallocator_name
6505 2bb5c911 Michael Hanselmann
    self.remote_node = remote_node
6506 2bb5c911 Michael Hanselmann
    self.disks = disks
6507 2bb5c911 Michael Hanselmann
6508 2bb5c911 Michael Hanselmann
    # Runtime data
6509 2bb5c911 Michael Hanselmann
    self.instance = None
6510 2bb5c911 Michael Hanselmann
    self.new_node = None
6511 2bb5c911 Michael Hanselmann
    self.target_node = None
6512 2bb5c911 Michael Hanselmann
    self.other_node = None
6513 2bb5c911 Michael Hanselmann
    self.remote_node_info = None
6514 2bb5c911 Michael Hanselmann
    self.node_secondary_ip = None
6515 2bb5c911 Michael Hanselmann
6516 2bb5c911 Michael Hanselmann
  @staticmethod
6517 2bb5c911 Michael Hanselmann
  def CheckArguments(mode, remote_node, iallocator):
6518 c68174b6 Michael Hanselmann
    """Helper function for users of this class.
6519 c68174b6 Michael Hanselmann

6520 c68174b6 Michael Hanselmann
    """
6521 2bb5c911 Michael Hanselmann
    # check for valid parameter combination
6522 2bb5c911 Michael Hanselmann
    if mode == constants.REPLACE_DISK_CHG:
6523 02a00186 Michael Hanselmann
      if remote_node is None and iallocator is None:
6524 2bb5c911 Michael Hanselmann
        raise errors.OpPrereqError("When changing the secondary either an"
6525 2bb5c911 Michael Hanselmann
                                   " iallocator script must be used or the"
6526 5c983ee5 Iustin Pop
                                   " new node given", errors.ECODE_INVAL)
6527 02a00186 Michael Hanselmann
6528 02a00186 Michael Hanselmann
      if remote_node is not None and iallocator is not None:
6529 2bb5c911 Michael Hanselmann
        raise errors.OpPrereqError("Give either the iallocator or the new"
6530 5c983ee5 Iustin Pop
                                   " secondary, not both", errors.ECODE_INVAL)
6531 02a00186 Michael Hanselmann
6532 02a00186 Michael Hanselmann
    elif remote_node is not None or iallocator is not None:
6533 02a00186 Michael Hanselmann
      # Not replacing the secondary
6534 02a00186 Michael Hanselmann
      raise errors.OpPrereqError("The iallocator and new node options can"
6535 02a00186 Michael Hanselmann
                                 " only be used when changing the"
6536 5c983ee5 Iustin Pop
                                 " secondary node", errors.ECODE_INVAL)
6537 2bb5c911 Michael Hanselmann
6538 2bb5c911 Michael Hanselmann
  @staticmethod
6539 2bb5c911 Michael Hanselmann
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
6540 2bb5c911 Michael Hanselmann
    """Compute a new secondary node using an IAllocator.
6541 2bb5c911 Michael Hanselmann

6542 2bb5c911 Michael Hanselmann
    """
6543 2bb5c911 Michael Hanselmann
    ial = IAllocator(lu.cfg, lu.rpc,
6544 2bb5c911 Michael Hanselmann
                     mode=constants.IALLOCATOR_MODE_RELOC,
6545 2bb5c911 Michael Hanselmann
                     name=instance_name,
6546 2bb5c911 Michael Hanselmann
                     relocate_from=relocate_from)
6547 2bb5c911 Michael Hanselmann
6548 2bb5c911 Michael Hanselmann
    ial.Run(iallocator_name)
6549 2bb5c911 Michael Hanselmann
6550 2bb5c911 Michael Hanselmann
    if not ial.success:
6551 2bb5c911 Michael Hanselmann
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
6552 5c983ee5 Iustin Pop
                                 " %s" % (iallocator_name, ial.info),
6553 5c983ee5 Iustin Pop
                                 errors.ECODE_NORES)
6554 2bb5c911 Michael Hanselmann
6555 2bb5c911 Michael Hanselmann
    if len(ial.nodes) != ial.required_nodes:
6556 2bb5c911 Michael Hanselmann
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6557 2bb5c911 Michael Hanselmann
                                 " of nodes (%s), required %s" %
6558 d984846d Iustin Pop
                                 (iallocator_name,
6559 d984846d Iustin Pop
                                  len(ial.nodes), ial.required_nodes),
6560 5c983ee5 Iustin Pop
                                 errors.ECODE_FAULT)
6561 2bb5c911 Michael Hanselmann
6562 2bb5c911 Michael Hanselmann
    remote_node_name = ial.nodes[0]
6563 2bb5c911 Michael Hanselmann
6564 2bb5c911 Michael Hanselmann
    lu.LogInfo("Selected new secondary for instance '%s': %s",
6565 2bb5c911 Michael Hanselmann
               instance_name, remote_node_name)
6566 2bb5c911 Michael Hanselmann
6567 2bb5c911 Michael Hanselmann
    return remote_node_name
6568 2bb5c911 Michael Hanselmann
6569 942be002 Michael Hanselmann
  def _FindFaultyDisks(self, node_name):
6570 2d9005d8 Michael Hanselmann
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
6571 2d9005d8 Michael Hanselmann
                                    node_name, True)
6572 942be002 Michael Hanselmann
6573 2bb5c911 Michael Hanselmann
  def CheckPrereq(self):
6574 2bb5c911 Michael Hanselmann
    """Check prerequisites.
6575 2bb5c911 Michael Hanselmann

6576 2bb5c911 Michael Hanselmann
    This checks that the instance is in the cluster.
6577 2bb5c911 Michael Hanselmann

6578 2bb5c911 Michael Hanselmann
    """
6579 e9022531 Iustin Pop
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
6580 e9022531 Iustin Pop
    assert instance is not None, \
6581 20eca47d Iustin Pop
      "Cannot retrieve locked instance %s" % self.instance_name
6582 2bb5c911 Michael Hanselmann
6583 e9022531 Iustin Pop
    if instance.disk_template != constants.DT_DRBD8:
6584 7e9366f7 Iustin Pop
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
6585 5c983ee5 Iustin Pop
                                 " instances", errors.ECODE_INVAL)
6586 a8083063 Iustin Pop
6587 e9022531 Iustin Pop
    if len(instance.secondary_nodes) != 1:
6588 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The instance has a strange layout,"
6589 3ecf6786 Iustin Pop
                                 " expected one secondary but found %d" %
6590 5c983ee5 Iustin Pop
                                 len(instance.secondary_nodes),
6591 5c983ee5 Iustin Pop
                                 errors.ECODE_FAULT)
6592 a8083063 Iustin Pop
6593 e9022531 Iustin Pop
    secondary_node = instance.secondary_nodes[0]
6594 a9e0c397 Iustin Pop
6595 2bb5c911 Michael Hanselmann
    if self.iallocator_name is None:
6596 2bb5c911 Michael Hanselmann
      remote_node = self.remote_node
6597 2bb5c911 Michael Hanselmann
    else:
6598 2bb5c911 Michael Hanselmann
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
6599 e9022531 Iustin Pop
                                       instance.name, instance.secondary_nodes)
6600 b6e82a65 Iustin Pop
6601 a9e0c397 Iustin Pop
    if remote_node is not None:
6602 a9e0c397 Iustin Pop
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
6603 efd990e4 Guido Trotter
      assert self.remote_node_info is not None, \
6604 efd990e4 Guido Trotter
        "Cannot retrieve locked node %s" % remote_node
6605 a9e0c397 Iustin Pop
    else:
6606 a9e0c397 Iustin Pop
      self.remote_node_info = None
6607 2bb5c911 Michael Hanselmann
6608 2bb5c911 Michael Hanselmann
    if remote_node == self.instance.primary_node:
6609 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The specified node is the primary node of"
6610 5c983ee5 Iustin Pop
                                 " the instance.", errors.ECODE_INVAL)
6611 2bb5c911 Michael Hanselmann
6612 2bb5c911 Michael Hanselmann
    if remote_node == secondary_node:
6613 7e9366f7 Iustin Pop
      raise errors.OpPrereqError("The specified node is already the"
6614 5c983ee5 Iustin Pop
                                 " secondary node of the instance.",
6615 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
6616 7e9366f7 Iustin Pop
6617 2945fd2d Michael Hanselmann
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
6618 2945fd2d Michael Hanselmann
                                    constants.REPLACE_DISK_CHG):
6619 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
6620 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
6621 942be002 Michael Hanselmann
6622 2945fd2d Michael Hanselmann
    if self.mode == constants.REPLACE_DISK_AUTO:
6623 e9022531 Iustin Pop
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
6624 942be002 Michael Hanselmann
      faulty_secondary = self._FindFaultyDisks(secondary_node)
6625 942be002 Michael Hanselmann
6626 942be002 Michael Hanselmann
      if faulty_primary and faulty_secondary:
6627 942be002 Michael Hanselmann
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
6628 942be002 Michael Hanselmann
                                   " one node and can not be repaired"
6629 5c983ee5 Iustin Pop
                                   " automatically" % self.instance_name,
6630 5c983ee5 Iustin Pop
                                   errors.ECODE_STATE)
6631 942be002 Michael Hanselmann
6632 942be002 Michael Hanselmann
      if faulty_primary:
6633 942be002 Michael Hanselmann
        self.disks = faulty_primary
6634 e9022531 Iustin Pop
        self.target_node = instance.primary_node
6635 942be002 Michael Hanselmann
        self.other_node = secondary_node
6636 942be002 Michael Hanselmann
        check_nodes = [self.target_node, self.other_node]
6637 942be002 Michael Hanselmann
      elif faulty_secondary:
6638 942be002 Michael Hanselmann
        self.disks = faulty_secondary
6639 942be002 Michael Hanselmann
        self.target_node = secondary_node
6640 e9022531 Iustin Pop
        self.other_node = instance.primary_node
6641 942be002 Michael Hanselmann
        check_nodes = [self.target_node, self.other_node]
6642 942be002 Michael Hanselmann
      else:
6643 942be002 Michael Hanselmann
        self.disks = []
6644 942be002 Michael Hanselmann
        check_nodes = []
6645 942be002 Michael Hanselmann
6646 942be002 Michael Hanselmann
    else:
6647 942be002 Michael Hanselmann
      # Non-automatic modes
6648 942be002 Michael Hanselmann
      if self.mode == constants.REPLACE_DISK_PRI:
6649 e9022531 Iustin Pop
        self.target_node = instance.primary_node
6650 942be002 Michael Hanselmann
        self.other_node = secondary_node
6651 942be002 Michael Hanselmann
        check_nodes = [self.target_node, self.other_node]
6652 7e9366f7 Iustin Pop
6653 942be002 Michael Hanselmann
      elif self.mode == constants.REPLACE_DISK_SEC:
6654 942be002 Michael Hanselmann
        self.target_node = secondary_node
6655 e9022531 Iustin Pop
        self.other_node = instance.primary_node
6656 942be002 Michael Hanselmann
        check_nodes = [self.target_node, self.other_node]
6657 a9e0c397 Iustin Pop
6658 942be002 Michael Hanselmann
      elif self.mode == constants.REPLACE_DISK_CHG:
6659 942be002 Michael Hanselmann
        self.new_node = remote_node
6660 e9022531 Iustin Pop
        self.other_node = instance.primary_node
6661 942be002 Michael Hanselmann
        self.target_node = secondary_node
6662 942be002 Michael Hanselmann
        check_nodes = [self.new_node, self.other_node]
6663 54155f52 Iustin Pop
6664 942be002 Michael Hanselmann
        _CheckNodeNotDrained(self.lu, remote_node)
6665 a8083063 Iustin Pop
6666 942be002 Michael Hanselmann
      else:
6667 942be002 Michael Hanselmann
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
6668 942be002 Michael Hanselmann
                                     self.mode)
6669 942be002 Michael Hanselmann
6670 942be002 Michael Hanselmann
      # If not specified all disks should be replaced
6671 942be002 Michael Hanselmann
      if not self.disks:
6672 942be002 Michael Hanselmann
        self.disks = range(len(self.instance.disks))
6673 a9e0c397 Iustin Pop
6674 2bb5c911 Michael Hanselmann
    for node in check_nodes:
6675 2bb5c911 Michael Hanselmann
      _CheckNodeOnline(self.lu, node)
6676 e4376078 Iustin Pop
6677 2bb5c911 Michael Hanselmann
    # Check whether disks are valid
6678 2bb5c911 Michael Hanselmann
    for disk_idx in self.disks:
6679 e9022531 Iustin Pop
      instance.FindDisk(disk_idx)
6680 e4376078 Iustin Pop
6681 2bb5c911 Michael Hanselmann
    # Get secondary node IP addresses
6682 2bb5c911 Michael Hanselmann
    node_2nd_ip = {}
6683 e4376078 Iustin Pop
6684 2bb5c911 Michael Hanselmann
    for node_name in [self.target_node, self.other_node, self.new_node]:
6685 2bb5c911 Michael Hanselmann
      if node_name is not None:
6686 2bb5c911 Michael Hanselmann
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
6687 e4376078 Iustin Pop
6688 2bb5c911 Michael Hanselmann
    self.node_secondary_ip = node_2nd_ip
6689 a9e0c397 Iustin Pop
6690 c68174b6 Michael Hanselmann
  def Exec(self, feedback_fn):
6691 2bb5c911 Michael Hanselmann
    """Execute disk replacement.
6692 2bb5c911 Michael Hanselmann

6693 2bb5c911 Michael Hanselmann
    This dispatches the disk replacement to the appropriate handler.
6694 cff90b79 Iustin Pop

6695 a9e0c397 Iustin Pop
    """
6696 942be002 Michael Hanselmann
    if not self.disks:
6697 942be002 Michael Hanselmann
      feedback_fn("No disks need replacement")
6698 942be002 Michael Hanselmann
      return
6699 942be002 Michael Hanselmann
6700 942be002 Michael Hanselmann
    feedback_fn("Replacing disk(s) %s for %s" %
6701 1f864b60 Iustin Pop
                (utils.CommaJoin(self.disks), self.instance.name))
6702 7ffc5a86 Michael Hanselmann
6703 2bb5c911 Michael Hanselmann
    activate_disks = (not self.instance.admin_up)
6704 2bb5c911 Michael Hanselmann
6705 2bb5c911 Michael Hanselmann
    # Activate the instance disks if we're replacing them on a down instance
6706 2bb5c911 Michael Hanselmann
    if activate_disks:
6707 2bb5c911 Michael Hanselmann
      _StartInstanceDisks(self.lu, self.instance, True)
6708 2bb5c911 Michael Hanselmann
6709 2bb5c911 Michael Hanselmann
    try:
6710 942be002 Michael Hanselmann
      # Should we replace the secondary node?
6711 942be002 Michael Hanselmann
      if self.new_node is not None:
6712 a4eae71f Michael Hanselmann
        fn = self._ExecDrbd8Secondary
6713 2bb5c911 Michael Hanselmann
      else:
6714 a4eae71f Michael Hanselmann
        fn = self._ExecDrbd8DiskOnly
6715 a4eae71f Michael Hanselmann
6716 a4eae71f Michael Hanselmann
      return fn(feedback_fn)
6717 2bb5c911 Michael Hanselmann
6718 2bb5c911 Michael Hanselmann
    finally:
6719 5c983ee5 Iustin Pop
      # Deactivate the instance disks if we're replacing them on a
6720 5c983ee5 Iustin Pop
      # down instance
6721 2bb5c911 Michael Hanselmann
      if activate_disks:
6722 2bb5c911 Michael Hanselmann
        _SafeShutdownInstanceDisks(self.lu, self.instance)
6723 2bb5c911 Michael Hanselmann
6724 2bb5c911 Michael Hanselmann
  def _CheckVolumeGroup(self, nodes):
6725 2bb5c911 Michael Hanselmann
    self.lu.LogInfo("Checking volume groups")
6726 2bb5c911 Michael Hanselmann
6727 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
6728 cff90b79 Iustin Pop
6729 2bb5c911 Michael Hanselmann
    # Make sure volume group exists on all involved nodes
6730 2bb5c911 Michael Hanselmann
    results = self.rpc.call_vg_list(nodes)
6731 cff90b79 Iustin Pop
    if not results:
6732 cff90b79 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
6733 2bb5c911 Michael Hanselmann
6734 2bb5c911 Michael Hanselmann
    for node in nodes:
6735 781de953 Iustin Pop
      res = results[node]
6736 4c4e4e1e Iustin Pop
      res.Raise("Error checking node %s" % node)
6737 2bb5c911 Michael Hanselmann
      if vgname not in res.payload:
6738 2bb5c911 Michael Hanselmann
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
6739 2bb5c911 Michael Hanselmann
                                 (vgname, node))
6740 2bb5c911 Michael Hanselmann
6741 2bb5c911 Michael Hanselmann
  def _CheckDisksExistence(self, nodes):
6742 2bb5c911 Michael Hanselmann
    # Check disk existence
6743 2bb5c911 Michael Hanselmann
    for idx, dev in enumerate(self.instance.disks):
6744 2bb5c911 Michael Hanselmann
      if idx not in self.disks:
6745 cff90b79 Iustin Pop
        continue
6746 2bb5c911 Michael Hanselmann
6747 2bb5c911 Michael Hanselmann
      for node in nodes:
6748 2bb5c911 Michael Hanselmann
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
6749 2bb5c911 Michael Hanselmann
        self.cfg.SetDiskID(dev, node)
6750 2bb5c911 Michael Hanselmann
6751 23829f6f Iustin Pop
        result = self.rpc.call_blockdev_find(node, dev)
6752 2bb5c911 Michael Hanselmann
6753 4c4e4e1e Iustin Pop
        msg = result.fail_msg
6754 2bb5c911 Michael Hanselmann
        if msg or not result.payload:
6755 2bb5c911 Michael Hanselmann
          if not msg:
6756 2bb5c911 Michael Hanselmann
            msg = "disk not found"
6757 23829f6f Iustin Pop
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
6758 23829f6f Iustin Pop
                                   (idx, node, msg))
6759 cff90b79 Iustin Pop
6760 2bb5c911 Michael Hanselmann
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
6761 2bb5c911 Michael Hanselmann
    for idx, dev in enumerate(self.instance.disks):
6762 2bb5c911 Michael Hanselmann
      if idx not in self.disks:
6763 cff90b79 Iustin Pop
        continue
6764 cff90b79 Iustin Pop
6765 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
6766 2bb5c911 Michael Hanselmann
                      (idx, node_name))
6767 2bb5c911 Michael Hanselmann
6768 2bb5c911 Michael Hanselmann
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
6769 2bb5c911 Michael Hanselmann
                                   ldisk=ldisk):
6770 2bb5c911 Michael Hanselmann
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
6771 2bb5c911 Michael Hanselmann
                                 " replace disks for instance %s" %
6772 2bb5c911 Michael Hanselmann
                                 (node_name, self.instance.name))
6773 2bb5c911 Michael Hanselmann
6774 2bb5c911 Michael Hanselmann
  def _CreateNewStorage(self, node_name):
6775 2bb5c911 Michael Hanselmann
    vgname = self.cfg.GetVGName()
6776 2bb5c911 Michael Hanselmann
    iv_names = {}
6777 2bb5c911 Michael Hanselmann
6778 2bb5c911 Michael Hanselmann
    for idx, dev in enumerate(self.instance.disks):
6779 2bb5c911 Michael Hanselmann
      if idx not in self.disks:
6780 a9e0c397 Iustin Pop
        continue
6781 2bb5c911 Michael Hanselmann
6782 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
6783 2bb5c911 Michael Hanselmann
6784 2bb5c911 Michael Hanselmann
      self.cfg.SetDiskID(dev, node_name)
6785 2bb5c911 Michael Hanselmann
6786 2bb5c911 Michael Hanselmann
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
6787 2bb5c911 Michael Hanselmann
      names = _GenerateUniqueNames(self.lu, lv_names)
6788 2bb5c911 Michael Hanselmann
6789 2bb5c911 Michael Hanselmann
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
6790 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[0]))
6791 a9e0c397 Iustin Pop
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6792 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[1]))
6793 2bb5c911 Michael Hanselmann
6794 a9e0c397 Iustin Pop
      new_lvs = [lv_data, lv_meta]
6795 a9e0c397 Iustin Pop
      old_lvs = dev.children
6796 a9e0c397 Iustin Pop
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
6797 2bb5c911 Michael Hanselmann
6798 428958aa Iustin Pop
      # we pass force_create=True to force the LVM creation
6799 a9e0c397 Iustin Pop
      for new_lv in new_lvs:
6800 2bb5c911 Michael Hanselmann
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
6801 2bb5c911 Michael Hanselmann
                        _GetInstanceInfoText(self.instance), False)
6802 2bb5c911 Michael Hanselmann
6803 2bb5c911 Michael Hanselmann
    return iv_names
6804 2bb5c911 Michael Hanselmann
6805 2bb5c911 Michael Hanselmann
  def _CheckDevices(self, node_name, iv_names):
6806 1122eb25 Iustin Pop
    for name, (dev, _, _) in iv_names.iteritems():
6807 2bb5c911 Michael Hanselmann
      self.cfg.SetDiskID(dev, node_name)
6808 2bb5c911 Michael Hanselmann
6809 2bb5c911 Michael Hanselmann
      result = self.rpc.call_blockdev_find(node_name, dev)
6810 2bb5c911 Michael Hanselmann
6811 2bb5c911 Michael Hanselmann
      msg = result.fail_msg
6812 2bb5c911 Michael Hanselmann
      if msg or not result.payload:
6813 2bb5c911 Michael Hanselmann
        if not msg:
6814 2bb5c911 Michael Hanselmann
          msg = "disk not found"
6815 2bb5c911 Michael Hanselmann
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
6816 2bb5c911 Michael Hanselmann
                                 (name, msg))
6817 2bb5c911 Michael Hanselmann
6818 96acbc09 Michael Hanselmann
      if result.payload.is_degraded:
6819 2bb5c911 Michael Hanselmann
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
6820 2bb5c911 Michael Hanselmann
6821 2bb5c911 Michael Hanselmann
  def _RemoveOldStorage(self, node_name, iv_names):
6822 1122eb25 Iustin Pop
    for name, (_, old_lvs, _) in iv_names.iteritems():
6823 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Remove logical volumes for %s" % name)
6824 2bb5c911 Michael Hanselmann
6825 2bb5c911 Michael Hanselmann
      for lv in old_lvs:
6826 2bb5c911 Michael Hanselmann
        self.cfg.SetDiskID(lv, node_name)
6827 2bb5c911 Michael Hanselmann
6828 2bb5c911 Michael Hanselmann
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
6829 2bb5c911 Michael Hanselmann
        if msg:
6830 2bb5c911 Michael Hanselmann
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
6831 2bb5c911 Michael Hanselmann
                             hint="remove unused LVs manually")
6832 2bb5c911 Michael Hanselmann
6833 a4eae71f Michael Hanselmann
  def _ExecDrbd8DiskOnly(self, feedback_fn):
6834 2bb5c911 Michael Hanselmann
    """Replace a disk on the primary or secondary for DRBD 8.
6835 2bb5c911 Michael Hanselmann

6836 2bb5c911 Michael Hanselmann
    The algorithm for replace is quite complicated:
6837 2bb5c911 Michael Hanselmann

6838 2bb5c911 Michael Hanselmann
      1. for each disk to be replaced:
6839 2bb5c911 Michael Hanselmann

6840 2bb5c911 Michael Hanselmann
        1. create new LVs on the target node with unique names
6841 2bb5c911 Michael Hanselmann
        1. detach old LVs from the drbd device
6842 2bb5c911 Michael Hanselmann
        1. rename old LVs to name_replaced.<time_t>
6843 2bb5c911 Michael Hanselmann
        1. rename new LVs to old LVs
6844 2bb5c911 Michael Hanselmann
        1. attach the new LVs (with the old names now) to the drbd device
6845 2bb5c911 Michael Hanselmann

6846 2bb5c911 Michael Hanselmann
      1. wait for sync across all devices
6847 2bb5c911 Michael Hanselmann

6848 2bb5c911 Michael Hanselmann
      1. for each modified disk:
6849 2bb5c911 Michael Hanselmann

6850 2bb5c911 Michael Hanselmann
        1. remove old LVs (which have the name name_replaces.<time_t>)
6851 2bb5c911 Michael Hanselmann

6852 2bb5c911 Michael Hanselmann
    Failures are not very well handled.
6853 2bb5c911 Michael Hanselmann

6854 2bb5c911 Michael Hanselmann
    """
6855 2bb5c911 Michael Hanselmann
    steps_total = 6
6856 2bb5c911 Michael Hanselmann
6857 2bb5c911 Michael Hanselmann
    # Step: check device activation
6858 2bb5c911 Michael Hanselmann
    self.lu.LogStep(1, steps_total, "Check device existence")
6859 2bb5c911 Michael Hanselmann
    self._CheckDisksExistence([self.other_node, self.target_node])
6860 2bb5c911 Michael Hanselmann
    self._CheckVolumeGroup([self.target_node, self.other_node])
6861 2bb5c911 Michael Hanselmann
6862 2bb5c911 Michael Hanselmann
    # Step: check other node consistency
6863 2bb5c911 Michael Hanselmann
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6864 2bb5c911 Michael Hanselmann
    self._CheckDisksConsistency(self.other_node,
6865 2bb5c911 Michael Hanselmann
                                self.other_node == self.instance.primary_node,
6866 2bb5c911 Michael Hanselmann
                                False)
6867 2bb5c911 Michael Hanselmann
6868 2bb5c911 Michael Hanselmann
    # Step: create new storage
6869 2bb5c911 Michael Hanselmann
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6870 2bb5c911 Michael Hanselmann
    iv_names = self._CreateNewStorage(self.target_node)
6871 a9e0c397 Iustin Pop
6872 cff90b79 Iustin Pop
    # Step: for each lv, detach+rename*2+attach
6873 2bb5c911 Michael Hanselmann
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
6874 cff90b79 Iustin Pop
    for dev, old_lvs, new_lvs in iv_names.itervalues():
6875 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
6876 2bb5c911 Michael Hanselmann
6877 4d4a651d Michael Hanselmann
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
6878 4d4a651d Michael Hanselmann
                                                     old_lvs)
6879 4c4e4e1e Iustin Pop
      result.Raise("Can't detach drbd from local storage on node"
6880 2bb5c911 Michael Hanselmann
                   " %s for device %s" % (self.target_node, dev.iv_name))
6881 cff90b79 Iustin Pop
      #dev.children = []
6882 cff90b79 Iustin Pop
      #cfg.Update(instance)
6883 a9e0c397 Iustin Pop
6884 a9e0c397 Iustin Pop
      # ok, we created the new LVs, so now we know we have the needed
6885 a9e0c397 Iustin Pop
      # storage; as such, we proceed on the target node to rename
6886 a9e0c397 Iustin Pop
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
6887 c99a3cc0 Manuel Franceschini
      # using the assumption that logical_id == physical_id (which in
6888 a9e0c397 Iustin Pop
      # turn is the unique_id on that node)
6889 cff90b79 Iustin Pop
6890 cff90b79 Iustin Pop
      # FIXME(iustin): use a better name for the replaced LVs
6891 a9e0c397 Iustin Pop
      temp_suffix = int(time.time())
6892 a9e0c397 Iustin Pop
      ren_fn = lambda d, suff: (d.physical_id[0],
6893 a9e0c397 Iustin Pop
                                d.physical_id[1] + "_replaced-%s" % suff)
6894 2bb5c911 Michael Hanselmann
6895 2bb5c911 Michael Hanselmann
      # Build the rename list based on what LVs exist on the node
6896 2bb5c911 Michael Hanselmann
      rename_old_to_new = []
6897 cff90b79 Iustin Pop
      for to_ren in old_lvs:
6898 2bb5c911 Michael Hanselmann
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
6899 4c4e4e1e Iustin Pop
        if not result.fail_msg and result.payload:
6900 23829f6f Iustin Pop
          # device exists
6901 2bb5c911 Michael Hanselmann
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
6902 cff90b79 Iustin Pop
6903 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Renaming the old LVs on the target node")
6904 4d4a651d Michael Hanselmann
      result = self.rpc.call_blockdev_rename(self.target_node,
6905 4d4a651d Michael Hanselmann
                                             rename_old_to_new)
6906 2bb5c911 Michael Hanselmann
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
6907 2bb5c911 Michael Hanselmann
6908 2bb5c911 Michael Hanselmann
      # Now we rename the new LVs to the old LVs
6909 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Renaming the new LVs on the target node")
6910 2bb5c911 Michael Hanselmann
      rename_new_to_old = [(new, old.physical_id)
6911 2bb5c911 Michael Hanselmann
                           for old, new in zip(old_lvs, new_lvs)]
6912 4d4a651d Michael Hanselmann
      result = self.rpc.call_blockdev_rename(self.target_node,
6913 4d4a651d Michael Hanselmann
                                             rename_new_to_old)
6914 2bb5c911 Michael Hanselmann
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
6915 cff90b79 Iustin Pop
6916 cff90b79 Iustin Pop
      for old, new in zip(old_lvs, new_lvs):
6917 cff90b79 Iustin Pop
        new.logical_id = old.logical_id
6918 2bb5c911 Michael Hanselmann
        self.cfg.SetDiskID(new, self.target_node)
6919 a9e0c397 Iustin Pop
6920 cff90b79 Iustin Pop
      for disk in old_lvs:
6921 cff90b79 Iustin Pop
        disk.logical_id = ren_fn(disk, temp_suffix)
6922 2bb5c911 Michael Hanselmann
        self.cfg.SetDiskID(disk, self.target_node)
6923 a9e0c397 Iustin Pop
6924 2bb5c911 Michael Hanselmann
      # Now that the new lvs have the old name, we can add them to the device
6925 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
6926 4d4a651d Michael Hanselmann
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
6927 4d4a651d Michael Hanselmann
                                                  new_lvs)
6928 4c4e4e1e Iustin Pop
      msg = result.fail_msg
6929 2cc1da8b Iustin Pop
      if msg:
6930 a9e0c397 Iustin Pop
        for new_lv in new_lvs:
6931 4d4a651d Michael Hanselmann
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
6932 4d4a651d Michael Hanselmann
                                               new_lv).fail_msg
6933 4c4e4e1e Iustin Pop
          if msg2:
6934 2bb5c911 Michael Hanselmann
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
6935 2bb5c911 Michael Hanselmann
                               hint=("cleanup manually the unused logical"
6936 2bb5c911 Michael Hanselmann
                                     "volumes"))
6937 2cc1da8b Iustin Pop
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
6938 a9e0c397 Iustin Pop
6939 a9e0c397 Iustin Pop
      dev.children = new_lvs
6940 a9e0c397 Iustin Pop
6941 a4eae71f Michael Hanselmann
      self.cfg.Update(self.instance, feedback_fn)
6942 a9e0c397 Iustin Pop
6943 2bb5c911 Michael Hanselmann
    # Wait for sync
6944 2bb5c911 Michael Hanselmann
    # This can fail as the old devices are degraded and _WaitForSync
6945 2bb5c911 Michael Hanselmann
    # does a combined result over all disks, so we don't check its return value
6946 2bb5c911 Michael Hanselmann
    self.lu.LogStep(5, steps_total, "Sync devices")
6947 b6c07b79 Michael Hanselmann
    _WaitForSync(self.lu, self.instance)
6948 a9e0c397 Iustin Pop
6949 2bb5c911 Michael Hanselmann
    # Check all devices manually
6950 2bb5c911 Michael Hanselmann
    self._CheckDevices(self.instance.primary_node, iv_names)
6951 a9e0c397 Iustin Pop
6952 cff90b79 Iustin Pop
    # Step: remove old storage
6953 2bb5c911 Michael Hanselmann
    self.lu.LogStep(6, steps_total, "Removing old storage")
6954 2bb5c911 Michael Hanselmann
    self._RemoveOldStorage(self.target_node, iv_names)
6955 a9e0c397 Iustin Pop
6956 a4eae71f Michael Hanselmann
  def _ExecDrbd8Secondary(self, feedback_fn):
6957 2bb5c911 Michael Hanselmann
    """Replace the secondary node for DRBD 8.
6958 a9e0c397 Iustin Pop

6959 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
6960 a9e0c397 Iustin Pop
      - for all disks of the instance:
6961 a9e0c397 Iustin Pop
        - create new LVs on the new node with same names
6962 a9e0c397 Iustin Pop
        - shutdown the drbd device on the old secondary
6963 a9e0c397 Iustin Pop
        - disconnect the drbd network on the primary
6964 a9e0c397 Iustin Pop
        - create the drbd device on the new secondary
6965 a9e0c397 Iustin Pop
        - network attach the drbd on the primary, using an artifice:
6966 a9e0c397 Iustin Pop
          the drbd code for Attach() will connect to the network if it
6967 a9e0c397 Iustin Pop
          finds a device which is connected to the good local disks but
6968 a9e0c397 Iustin Pop
          not network enabled
6969 a9e0c397 Iustin Pop
      - wait for sync across all devices
6970 a9e0c397 Iustin Pop
      - remove all disks from the old secondary
6971 a9e0c397 Iustin Pop

6972 a9e0c397 Iustin Pop
    Failures are not very well handled.
6973 0834c866 Iustin Pop

6974 a9e0c397 Iustin Pop
    """
6975 0834c866 Iustin Pop
    steps_total = 6
6976 0834c866 Iustin Pop
6977 0834c866 Iustin Pop
    # Step: check device activation
6978 2bb5c911 Michael Hanselmann
    self.lu.LogStep(1, steps_total, "Check device existence")
6979 2bb5c911 Michael Hanselmann
    self._CheckDisksExistence([self.instance.primary_node])
6980 2bb5c911 Michael Hanselmann
    self._CheckVolumeGroup([self.instance.primary_node])
6981 0834c866 Iustin Pop
6982 0834c866 Iustin Pop
    # Step: check other node consistency
6983 2bb5c911 Michael Hanselmann
    self.lu.LogStep(2, steps_total, "Check peer consistency")
6984 2bb5c911 Michael Hanselmann
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
6985 0834c866 Iustin Pop
6986 0834c866 Iustin Pop
    # Step: create new storage
6987 2bb5c911 Michael Hanselmann
    self.lu.LogStep(3, steps_total, "Allocate new storage")
6988 2bb5c911 Michael Hanselmann
    for idx, dev in enumerate(self.instance.disks):
6989 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
6990 2bb5c911 Michael Hanselmann
                      (self.new_node, idx))
6991 428958aa Iustin Pop
      # we pass force_create=True to force LVM creation
6992 a9e0c397 Iustin Pop
      for new_lv in dev.children:
6993 2bb5c911 Michael Hanselmann
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
6994 2bb5c911 Michael Hanselmann
                        _GetInstanceInfoText(self.instance), False)
6995 a9e0c397 Iustin Pop
6996 468b46f9 Iustin Pop
    # Step 4: dbrd minors and drbd setups changes
6997 a1578d63 Iustin Pop
    # after this, we must manually remove the drbd minors on both the
6998 a1578d63 Iustin Pop
    # error and the success paths
6999 2bb5c911 Michael Hanselmann
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7000 4d4a651d Michael Hanselmann
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7001 4d4a651d Michael Hanselmann
                                         for dev in self.instance.disks],
7002 2bb5c911 Michael Hanselmann
                                        self.instance.name)
7003 099c52ad Iustin Pop
    logging.debug("Allocated minors %r", minors)
7004 2bb5c911 Michael Hanselmann
7005 2bb5c911 Michael Hanselmann
    iv_names = {}
7006 2bb5c911 Michael Hanselmann
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7007 4d4a651d Michael Hanselmann
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7008 4d4a651d Michael Hanselmann
                      (self.new_node, idx))
7009 a2d59d8b Iustin Pop
      # create new devices on new_node; note that we create two IDs:
7010 a2d59d8b Iustin Pop
      # one without port, so the drbd will be activated without
7011 a2d59d8b Iustin Pop
      # networking information on the new node at this stage, and one
7012 a2d59d8b Iustin Pop
      # with network, for the latter activation in step 4
7013 a2d59d8b Iustin Pop
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7014 2bb5c911 Michael Hanselmann
      if self.instance.primary_node == o_node1:
7015 a2d59d8b Iustin Pop
        p_minor = o_minor1
7016 ffa1c0dc Iustin Pop
      else:
7017 1122eb25 Iustin Pop
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7018 a2d59d8b Iustin Pop
        p_minor = o_minor2
7019 a2d59d8b Iustin Pop
7020 4d4a651d Michael Hanselmann
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7021 4d4a651d Michael Hanselmann
                      p_minor, new_minor, o_secret)
7022 4d4a651d Michael Hanselmann
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7023 4d4a651d Michael Hanselmann
                    p_minor, new_minor, o_secret)
7024 a2d59d8b Iustin Pop
7025 a2d59d8b Iustin Pop
      iv_names[idx] = (dev, dev.children, new_net_id)
7026 a1578d63 Iustin Pop
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7027 a2d59d8b Iustin Pop
                    new_net_id)
7028 a9e0c397 Iustin Pop
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7029 a2d59d8b Iustin Pop
                              logical_id=new_alone_id,
7030 8a6c7011 Iustin Pop
                              children=dev.children,
7031 8a6c7011 Iustin Pop
                              size=dev.size)
7032 796cab27 Iustin Pop
      try:
7033 2bb5c911 Michael Hanselmann
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7034 2bb5c911 Michael Hanselmann
                              _GetInstanceInfoText(self.instance), False)
7035 82759cb1 Iustin Pop
      except errors.GenericError:
7036 2bb5c911 Michael Hanselmann
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7037 796cab27 Iustin Pop
        raise
7038 a9e0c397 Iustin Pop
7039 2bb5c911 Michael Hanselmann
    # We have new devices, shutdown the drbd on the old secondary
7040 2bb5c911 Michael Hanselmann
    for idx, dev in enumerate(self.instance.disks):
7041 2bb5c911 Michael Hanselmann
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7042 2bb5c911 Michael Hanselmann
      self.cfg.SetDiskID(dev, self.target_node)
7043 2bb5c911 Michael Hanselmann
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7044 cacfd1fd Iustin Pop
      if msg:
7045 2bb5c911 Michael Hanselmann
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7046 2bb5c911 Michael Hanselmann
                           "node: %s" % (idx, msg),
7047 2bb5c911 Michael Hanselmann
                           hint=("Please cleanup this device manually as"
7048 2bb5c911 Michael Hanselmann
                                 " soon as possible"))
7049 a9e0c397 Iustin Pop
7050 2bb5c911 Michael Hanselmann
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7051 4d4a651d Michael Hanselmann
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7052 4d4a651d Michael Hanselmann
                                               self.node_secondary_ip,
7053 4d4a651d Michael Hanselmann
                                               self.instance.disks)\
7054 4d4a651d Michael Hanselmann
                                              [self.instance.primary_node]
7055 642445d9 Iustin Pop
7056 4c4e4e1e Iustin Pop
    msg = result.fail_msg
7057 a2d59d8b Iustin Pop
    if msg:
7058 a2d59d8b Iustin Pop
      # detaches didn't succeed (unlikely)
7059 2bb5c911 Michael Hanselmann
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7060 a2d59d8b Iustin Pop
      raise errors.OpExecError("Can't detach the disks from the network on"
7061 a2d59d8b Iustin Pop
                               " old node: %s" % (msg,))
7062 642445d9 Iustin Pop
7063 642445d9 Iustin Pop
    # if we managed to detach at least one, we update all the disks of
7064 642445d9 Iustin Pop
    # the instance to point to the new secondary
7065 2bb5c911 Michael Hanselmann
    self.lu.LogInfo("Updating instance configuration")
7066 468b46f9 Iustin Pop
    for dev, _, new_logical_id in iv_names.itervalues():
7067 468b46f9 Iustin Pop
      dev.logical_id = new_logical_id
7068 2bb5c911 Michael Hanselmann
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7069 2bb5c911 Michael Hanselmann
7070 a4eae71f Michael Hanselmann
    self.cfg.Update(self.instance, feedback_fn)
7071 a9e0c397 Iustin Pop
7072 642445d9 Iustin Pop
    # and now perform the drbd attach
7073 2bb5c911 Michael Hanselmann
    self.lu.LogInfo("Attaching primary drbds to new secondary"
7074 2bb5c911 Michael Hanselmann
                    " (standalone => connected)")
7075 4d4a651d Michael Hanselmann
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
7076 4d4a651d Michael Hanselmann
                                            self.new_node],
7077 4d4a651d Michael Hanselmann
                                           self.node_secondary_ip,
7078 4d4a651d Michael Hanselmann
                                           self.instance.disks,
7079 4d4a651d Michael Hanselmann
                                           self.instance.name,
7080 a2d59d8b Iustin Pop
                                           False)
7081 a2d59d8b Iustin Pop
    for to_node, to_result in result.items():
7082 4c4e4e1e Iustin Pop
      msg = to_result.fail_msg
7083 a2d59d8b Iustin Pop
      if msg:
7084 4d4a651d Michael Hanselmann
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
7085 4d4a651d Michael Hanselmann
                           to_node, msg,
7086 2bb5c911 Michael Hanselmann
                           hint=("please do a gnt-instance info to see the"
7087 2bb5c911 Michael Hanselmann
                                 " status of disks"))
7088 a9e0c397 Iustin Pop
7089 2bb5c911 Michael Hanselmann
    # Wait for sync
7090 2bb5c911 Michael Hanselmann
    # This can fail as the old devices are degraded and _WaitForSync
7091 2bb5c911 Michael Hanselmann
    # does a combined result over all disks, so we don't check its return value
7092 2bb5c911 Michael Hanselmann
    self.lu.LogStep(5, steps_total, "Sync devices")
7093 b6c07b79 Michael Hanselmann
    _WaitForSync(self.lu, self.instance)
7094 a9e0c397 Iustin Pop
7095 2bb5c911 Michael Hanselmann
    # Check all devices manually
7096 2bb5c911 Michael Hanselmann
    self._CheckDevices(self.instance.primary_node, iv_names)
7097 22985314 Guido Trotter
7098 2bb5c911 Michael Hanselmann
    # Step: remove old storage
7099 2bb5c911 Michael Hanselmann
    self.lu.LogStep(6, steps_total, "Removing old storage")
7100 2bb5c911 Michael Hanselmann
    self._RemoveOldStorage(self.target_node, iv_names)
7101 a9e0c397 Iustin Pop
7102 a8083063 Iustin Pop
7103 76aef8fc Michael Hanselmann
class LURepairNodeStorage(NoHooksLU):
7104 76aef8fc Michael Hanselmann
  """Repairs the volume group on a node.
7105 76aef8fc Michael Hanselmann

7106 76aef8fc Michael Hanselmann
  """
7107 76aef8fc Michael Hanselmann
  _OP_REQP = ["node_name"]
7108 76aef8fc Michael Hanselmann
  REQ_BGL = False
7109 76aef8fc Michael Hanselmann
7110 76aef8fc Michael Hanselmann
  def CheckArguments(self):
7111 76aef8fc Michael Hanselmann
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
7112 76aef8fc Michael Hanselmann
    if node_name is None:
7113 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name,
7114 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
7115 76aef8fc Michael Hanselmann
7116 76aef8fc Michael Hanselmann
    self.op.node_name = node_name
7117 76aef8fc Michael Hanselmann
7118 76aef8fc Michael Hanselmann
  def ExpandNames(self):
7119 76aef8fc Michael Hanselmann
    self.needed_locks = {
7120 76aef8fc Michael Hanselmann
      locking.LEVEL_NODE: [self.op.node_name],
7121 76aef8fc Michael Hanselmann
      }
7122 76aef8fc Michael Hanselmann
7123 76aef8fc Michael Hanselmann
  def _CheckFaultyDisks(self, instance, node_name):
7124 7e9c6a78 Iustin Pop
    """Ensure faulty disks abort the opcode or at least warn."""
7125 7e9c6a78 Iustin Pop
    try:
7126 7e9c6a78 Iustin Pop
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7127 7e9c6a78 Iustin Pop
                                  node_name, True):
7128 7e9c6a78 Iustin Pop
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7129 7e9c6a78 Iustin Pop
                                   " node '%s'" % (instance.name, node_name),
7130 7e9c6a78 Iustin Pop
                                   errors.ECODE_STATE)
7131 7e9c6a78 Iustin Pop
    except errors.OpPrereqError, err:
7132 7e9c6a78 Iustin Pop
      if self.op.ignore_consistency:
7133 7e9c6a78 Iustin Pop
        self.proc.LogWarning(str(err.args[0]))
7134 7e9c6a78 Iustin Pop
      else:
7135 7e9c6a78 Iustin Pop
        raise
7136 76aef8fc Michael Hanselmann
7137 76aef8fc Michael Hanselmann
  def CheckPrereq(self):
7138 76aef8fc Michael Hanselmann
    """Check prerequisites.
7139 76aef8fc Michael Hanselmann

7140 76aef8fc Michael Hanselmann
    """
7141 76aef8fc Michael Hanselmann
    storage_type = self.op.storage_type
7142 76aef8fc Michael Hanselmann
7143 76aef8fc Michael Hanselmann
    if (constants.SO_FIX_CONSISTENCY not in
7144 76aef8fc Michael Hanselmann
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7145 76aef8fc Michael Hanselmann
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7146 5c983ee5 Iustin Pop
                                 " repaired" % storage_type,
7147 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
7148 76aef8fc Michael Hanselmann
7149 76aef8fc Michael Hanselmann
    # Check whether any instance on this node has faulty disks
7150 76aef8fc Michael Hanselmann
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7151 7e9c6a78 Iustin Pop
      if not inst.admin_up:
7152 7e9c6a78 Iustin Pop
        continue
7153 76aef8fc Michael Hanselmann
      check_nodes = set(inst.all_nodes)
7154 76aef8fc Michael Hanselmann
      check_nodes.discard(self.op.node_name)
7155 76aef8fc Michael Hanselmann
      for inst_node_name in check_nodes:
7156 76aef8fc Michael Hanselmann
        self._CheckFaultyDisks(inst, inst_node_name)
7157 76aef8fc Michael Hanselmann
7158 76aef8fc Michael Hanselmann
  def Exec(self, feedback_fn):
7159 76aef8fc Michael Hanselmann
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7160 76aef8fc Michael Hanselmann
                (self.op.name, self.op.node_name))
7161 76aef8fc Michael Hanselmann
7162 76aef8fc Michael Hanselmann
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7163 76aef8fc Michael Hanselmann
    result = self.rpc.call_storage_execute(self.op.node_name,
7164 76aef8fc Michael Hanselmann
                                           self.op.storage_type, st_args,
7165 76aef8fc Michael Hanselmann
                                           self.op.name,
7166 76aef8fc Michael Hanselmann
                                           constants.SO_FIX_CONSISTENCY)
7167 76aef8fc Michael Hanselmann
    result.Raise("Failed to repair storage unit '%s' on %s" %
7168 76aef8fc Michael Hanselmann
                 (self.op.name, self.op.node_name))
7169 76aef8fc Michael Hanselmann
7170 76aef8fc Michael Hanselmann
7171 8729e0d7 Iustin Pop
class LUGrowDisk(LogicalUnit):
7172 8729e0d7 Iustin Pop
  """Grow a disk of an instance.
7173 8729e0d7 Iustin Pop

7174 8729e0d7 Iustin Pop
  """
7175 8729e0d7 Iustin Pop
  HPATH = "disk-grow"
7176 8729e0d7 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
7177 6605411d Iustin Pop
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7178 31e63dbf Guido Trotter
  REQ_BGL = False
7179 31e63dbf Guido Trotter
7180 31e63dbf Guido Trotter
  def ExpandNames(self):
7181 31e63dbf Guido Trotter
    self._ExpandAndLockInstance()
7182 31e63dbf Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
7183 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7184 31e63dbf Guido Trotter
7185 31e63dbf Guido Trotter
  def DeclareLocks(self, level):
7186 31e63dbf Guido Trotter
    if level == locking.LEVEL_NODE:
7187 31e63dbf Guido Trotter
      self._LockInstancesNodes()
7188 8729e0d7 Iustin Pop
7189 8729e0d7 Iustin Pop
  def BuildHooksEnv(self):
7190 8729e0d7 Iustin Pop
    """Build hooks env.
7191 8729e0d7 Iustin Pop

7192 8729e0d7 Iustin Pop
    This runs on the master, the primary and all the secondaries.
7193 8729e0d7 Iustin Pop

7194 8729e0d7 Iustin Pop
    """
7195 8729e0d7 Iustin Pop
    env = {
7196 8729e0d7 Iustin Pop
      "DISK": self.op.disk,
7197 8729e0d7 Iustin Pop
      "AMOUNT": self.op.amount,
7198 8729e0d7 Iustin Pop
      }
7199 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7200 8729e0d7 Iustin Pop
    nl = [
7201 d6a02168 Michael Hanselmann
      self.cfg.GetMasterNode(),
7202 8729e0d7 Iustin Pop
      self.instance.primary_node,
7203 8729e0d7 Iustin Pop
      ]
7204 8729e0d7 Iustin Pop
    return env, nl, nl
7205 8729e0d7 Iustin Pop
7206 8729e0d7 Iustin Pop
  def CheckPrereq(self):
7207 8729e0d7 Iustin Pop
    """Check prerequisites.
7208 8729e0d7 Iustin Pop

7209 8729e0d7 Iustin Pop
    This checks that the instance is in the cluster.
7210 8729e0d7 Iustin Pop

7211 8729e0d7 Iustin Pop
    """
7212 31e63dbf Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7213 31e63dbf Guido Trotter
    assert instance is not None, \
7214 31e63dbf Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
7215 6b12959c Iustin Pop
    nodenames = list(instance.all_nodes)
7216 6b12959c Iustin Pop
    for node in nodenames:
7217 7527a8a4 Iustin Pop
      _CheckNodeOnline(self, node)
7218 7527a8a4 Iustin Pop
7219 31e63dbf Guido Trotter
7220 8729e0d7 Iustin Pop
    self.instance = instance
7221 8729e0d7 Iustin Pop
7222 8729e0d7 Iustin Pop
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
7223 8729e0d7 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout does not support"
7224 5c983ee5 Iustin Pop
                                 " growing.", errors.ECODE_INVAL)
7225 8729e0d7 Iustin Pop
7226 ad24e046 Iustin Pop
    self.disk = instance.FindDisk(self.op.disk)
7227 8729e0d7 Iustin Pop
7228 72737a7f Iustin Pop
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
7229 72737a7f Iustin Pop
                                       instance.hypervisor)
7230 8729e0d7 Iustin Pop
    for node in nodenames:
7231 781de953 Iustin Pop
      info = nodeinfo[node]
7232 4c4e4e1e Iustin Pop
      info.Raise("Cannot get current information from node %s" % node)
7233 070e998b Iustin Pop
      vg_free = info.payload.get('vg_free', None)
7234 8729e0d7 Iustin Pop
      if not isinstance(vg_free, int):
7235 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Can't compute free disk space on"
7236 5c983ee5 Iustin Pop
                                   " node %s" % node, errors.ECODE_ENVIRON)
7237 781de953 Iustin Pop
      if self.op.amount > vg_free:
7238 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
7239 8729e0d7 Iustin Pop
                                   " %d MiB available, %d MiB required" %
7240 5c983ee5 Iustin Pop
                                   (node, vg_free, self.op.amount),
7241 5c983ee5 Iustin Pop
                                   errors.ECODE_NORES)
7242 8729e0d7 Iustin Pop
7243 8729e0d7 Iustin Pop
  def Exec(self, feedback_fn):
7244 8729e0d7 Iustin Pop
    """Execute disk grow.
7245 8729e0d7 Iustin Pop

7246 8729e0d7 Iustin Pop
    """
7247 8729e0d7 Iustin Pop
    instance = self.instance
7248 ad24e046 Iustin Pop
    disk = self.disk
7249 6b12959c Iustin Pop
    for node in instance.all_nodes:
7250 8729e0d7 Iustin Pop
      self.cfg.SetDiskID(disk, node)
7251 72737a7f Iustin Pop
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7252 4c4e4e1e Iustin Pop
      result.Raise("Grow request failed to node %s" % node)
7253 5bc556dd Michael Hanselmann
7254 5bc556dd Michael Hanselmann
      # TODO: Rewrite code to work properly
7255 5bc556dd Michael Hanselmann
      # DRBD goes into sync mode for a short amount of time after executing the
7256 5bc556dd Michael Hanselmann
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
7257 5bc556dd Michael Hanselmann
      # calling "resize" in sync mode fails. Sleeping for a short amount of
7258 5bc556dd Michael Hanselmann
      # time is a work-around.
7259 5bc556dd Michael Hanselmann
      time.sleep(5)
7260 5bc556dd Michael Hanselmann
7261 8729e0d7 Iustin Pop
    disk.RecordGrow(self.op.amount)
7262 a4eae71f Michael Hanselmann
    self.cfg.Update(instance, feedback_fn)
7263 6605411d Iustin Pop
    if self.op.wait_for_sync:
7264 cd4d138f Guido Trotter
      disk_abort = not _WaitForSync(self, instance)
7265 6605411d Iustin Pop
      if disk_abort:
7266 86d9d3bb Iustin Pop
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
7267 86d9d3bb Iustin Pop
                             " status.\nPlease check the instance.")
7268 8729e0d7 Iustin Pop
7269 8729e0d7 Iustin Pop
7270 a8083063 Iustin Pop
class LUQueryInstanceData(NoHooksLU):
7271 a8083063 Iustin Pop
  """Query runtime instance data.
7272 a8083063 Iustin Pop

7273 a8083063 Iustin Pop
  """
7274 57821cac Iustin Pop
  _OP_REQP = ["instances", "static"]
7275 a987fa48 Guido Trotter
  REQ_BGL = False
7276 ae5849b5 Michael Hanselmann
7277 a987fa48 Guido Trotter
  def ExpandNames(self):
7278 a987fa48 Guido Trotter
    self.needed_locks = {}
7279 c772d142 Michael Hanselmann
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
7280 a987fa48 Guido Trotter
7281 a987fa48 Guido Trotter
    if not isinstance(self.op.instances, list):
7282 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Invalid argument type 'instances'",
7283 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
7284 a987fa48 Guido Trotter
7285 a987fa48 Guido Trotter
    if self.op.instances:
7286 a987fa48 Guido Trotter
      self.wanted_names = []
7287 a987fa48 Guido Trotter
      for name in self.op.instances:
7288 a987fa48 Guido Trotter
        full_name = self.cfg.ExpandInstanceName(name)
7289 a987fa48 Guido Trotter
        if full_name is None:
7290 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Instance '%s' not known" % name,
7291 5c983ee5 Iustin Pop
                                     errors.ECODE_NOENT)
7292 a987fa48 Guido Trotter
        self.wanted_names.append(full_name)
7293 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
7294 a987fa48 Guido Trotter
    else:
7295 a987fa48 Guido Trotter
      self.wanted_names = None
7296 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
7297 a987fa48 Guido Trotter
7298 a987fa48 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
7299 a987fa48 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7300 a987fa48 Guido Trotter
7301 a987fa48 Guido Trotter
  def DeclareLocks(self, level):
7302 a987fa48 Guido Trotter
    if level == locking.LEVEL_NODE:
7303 a987fa48 Guido Trotter
      self._LockInstancesNodes()
7304 a8083063 Iustin Pop
7305 a8083063 Iustin Pop
  def CheckPrereq(self):
7306 a8083063 Iustin Pop
    """Check prerequisites.
7307 a8083063 Iustin Pop

7308 a8083063 Iustin Pop
    This only checks the optional instance list against the existing names.
7309 a8083063 Iustin Pop

7310 a8083063 Iustin Pop
    """
7311 a987fa48 Guido Trotter
    if self.wanted_names is None:
7312 a987fa48 Guido Trotter
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
7313 a8083063 Iustin Pop
7314 a987fa48 Guido Trotter
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
7315 a987fa48 Guido Trotter
                             in self.wanted_names]
7316 a987fa48 Guido Trotter
    return
7317 a8083063 Iustin Pop
7318 98825740 Michael Hanselmann
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
7319 98825740 Michael Hanselmann
    """Returns the status of a block device
7320 98825740 Michael Hanselmann

7321 98825740 Michael Hanselmann
    """
7322 4dce1a83 Michael Hanselmann
    if self.op.static or not node:
7323 98825740 Michael Hanselmann
      return None
7324 98825740 Michael Hanselmann
7325 98825740 Michael Hanselmann
    self.cfg.SetDiskID(dev, node)
7326 98825740 Michael Hanselmann
7327 98825740 Michael Hanselmann
    result = self.rpc.call_blockdev_find(node, dev)
7328 98825740 Michael Hanselmann
    if result.offline:
7329 98825740 Michael Hanselmann
      return None
7330 98825740 Michael Hanselmann
7331 98825740 Michael Hanselmann
    result.Raise("Can't compute disk status for %s" % instance_name)
7332 98825740 Michael Hanselmann
7333 98825740 Michael Hanselmann
    status = result.payload
7334 ddfe2228 Michael Hanselmann
    if status is None:
7335 ddfe2228 Michael Hanselmann
      return None
7336 98825740 Michael Hanselmann
7337 98825740 Michael Hanselmann
    return (status.dev_path, status.major, status.minor,
7338 98825740 Michael Hanselmann
            status.sync_percent, status.estimated_time,
7339 f208978a Michael Hanselmann
            status.is_degraded, status.ldisk_status)
7340 98825740 Michael Hanselmann
7341 a8083063 Iustin Pop
  def _ComputeDiskStatus(self, instance, snode, dev):
7342 a8083063 Iustin Pop
    """Compute block device status.
7343 a8083063 Iustin Pop

7344 a8083063 Iustin Pop
    """
7345 a1f445d3 Iustin Pop
    if dev.dev_type in constants.LDS_DRBD:
7346 a8083063 Iustin Pop
      # we change the snode then (otherwise we use the one passed in)
7347 a8083063 Iustin Pop
      if dev.logical_id[0] == instance.primary_node:
7348 a8083063 Iustin Pop
        snode = dev.logical_id[1]
7349 a8083063 Iustin Pop
      else:
7350 a8083063 Iustin Pop
        snode = dev.logical_id[0]
7351 a8083063 Iustin Pop
7352 98825740 Michael Hanselmann
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
7353 98825740 Michael Hanselmann
                                              instance.name, dev)
7354 98825740 Michael Hanselmann
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
7355 a8083063 Iustin Pop
7356 a8083063 Iustin Pop
    if dev.children:
7357 a8083063 Iustin Pop
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
7358 a8083063 Iustin Pop
                      for child in dev.children]
7359 a8083063 Iustin Pop
    else:
7360 a8083063 Iustin Pop
      dev_children = []
7361 a8083063 Iustin Pop
7362 a8083063 Iustin Pop
    data = {
7363 a8083063 Iustin Pop
      "iv_name": dev.iv_name,
7364 a8083063 Iustin Pop
      "dev_type": dev.dev_type,
7365 a8083063 Iustin Pop
      "logical_id": dev.logical_id,
7366 a8083063 Iustin Pop
      "physical_id": dev.physical_id,
7367 a8083063 Iustin Pop
      "pstatus": dev_pstatus,
7368 a8083063 Iustin Pop
      "sstatus": dev_sstatus,
7369 a8083063 Iustin Pop
      "children": dev_children,
7370 b6fdf8b8 Iustin Pop
      "mode": dev.mode,
7371 c98162a7 Iustin Pop
      "size": dev.size,
7372 a8083063 Iustin Pop
      }
7373 a8083063 Iustin Pop
7374 a8083063 Iustin Pop
    return data
7375 a8083063 Iustin Pop
7376 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
7377 a8083063 Iustin Pop
    """Gather and return data"""
7378 a8083063 Iustin Pop
    result = {}
7379 338e51e8 Iustin Pop
7380 338e51e8 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
7381 338e51e8 Iustin Pop
7382 a8083063 Iustin Pop
    for instance in self.wanted_instances:
7383 57821cac Iustin Pop
      if not self.op.static:
7384 57821cac Iustin Pop
        remote_info = self.rpc.call_instance_info(instance.primary_node,
7385 57821cac Iustin Pop
                                                  instance.name,
7386 57821cac Iustin Pop
                                                  instance.hypervisor)
7387 4c4e4e1e Iustin Pop
        remote_info.Raise("Error checking node %s" % instance.primary_node)
7388 7ad1af4a Iustin Pop
        remote_info = remote_info.payload
7389 57821cac Iustin Pop
        if remote_info and "state" in remote_info:
7390 57821cac Iustin Pop
          remote_state = "up"
7391 57821cac Iustin Pop
        else:
7392 57821cac Iustin Pop
          remote_state = "down"
7393 a8083063 Iustin Pop
      else:
7394 57821cac Iustin Pop
        remote_state = None
7395 0d68c45d Iustin Pop
      if instance.admin_up:
7396 a8083063 Iustin Pop
        config_state = "up"
7397 0d68c45d Iustin Pop
      else:
7398 0d68c45d Iustin Pop
        config_state = "down"
7399 a8083063 Iustin Pop
7400 a8083063 Iustin Pop
      disks = [self._ComputeDiskStatus(instance, None, device)
7401 a8083063 Iustin Pop
               for device in instance.disks]
7402 a8083063 Iustin Pop
7403 a8083063 Iustin Pop
      idict = {
7404 a8083063 Iustin Pop
        "name": instance.name,
7405 a8083063 Iustin Pop
        "config_state": config_state,
7406 a8083063 Iustin Pop
        "run_state": remote_state,
7407 a8083063 Iustin Pop
        "pnode": instance.primary_node,
7408 a8083063 Iustin Pop
        "snodes": instance.secondary_nodes,
7409 a8083063 Iustin Pop
        "os": instance.os,
7410 0b13832c Guido Trotter
        # this happens to be the same format used for hooks
7411 0b13832c Guido Trotter
        "nics": _NICListToTuple(self, instance.nics),
7412 a8083063 Iustin Pop
        "disks": disks,
7413 e69d05fd Iustin Pop
        "hypervisor": instance.hypervisor,
7414 24838135 Iustin Pop
        "network_port": instance.network_port,
7415 24838135 Iustin Pop
        "hv_instance": instance.hvparams,
7416 7736a5f2 Iustin Pop
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
7417 338e51e8 Iustin Pop
        "be_instance": instance.beparams,
7418 338e51e8 Iustin Pop
        "be_actual": cluster.FillBE(instance),
7419 90f72445 Iustin Pop
        "serial_no": instance.serial_no,
7420 90f72445 Iustin Pop
        "mtime": instance.mtime,
7421 90f72445 Iustin Pop
        "ctime": instance.ctime,
7422 033d58b0 Iustin Pop
        "uuid": instance.uuid,
7423 a8083063 Iustin Pop
        }
7424 a8083063 Iustin Pop
7425 a8083063 Iustin Pop
      result[instance.name] = idict
7426 a8083063 Iustin Pop
7427 a8083063 Iustin Pop
    return result
7428 a8083063 Iustin Pop
7429 a8083063 Iustin Pop
7430 7767bbf5 Manuel Franceschini
class LUSetInstanceParams(LogicalUnit):
7431 a8083063 Iustin Pop
  """Modifies an instances's parameters.
7432 a8083063 Iustin Pop

7433 a8083063 Iustin Pop
  """
7434 a8083063 Iustin Pop
  HPATH = "instance-modify"
7435 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
7436 24991749 Iustin Pop
  _OP_REQP = ["instance_name"]
7437 1a5c7281 Guido Trotter
  REQ_BGL = False
7438 1a5c7281 Guido Trotter
7439 24991749 Iustin Pop
  def CheckArguments(self):
7440 24991749 Iustin Pop
    if not hasattr(self.op, 'nics'):
7441 24991749 Iustin Pop
      self.op.nics = []
7442 24991749 Iustin Pop
    if not hasattr(self.op, 'disks'):
7443 24991749 Iustin Pop
      self.op.disks = []
7444 24991749 Iustin Pop
    if not hasattr(self.op, 'beparams'):
7445 24991749 Iustin Pop
      self.op.beparams = {}
7446 24991749 Iustin Pop
    if not hasattr(self.op, 'hvparams'):
7447 24991749 Iustin Pop
      self.op.hvparams = {}
7448 24991749 Iustin Pop
    self.op.force = getattr(self.op, "force", False)
7449 24991749 Iustin Pop
    if not (self.op.nics or self.op.disks or
7450 24991749 Iustin Pop
            self.op.hvparams or self.op.beparams):
7451 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
7452 24991749 Iustin Pop
7453 7736a5f2 Iustin Pop
    if self.op.hvparams:
7454 7736a5f2 Iustin Pop
      _CheckGlobalHvParams(self.op.hvparams)
7455 7736a5f2 Iustin Pop
7456 24991749 Iustin Pop
    # Disk validation
7457 24991749 Iustin Pop
    disk_addremove = 0
7458 24991749 Iustin Pop
    for disk_op, disk_dict in self.op.disks:
7459 24991749 Iustin Pop
      if disk_op == constants.DDM_REMOVE:
7460 24991749 Iustin Pop
        disk_addremove += 1
7461 24991749 Iustin Pop
        continue
7462 24991749 Iustin Pop
      elif disk_op == constants.DDM_ADD:
7463 24991749 Iustin Pop
        disk_addremove += 1
7464 24991749 Iustin Pop
      else:
7465 24991749 Iustin Pop
        if not isinstance(disk_op, int):
7466 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
7467 8b46606c Guido Trotter
        if not isinstance(disk_dict, dict):
7468 8b46606c Guido Trotter
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
7469 5c983ee5 Iustin Pop
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7470 8b46606c Guido Trotter
7471 24991749 Iustin Pop
      if disk_op == constants.DDM_ADD:
7472 24991749 Iustin Pop
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
7473 6ec66eae Iustin Pop
        if mode not in constants.DISK_ACCESS_SET:
7474 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
7475 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7476 24991749 Iustin Pop
        size = disk_dict.get('size', None)
7477 24991749 Iustin Pop
        if size is None:
7478 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Required disk parameter size missing",
7479 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7480 24991749 Iustin Pop
        try:
7481 24991749 Iustin Pop
          size = int(size)
7482 24991749 Iustin Pop
        except ValueError, err:
7483 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
7484 5c983ee5 Iustin Pop
                                     str(err), errors.ECODE_INVAL)
7485 24991749 Iustin Pop
        disk_dict['size'] = size
7486 24991749 Iustin Pop
      else:
7487 24991749 Iustin Pop
        # modification of disk
7488 24991749 Iustin Pop
        if 'size' in disk_dict:
7489 24991749 Iustin Pop
          raise errors.OpPrereqError("Disk size change not possible, use"
7490 5c983ee5 Iustin Pop
                                     " grow-disk", errors.ECODE_INVAL)
7491 24991749 Iustin Pop
7492 24991749 Iustin Pop
    if disk_addremove > 1:
7493 24991749 Iustin Pop
      raise errors.OpPrereqError("Only one disk add or remove operation"
7494 5c983ee5 Iustin Pop
                                 " supported at a time", errors.ECODE_INVAL)
7495 24991749 Iustin Pop
7496 24991749 Iustin Pop
    # NIC validation
7497 24991749 Iustin Pop
    nic_addremove = 0
7498 24991749 Iustin Pop
    for nic_op, nic_dict in self.op.nics:
7499 24991749 Iustin Pop
      if nic_op == constants.DDM_REMOVE:
7500 24991749 Iustin Pop
        nic_addremove += 1
7501 24991749 Iustin Pop
        continue
7502 24991749 Iustin Pop
      elif nic_op == constants.DDM_ADD:
7503 24991749 Iustin Pop
        nic_addremove += 1
7504 24991749 Iustin Pop
      else:
7505 24991749 Iustin Pop
        if not isinstance(nic_op, int):
7506 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
7507 8b46606c Guido Trotter
        if not isinstance(nic_dict, dict):
7508 8b46606c Guido Trotter
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
7509 5c983ee5 Iustin Pop
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
7510 24991749 Iustin Pop
7511 24991749 Iustin Pop
      # nic_dict should be a dict
7512 24991749 Iustin Pop
      nic_ip = nic_dict.get('ip', None)
7513 24991749 Iustin Pop
      if nic_ip is not None:
7514 5c44da6a Guido Trotter
        if nic_ip.lower() == constants.VALUE_NONE:
7515 24991749 Iustin Pop
          nic_dict['ip'] = None
7516 24991749 Iustin Pop
        else:
7517 24991749 Iustin Pop
          if not utils.IsValidIP(nic_ip):
7518 5c983ee5 Iustin Pop
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
7519 5c983ee5 Iustin Pop
                                       errors.ECODE_INVAL)
7520 5c44da6a Guido Trotter
7521 cd098c41 Guido Trotter
      nic_bridge = nic_dict.get('bridge', None)
7522 cd098c41 Guido Trotter
      nic_link = nic_dict.get('link', None)
7523 cd098c41 Guido Trotter
      if nic_bridge and nic_link:
7524 29921401 Iustin Pop
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7525 5c983ee5 Iustin Pop
                                   " at the same time", errors.ECODE_INVAL)
7526 cd098c41 Guido Trotter
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
7527 cd098c41 Guido Trotter
        nic_dict['bridge'] = None
7528 cd098c41 Guido Trotter
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
7529 cd098c41 Guido Trotter
        nic_dict['link'] = None
7530 cd098c41 Guido Trotter
7531 5c44da6a Guido Trotter
      if nic_op == constants.DDM_ADD:
7532 5c44da6a Guido Trotter
        nic_mac = nic_dict.get('mac', None)
7533 5c44da6a Guido Trotter
        if nic_mac is None:
7534 5c44da6a Guido Trotter
          nic_dict['mac'] = constants.VALUE_AUTO
7535 5c44da6a Guido Trotter
7536 5c44da6a Guido Trotter
      if 'mac' in nic_dict:
7537 5c44da6a Guido Trotter
        nic_mac = nic_dict['mac']
7538 24991749 Iustin Pop
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7539 24991749 Iustin Pop
          if not utils.IsValidMac(nic_mac):
7540 5c983ee5 Iustin Pop
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac,
7541 5c983ee5 Iustin Pop
                                       errors.ECODE_INVAL)
7542 5c44da6a Guido Trotter
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
7543 5c44da6a Guido Trotter
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
7544 5c983ee5 Iustin Pop
                                     " modifying an existing nic",
7545 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7546 5c44da6a Guido Trotter
7547 24991749 Iustin Pop
    if nic_addremove > 1:
7548 24991749 Iustin Pop
      raise errors.OpPrereqError("Only one NIC add or remove operation"
7549 5c983ee5 Iustin Pop
                                 " supported at a time", errors.ECODE_INVAL)
7550 24991749 Iustin Pop
7551 1a5c7281 Guido Trotter
  def ExpandNames(self):
7552 1a5c7281 Guido Trotter
    self._ExpandAndLockInstance()
7553 74409b12 Iustin Pop
    self.needed_locks[locking.LEVEL_NODE] = []
7554 74409b12 Iustin Pop
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7555 74409b12 Iustin Pop
7556 74409b12 Iustin Pop
  def DeclareLocks(self, level):
7557 74409b12 Iustin Pop
    if level == locking.LEVEL_NODE:
7558 74409b12 Iustin Pop
      self._LockInstancesNodes()
7559 a8083063 Iustin Pop
7560 a8083063 Iustin Pop
  def BuildHooksEnv(self):
7561 a8083063 Iustin Pop
    """Build hooks env.
7562 a8083063 Iustin Pop

7563 a8083063 Iustin Pop
    This runs on the master, primary and secondaries.
7564 a8083063 Iustin Pop

7565 a8083063 Iustin Pop
    """
7566 396e1b78 Michael Hanselmann
    args = dict()
7567 338e51e8 Iustin Pop
    if constants.BE_MEMORY in self.be_new:
7568 338e51e8 Iustin Pop
      args['memory'] = self.be_new[constants.BE_MEMORY]
7569 338e51e8 Iustin Pop
    if constants.BE_VCPUS in self.be_new:
7570 61be6ba4 Iustin Pop
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
7571 d8dcf3c9 Guido Trotter
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
7572 d8dcf3c9 Guido Trotter
    # information at all.
7573 d8dcf3c9 Guido Trotter
    if self.op.nics:
7574 d8dcf3c9 Guido Trotter
      args['nics'] = []
7575 d8dcf3c9 Guido Trotter
      nic_override = dict(self.op.nics)
7576 62f0dd02 Guido Trotter
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
7577 d8dcf3c9 Guido Trotter
      for idx, nic in enumerate(self.instance.nics):
7578 d8dcf3c9 Guido Trotter
        if idx in nic_override:
7579 d8dcf3c9 Guido Trotter
          this_nic_override = nic_override[idx]
7580 d8dcf3c9 Guido Trotter
        else:
7581 d8dcf3c9 Guido Trotter
          this_nic_override = {}
7582 d8dcf3c9 Guido Trotter
        if 'ip' in this_nic_override:
7583 d8dcf3c9 Guido Trotter
          ip = this_nic_override['ip']
7584 d8dcf3c9 Guido Trotter
        else:
7585 d8dcf3c9 Guido Trotter
          ip = nic.ip
7586 d8dcf3c9 Guido Trotter
        if 'mac' in this_nic_override:
7587 d8dcf3c9 Guido Trotter
          mac = this_nic_override['mac']
7588 d8dcf3c9 Guido Trotter
        else:
7589 d8dcf3c9 Guido Trotter
          mac = nic.mac
7590 62f0dd02 Guido Trotter
        if idx in self.nic_pnew:
7591 62f0dd02 Guido Trotter
          nicparams = self.nic_pnew[idx]
7592 62f0dd02 Guido Trotter
        else:
7593 62f0dd02 Guido Trotter
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
7594 62f0dd02 Guido Trotter
        mode = nicparams[constants.NIC_MODE]
7595 62f0dd02 Guido Trotter
        link = nicparams[constants.NIC_LINK]
7596 62f0dd02 Guido Trotter
        args['nics'].append((ip, mac, mode, link))
7597 d8dcf3c9 Guido Trotter
      if constants.DDM_ADD in nic_override:
7598 d8dcf3c9 Guido Trotter
        ip = nic_override[constants.DDM_ADD].get('ip', None)
7599 d8dcf3c9 Guido Trotter
        mac = nic_override[constants.DDM_ADD]['mac']
7600 62f0dd02 Guido Trotter
        nicparams = self.nic_pnew[constants.DDM_ADD]
7601 62f0dd02 Guido Trotter
        mode = nicparams[constants.NIC_MODE]
7602 62f0dd02 Guido Trotter
        link = nicparams[constants.NIC_LINK]
7603 62f0dd02 Guido Trotter
        args['nics'].append((ip, mac, mode, link))
7604 d8dcf3c9 Guido Trotter
      elif constants.DDM_REMOVE in nic_override:
7605 d8dcf3c9 Guido Trotter
        del args['nics'][-1]
7606 d8dcf3c9 Guido Trotter
7607 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
7608 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7609 a8083063 Iustin Pop
    return env, nl, nl
7610 a8083063 Iustin Pop
7611 7e950d31 Iustin Pop
  @staticmethod
7612 7e950d31 Iustin Pop
  def _GetUpdatedParams(old_params, update_dict,
7613 0329617a Guido Trotter
                        default_values, parameter_types):
7614 0329617a Guido Trotter
    """Return the new params dict for the given params.
7615 0329617a Guido Trotter

7616 0329617a Guido Trotter
    @type old_params: dict
7617 f2fd87d7 Iustin Pop
    @param old_params: old parameters
7618 0329617a Guido Trotter
    @type update_dict: dict
7619 f2fd87d7 Iustin Pop
    @param update_dict: dict containing new parameter values,
7620 f2fd87d7 Iustin Pop
                        or constants.VALUE_DEFAULT to reset the
7621 f2fd87d7 Iustin Pop
                        parameter to its default value
7622 0329617a Guido Trotter
    @type default_values: dict
7623 0329617a Guido Trotter
    @param default_values: default values for the filled parameters
7624 0329617a Guido Trotter
    @type parameter_types: dict
7625 0329617a Guido Trotter
    @param parameter_types: dict mapping target dict keys to types
7626 0329617a Guido Trotter
                            in constants.ENFORCEABLE_TYPES
7627 0329617a Guido Trotter
    @rtype: (dict, dict)
7628 0329617a Guido Trotter
    @return: (new_parameters, filled_parameters)
7629 0329617a Guido Trotter

7630 0329617a Guido Trotter
    """
7631 0329617a Guido Trotter
    params_copy = copy.deepcopy(old_params)
7632 0329617a Guido Trotter
    for key, val in update_dict.iteritems():
7633 0329617a Guido Trotter
      if val == constants.VALUE_DEFAULT:
7634 0329617a Guido Trotter
        try:
7635 0329617a Guido Trotter
          del params_copy[key]
7636 0329617a Guido Trotter
        except KeyError:
7637 0329617a Guido Trotter
          pass
7638 0329617a Guido Trotter
      else:
7639 0329617a Guido Trotter
        params_copy[key] = val
7640 0329617a Guido Trotter
    utils.ForceDictType(params_copy, parameter_types)
7641 0329617a Guido Trotter
    params_filled = objects.FillDict(default_values, params_copy)
7642 0329617a Guido Trotter
    return (params_copy, params_filled)
7643 0329617a Guido Trotter
7644 a8083063 Iustin Pop
  def CheckPrereq(self):
7645 a8083063 Iustin Pop
    """Check prerequisites.
7646 a8083063 Iustin Pop

7647 a8083063 Iustin Pop
    This only checks the instance list against the existing names.
7648 a8083063 Iustin Pop

7649 a8083063 Iustin Pop
    """
7650 7c4d6c7b Michael Hanselmann
    self.force = self.op.force
7651 a8083063 Iustin Pop
7652 74409b12 Iustin Pop
    # checking the new params on the primary/secondary nodes
7653 31a853d2 Iustin Pop
7654 cfefe007 Guido Trotter
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7655 2ee88aeb Guido Trotter
    cluster = self.cluster = self.cfg.GetClusterInfo()
7656 1a5c7281 Guido Trotter
    assert self.instance is not None, \
7657 1a5c7281 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
7658 6b12959c Iustin Pop
    pnode = instance.primary_node
7659 6b12959c Iustin Pop
    nodelist = list(instance.all_nodes)
7660 74409b12 Iustin Pop
7661 338e51e8 Iustin Pop
    # hvparams processing
7662 74409b12 Iustin Pop
    if self.op.hvparams:
7663 0329617a Guido Trotter
      i_hvdict, hv_new = self._GetUpdatedParams(
7664 0329617a Guido Trotter
                             instance.hvparams, self.op.hvparams,
7665 0329617a Guido Trotter
                             cluster.hvparams[instance.hypervisor],
7666 0329617a Guido Trotter
                             constants.HVS_PARAMETER_TYPES)
7667 74409b12 Iustin Pop
      # local check
7668 74409b12 Iustin Pop
      hypervisor.GetHypervisor(
7669 74409b12 Iustin Pop
        instance.hypervisor).CheckParameterSyntax(hv_new)
7670 74409b12 Iustin Pop
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
7671 338e51e8 Iustin Pop
      self.hv_new = hv_new # the new actual values
7672 338e51e8 Iustin Pop
      self.hv_inst = i_hvdict # the new dict (without defaults)
7673 338e51e8 Iustin Pop
    else:
7674 338e51e8 Iustin Pop
      self.hv_new = self.hv_inst = {}
7675 338e51e8 Iustin Pop
7676 338e51e8 Iustin Pop
    # beparams processing
7677 338e51e8 Iustin Pop
    if self.op.beparams:
7678 0329617a Guido Trotter
      i_bedict, be_new = self._GetUpdatedParams(
7679 0329617a Guido Trotter
                             instance.beparams, self.op.beparams,
7680 0329617a Guido Trotter
                             cluster.beparams[constants.PP_DEFAULT],
7681 0329617a Guido Trotter
                             constants.BES_PARAMETER_TYPES)
7682 338e51e8 Iustin Pop
      self.be_new = be_new # the new actual values
7683 338e51e8 Iustin Pop
      self.be_inst = i_bedict # the new dict (without defaults)
7684 338e51e8 Iustin Pop
    else:
7685 b637ae4d Iustin Pop
      self.be_new = self.be_inst = {}
7686 74409b12 Iustin Pop
7687 cfefe007 Guido Trotter
    self.warn = []
7688 647a5d80 Iustin Pop
7689 338e51e8 Iustin Pop
    if constants.BE_MEMORY in self.op.beparams and not self.force:
7690 647a5d80 Iustin Pop
      mem_check_list = [pnode]
7691 c0f2b229 Iustin Pop
      if be_new[constants.BE_AUTO_BALANCE]:
7692 c0f2b229 Iustin Pop
        # either we changed auto_balance to yes or it was from before
7693 647a5d80 Iustin Pop
        mem_check_list.extend(instance.secondary_nodes)
7694 72737a7f Iustin Pop
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
7695 72737a7f Iustin Pop
                                                  instance.hypervisor)
7696 647a5d80 Iustin Pop
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
7697 72737a7f Iustin Pop
                                         instance.hypervisor)
7698 070e998b Iustin Pop
      pninfo = nodeinfo[pnode]
7699 4c4e4e1e Iustin Pop
      msg = pninfo.fail_msg
7700 070e998b Iustin Pop
      if msg:
7701 cfefe007 Guido Trotter
        # Assume the primary node is unreachable and go ahead
7702 070e998b Iustin Pop
        self.warn.append("Can't get info from primary node %s: %s" %
7703 070e998b Iustin Pop
                         (pnode,  msg))
7704 070e998b Iustin Pop
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
7705 070e998b Iustin Pop
        self.warn.append("Node data from primary node %s doesn't contain"
7706 070e998b Iustin Pop
                         " free memory information" % pnode)
7707 4c4e4e1e Iustin Pop
      elif instance_info.fail_msg:
7708 7ad1af4a Iustin Pop
        self.warn.append("Can't get instance runtime information: %s" %
7709 4c4e4e1e Iustin Pop
                        instance_info.fail_msg)
7710 cfefe007 Guido Trotter
      else:
7711 7ad1af4a Iustin Pop
        if instance_info.payload:
7712 7ad1af4a Iustin Pop
          current_mem = int(instance_info.payload['memory'])
7713 cfefe007 Guido Trotter
        else:
7714 cfefe007 Guido Trotter
          # Assume instance not running
7715 cfefe007 Guido Trotter
          # (there is a slight race condition here, but it's not very probable,
7716 cfefe007 Guido Trotter
          # and we have no other way to check)
7717 cfefe007 Guido Trotter
          current_mem = 0
7718 338e51e8 Iustin Pop
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
7719 070e998b Iustin Pop
                    pninfo.payload['memory_free'])
7720 cfefe007 Guido Trotter
        if miss_mem > 0:
7721 cfefe007 Guido Trotter
          raise errors.OpPrereqError("This change will prevent the instance"
7722 cfefe007 Guido Trotter
                                     " from starting, due to %d MB of memory"
7723 5c983ee5 Iustin Pop
                                     " missing on its primary node" % miss_mem,
7724 5c983ee5 Iustin Pop
                                     errors.ECODE_NORES)
7725 cfefe007 Guido Trotter
7726 c0f2b229 Iustin Pop
      if be_new[constants.BE_AUTO_BALANCE]:
7727 070e998b Iustin Pop
        for node, nres in nodeinfo.items():
7728 ea33068f Iustin Pop
          if node not in instance.secondary_nodes:
7729 ea33068f Iustin Pop
            continue
7730 4c4e4e1e Iustin Pop
          msg = nres.fail_msg
7731 070e998b Iustin Pop
          if msg:
7732 070e998b Iustin Pop
            self.warn.append("Can't get info from secondary node %s: %s" %
7733 070e998b Iustin Pop
                             (node, msg))
7734 070e998b Iustin Pop
          elif not isinstance(nres.payload.get('memory_free', None), int):
7735 070e998b Iustin Pop
            self.warn.append("Secondary node %s didn't return free"
7736 070e998b Iustin Pop
                             " memory information" % node)
7737 070e998b Iustin Pop
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
7738 647a5d80 Iustin Pop
            self.warn.append("Not enough memory to failover instance to"
7739 647a5d80 Iustin Pop
                             " secondary node %s" % node)
7740 5bc84f33 Alexander Schreiber
7741 24991749 Iustin Pop
    # NIC processing
7742 cd098c41 Guido Trotter
    self.nic_pnew = {}
7743 cd098c41 Guido Trotter
    self.nic_pinst = {}
7744 24991749 Iustin Pop
    for nic_op, nic_dict in self.op.nics:
7745 24991749 Iustin Pop
      if nic_op == constants.DDM_REMOVE:
7746 24991749 Iustin Pop
        if not instance.nics:
7747 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
7748 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7749 24991749 Iustin Pop
        continue
7750 24991749 Iustin Pop
      if nic_op != constants.DDM_ADD:
7751 24991749 Iustin Pop
        # an existing nic
7752 21bcb9aa Michael Hanselmann
        if not instance.nics:
7753 21bcb9aa Michael Hanselmann
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
7754 21bcb9aa Michael Hanselmann
                                     " no NICs" % nic_op,
7755 21bcb9aa Michael Hanselmann
                                     errors.ECODE_INVAL)
7756 24991749 Iustin Pop
        if nic_op < 0 or nic_op >= len(instance.nics):
7757 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
7758 24991749 Iustin Pop
                                     " are 0 to %d" %
7759 21bcb9aa Michael Hanselmann
                                     (nic_op, len(instance.nics) - 1),
7760 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7761 cd098c41 Guido Trotter
        old_nic_params = instance.nics[nic_op].nicparams
7762 cd098c41 Guido Trotter
        old_nic_ip = instance.nics[nic_op].ip
7763 cd098c41 Guido Trotter
      else:
7764 cd098c41 Guido Trotter
        old_nic_params = {}
7765 cd098c41 Guido Trotter
        old_nic_ip = None
7766 cd098c41 Guido Trotter
7767 cd098c41 Guido Trotter
      update_params_dict = dict([(key, nic_dict[key])
7768 cd098c41 Guido Trotter
                                 for key in constants.NICS_PARAMETERS
7769 cd098c41 Guido Trotter
                                 if key in nic_dict])
7770 cd098c41 Guido Trotter
7771 5c44da6a Guido Trotter
      if 'bridge' in nic_dict:
7772 cd098c41 Guido Trotter
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
7773 cd098c41 Guido Trotter
7774 cd098c41 Guido Trotter
      new_nic_params, new_filled_nic_params = \
7775 cd098c41 Guido Trotter
          self._GetUpdatedParams(old_nic_params, update_params_dict,
7776 cd098c41 Guido Trotter
                                 cluster.nicparams[constants.PP_DEFAULT],
7777 cd098c41 Guido Trotter
                                 constants.NICS_PARAMETER_TYPES)
7778 cd098c41 Guido Trotter
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
7779 cd098c41 Guido Trotter
      self.nic_pinst[nic_op] = new_nic_params
7780 cd098c41 Guido Trotter
      self.nic_pnew[nic_op] = new_filled_nic_params
7781 cd098c41 Guido Trotter
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
7782 cd098c41 Guido Trotter
7783 cd098c41 Guido Trotter
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
7784 cd098c41 Guido Trotter
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
7785 4c4e4e1e Iustin Pop
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
7786 35c0c8da Iustin Pop
        if msg:
7787 35c0c8da Iustin Pop
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
7788 24991749 Iustin Pop
          if self.force:
7789 24991749 Iustin Pop
            self.warn.append(msg)
7790 24991749 Iustin Pop
          else:
7791 5c983ee5 Iustin Pop
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
7792 cd098c41 Guido Trotter
      if new_nic_mode == constants.NIC_MODE_ROUTED:
7793 cd098c41 Guido Trotter
        if 'ip' in nic_dict:
7794 cd098c41 Guido Trotter
          nic_ip = nic_dict['ip']
7795 cd098c41 Guido Trotter
        else:
7796 cd098c41 Guido Trotter
          nic_ip = old_nic_ip
7797 cd098c41 Guido Trotter
        if nic_ip is None:
7798 cd098c41 Guido Trotter
          raise errors.OpPrereqError('Cannot set the nic ip to None'
7799 5c983ee5 Iustin Pop
                                     ' on a routed nic', errors.ECODE_INVAL)
7800 5c44da6a Guido Trotter
      if 'mac' in nic_dict:
7801 5c44da6a Guido Trotter
        nic_mac = nic_dict['mac']
7802 5c44da6a Guido Trotter
        if nic_mac is None:
7803 5c983ee5 Iustin Pop
          raise errors.OpPrereqError('Cannot set the nic mac to None',
7804 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7805 5c44da6a Guido Trotter
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7806 5c44da6a Guido Trotter
          # otherwise generate the mac
7807 36b66e6e Guido Trotter
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
7808 5c44da6a Guido Trotter
        else:
7809 5c44da6a Guido Trotter
          # or validate/reserve the current one
7810 36b66e6e Guido Trotter
          try:
7811 36b66e6e Guido Trotter
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
7812 36b66e6e Guido Trotter
          except errors.ReservationError:
7813 5c44da6a Guido Trotter
            raise errors.OpPrereqError("MAC address %s already in use"
7814 5c983ee5 Iustin Pop
                                       " in cluster" % nic_mac,
7815 5c983ee5 Iustin Pop
                                       errors.ECODE_NOTUNIQUE)
7816 24991749 Iustin Pop
7817 24991749 Iustin Pop
    # DISK processing
7818 24991749 Iustin Pop
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
7819 24991749 Iustin Pop
      raise errors.OpPrereqError("Disk operations not supported for"
7820 5c983ee5 Iustin Pop
                                 " diskless instances",
7821 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
7822 1122eb25 Iustin Pop
    for disk_op, _ in self.op.disks:
7823 24991749 Iustin Pop
      if disk_op == constants.DDM_REMOVE:
7824 24991749 Iustin Pop
        if len(instance.disks) == 1:
7825 24991749 Iustin Pop
          raise errors.OpPrereqError("Cannot remove the last disk of"
7826 5c983ee5 Iustin Pop
                                     " an instance",
7827 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7828 24991749 Iustin Pop
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
7829 24991749 Iustin Pop
        ins_l = ins_l[pnode]
7830 4c4e4e1e Iustin Pop
        msg = ins_l.fail_msg
7831 aca13712 Iustin Pop
        if msg:
7832 aca13712 Iustin Pop
          raise errors.OpPrereqError("Can't contact node %s: %s" %
7833 5c983ee5 Iustin Pop
                                     (pnode, msg), errors.ECODE_ENVIRON)
7834 aca13712 Iustin Pop
        if instance.name in ins_l.payload:
7835 24991749 Iustin Pop
          raise errors.OpPrereqError("Instance is running, can't remove"
7836 5c983ee5 Iustin Pop
                                     " disks.", errors.ECODE_STATE)
7837 24991749 Iustin Pop
7838 24991749 Iustin Pop
      if (disk_op == constants.DDM_ADD and
7839 24991749 Iustin Pop
          len(instance.nics) >= constants.MAX_DISKS):
7840 24991749 Iustin Pop
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
7841 5c983ee5 Iustin Pop
                                   " add more" % constants.MAX_DISKS,
7842 5c983ee5 Iustin Pop
                                   errors.ECODE_STATE)
7843 24991749 Iustin Pop
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
7844 24991749 Iustin Pop
        # an existing disk
7845 24991749 Iustin Pop
        if disk_op < 0 or disk_op >= len(instance.disks):
7846 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
7847 24991749 Iustin Pop
                                     " are 0 to %d" %
7848 5c983ee5 Iustin Pop
                                     (disk_op, len(instance.disks)),
7849 5c983ee5 Iustin Pop
                                     errors.ECODE_INVAL)
7850 24991749 Iustin Pop
7851 a8083063 Iustin Pop
    return
7852 a8083063 Iustin Pop
7853 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
7854 a8083063 Iustin Pop
    """Modifies an instance.
7855 a8083063 Iustin Pop

7856 a8083063 Iustin Pop
    All parameters take effect only at the next restart of the instance.
7857 24991749 Iustin Pop

7858 a8083063 Iustin Pop
    """
7859 cfefe007 Guido Trotter
    # Process here the warnings from CheckPrereq, as we don't have a
7860 cfefe007 Guido Trotter
    # feedback_fn there.
7861 cfefe007 Guido Trotter
    for warn in self.warn:
7862 cfefe007 Guido Trotter
      feedback_fn("WARNING: %s" % warn)
7863 cfefe007 Guido Trotter
7864 a8083063 Iustin Pop
    result = []
7865 a8083063 Iustin Pop
    instance = self.instance
7866 24991749 Iustin Pop
    # disk changes
7867 24991749 Iustin Pop
    for disk_op, disk_dict in self.op.disks:
7868 24991749 Iustin Pop
      if disk_op == constants.DDM_REMOVE:
7869 24991749 Iustin Pop
        # remove the last disk
7870 24991749 Iustin Pop
        device = instance.disks.pop()
7871 24991749 Iustin Pop
        device_idx = len(instance.disks)
7872 24991749 Iustin Pop
        for node, disk in device.ComputeNodeTree(instance.primary_node):
7873 24991749 Iustin Pop
          self.cfg.SetDiskID(disk, node)
7874 4c4e4e1e Iustin Pop
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
7875 e1bc0878 Iustin Pop
          if msg:
7876 e1bc0878 Iustin Pop
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
7877 e1bc0878 Iustin Pop
                            " continuing anyway", device_idx, node, msg)
7878 24991749 Iustin Pop
        result.append(("disk/%d" % device_idx, "remove"))
7879 24991749 Iustin Pop
      elif disk_op == constants.DDM_ADD:
7880 24991749 Iustin Pop
        # add a new disk
7881 24991749 Iustin Pop
        if instance.disk_template == constants.DT_FILE:
7882 24991749 Iustin Pop
          file_driver, file_path = instance.disks[0].logical_id
7883 24991749 Iustin Pop
          file_path = os.path.dirname(file_path)
7884 24991749 Iustin Pop
        else:
7885 24991749 Iustin Pop
          file_driver = file_path = None
7886 24991749 Iustin Pop
        disk_idx_base = len(instance.disks)
7887 24991749 Iustin Pop
        new_disk = _GenerateDiskTemplate(self,
7888 24991749 Iustin Pop
                                         instance.disk_template,
7889 32388e6d Iustin Pop
                                         instance.name, instance.primary_node,
7890 24991749 Iustin Pop
                                         instance.secondary_nodes,
7891 24991749 Iustin Pop
                                         [disk_dict],
7892 24991749 Iustin Pop
                                         file_path,
7893 24991749 Iustin Pop
                                         file_driver,
7894 24991749 Iustin Pop
                                         disk_idx_base)[0]
7895 24991749 Iustin Pop
        instance.disks.append(new_disk)
7896 24991749 Iustin Pop
        info = _GetInstanceInfoText(instance)
7897 24991749 Iustin Pop
7898 24991749 Iustin Pop
        logging.info("Creating volume %s for instance %s",
7899 24991749 Iustin Pop
                     new_disk.iv_name, instance.name)
7900 24991749 Iustin Pop
        # Note: this needs to be kept in sync with _CreateDisks
7901 24991749 Iustin Pop
        #HARDCODE
7902 428958aa Iustin Pop
        for node in instance.all_nodes:
7903 428958aa Iustin Pop
          f_create = node == instance.primary_node
7904 796cab27 Iustin Pop
          try:
7905 428958aa Iustin Pop
            _CreateBlockDev(self, node, instance, new_disk,
7906 428958aa Iustin Pop
                            f_create, info, f_create)
7907 1492cca7 Iustin Pop
          except errors.OpExecError, err:
7908 24991749 Iustin Pop
            self.LogWarning("Failed to create volume %s (%s) on"
7909 428958aa Iustin Pop
                            " node %s: %s",
7910 428958aa Iustin Pop
                            new_disk.iv_name, new_disk, node, err)
7911 24991749 Iustin Pop
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
7912 24991749 Iustin Pop
                       (new_disk.size, new_disk.mode)))
7913 24991749 Iustin Pop
      else:
7914 24991749 Iustin Pop
        # change a given disk
7915 24991749 Iustin Pop
        instance.disks[disk_op].mode = disk_dict['mode']
7916 24991749 Iustin Pop
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
7917 24991749 Iustin Pop
    # NIC changes
7918 24991749 Iustin Pop
    for nic_op, nic_dict in self.op.nics:
7919 24991749 Iustin Pop
      if nic_op == constants.DDM_REMOVE:
7920 24991749 Iustin Pop
        # remove the last nic
7921 24991749 Iustin Pop
        del instance.nics[-1]
7922 24991749 Iustin Pop
        result.append(("nic.%d" % len(instance.nics), "remove"))
7923 24991749 Iustin Pop
      elif nic_op == constants.DDM_ADD:
7924 5c44da6a Guido Trotter
        # mac and bridge should be set, by now
7925 5c44da6a Guido Trotter
        mac = nic_dict['mac']
7926 cd098c41 Guido Trotter
        ip = nic_dict.get('ip', None)
7927 cd098c41 Guido Trotter
        nicparams = self.nic_pinst[constants.DDM_ADD]
7928 cd098c41 Guido Trotter
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
7929 24991749 Iustin Pop
        instance.nics.append(new_nic)
7930 24991749 Iustin Pop
        result.append(("nic.%d" % (len(instance.nics) - 1),
7931 cd098c41 Guido Trotter
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
7932 cd098c41 Guido Trotter
                       (new_nic.mac, new_nic.ip,
7933 cd098c41 Guido Trotter
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
7934 cd098c41 Guido Trotter
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
7935 cd098c41 Guido Trotter
                       )))
7936 24991749 Iustin Pop
      else:
7937 cd098c41 Guido Trotter
        for key in 'mac', 'ip':
7938 24991749 Iustin Pop
          if key in nic_dict:
7939 24991749 Iustin Pop
            setattr(instance.nics[nic_op], key, nic_dict[key])
7940 beabf067 Guido Trotter
        if nic_op in self.nic_pinst:
7941 beabf067 Guido Trotter
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
7942 cd098c41 Guido Trotter
        for key, val in nic_dict.iteritems():
7943 cd098c41 Guido Trotter
          result.append(("nic.%s/%d" % (key, nic_op), val))
7944 24991749 Iustin Pop
7945 24991749 Iustin Pop
    # hvparams changes
7946 74409b12 Iustin Pop
    if self.op.hvparams:
7947 12649e35 Guido Trotter
      instance.hvparams = self.hv_inst
7948 74409b12 Iustin Pop
      for key, val in self.op.hvparams.iteritems():
7949 74409b12 Iustin Pop
        result.append(("hv/%s" % key, val))
7950 24991749 Iustin Pop
7951 24991749 Iustin Pop
    # beparams changes
7952 338e51e8 Iustin Pop
    if self.op.beparams:
7953 338e51e8 Iustin Pop
      instance.beparams = self.be_inst
7954 338e51e8 Iustin Pop
      for key, val in self.op.beparams.iteritems():
7955 338e51e8 Iustin Pop
        result.append(("be/%s" % key, val))
7956 a8083063 Iustin Pop
7957 a4eae71f Michael Hanselmann
    self.cfg.Update(instance, feedback_fn)
7958 a8083063 Iustin Pop
7959 a8083063 Iustin Pop
    return result
7960 a8083063 Iustin Pop
7961 a8083063 Iustin Pop
7962 a8083063 Iustin Pop
class LUQueryExports(NoHooksLU):
7963 a8083063 Iustin Pop
  """Query the exports list
7964 a8083063 Iustin Pop

7965 a8083063 Iustin Pop
  """
7966 895ecd9c Guido Trotter
  _OP_REQP = ['nodes']
7967 21a15682 Guido Trotter
  REQ_BGL = False
7968 21a15682 Guido Trotter
7969 21a15682 Guido Trotter
  def ExpandNames(self):
7970 21a15682 Guido Trotter
    self.needed_locks = {}
7971 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
7972 21a15682 Guido Trotter
    if not self.op.nodes:
7973 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7974 21a15682 Guido Trotter
    else:
7975 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
7976 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
7977 a8083063 Iustin Pop
7978 a8083063 Iustin Pop
  def CheckPrereq(self):
7979 21a15682 Guido Trotter
    """Check prerequisites.
7980 a8083063 Iustin Pop

7981 a8083063 Iustin Pop
    """
7982 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
7983 a8083063 Iustin Pop
7984 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
7985 a8083063 Iustin Pop
    """Compute the list of all the exported system images.
7986 a8083063 Iustin Pop

7987 e4376078 Iustin Pop
    @rtype: dict
7988 e4376078 Iustin Pop
    @return: a dictionary with the structure node->(export-list)
7989 e4376078 Iustin Pop
        where export-list is a list of the instances exported on
7990 e4376078 Iustin Pop
        that node.
7991 a8083063 Iustin Pop

7992 a8083063 Iustin Pop
    """
7993 b04285f2 Guido Trotter
    rpcresult = self.rpc.call_export_list(self.nodes)
7994 b04285f2 Guido Trotter
    result = {}
7995 b04285f2 Guido Trotter
    for node in rpcresult:
7996 4c4e4e1e Iustin Pop
      if rpcresult[node].fail_msg:
7997 b04285f2 Guido Trotter
        result[node] = False
7998 b04285f2 Guido Trotter
      else:
7999 1b7bfbb7 Iustin Pop
        result[node] = rpcresult[node].payload
8000 b04285f2 Guido Trotter
8001 b04285f2 Guido Trotter
    return result
8002 a8083063 Iustin Pop
8003 a8083063 Iustin Pop
8004 a8083063 Iustin Pop
class LUExportInstance(LogicalUnit):
8005 a8083063 Iustin Pop
  """Export an instance to an image in the cluster.
8006 a8083063 Iustin Pop

8007 a8083063 Iustin Pop
  """
8008 a8083063 Iustin Pop
  HPATH = "instance-export"
8009 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
8010 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
8011 6657590e Guido Trotter
  REQ_BGL = False
8012 6657590e Guido Trotter
8013 17c3f802 Guido Trotter
  def CheckArguments(self):
8014 17c3f802 Guido Trotter
    """Check the arguments.
8015 17c3f802 Guido Trotter

8016 17c3f802 Guido Trotter
    """
8017 17c3f802 Guido Trotter
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
8018 17c3f802 Guido Trotter
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
8019 17c3f802 Guido Trotter
8020 6657590e Guido Trotter
  def ExpandNames(self):
8021 6657590e Guido Trotter
    self._ExpandAndLockInstance()
8022 6657590e Guido Trotter
    # FIXME: lock only instance primary and destination node
8023 6657590e Guido Trotter
    #
8024 6657590e Guido Trotter
    # Sad but true, for now we have do lock all nodes, as we don't know where
8025 6657590e Guido Trotter
    # the previous export might be, and and in this LU we search for it and
8026 6657590e Guido Trotter
    # remove it from its current node. In the future we could fix this by:
8027 6657590e Guido Trotter
    #  - making a tasklet to search (share-lock all), then create the new one,
8028 6657590e Guido Trotter
    #    then one to remove, after
8029 5bbd3f7f Michael Hanselmann
    #  - removing the removal operation altogether
8030 6657590e Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8031 6657590e Guido Trotter
8032 6657590e Guido Trotter
  def DeclareLocks(self, level):
8033 6657590e Guido Trotter
    """Last minute lock declaration."""
8034 6657590e Guido Trotter
    # All nodes are locked anyway, so nothing to do here.
8035 a8083063 Iustin Pop
8036 a8083063 Iustin Pop
  def BuildHooksEnv(self):
8037 a8083063 Iustin Pop
    """Build hooks env.
8038 a8083063 Iustin Pop

8039 a8083063 Iustin Pop
    This will run on the master, primary node and target node.
8040 a8083063 Iustin Pop

8041 a8083063 Iustin Pop
    """
8042 a8083063 Iustin Pop
    env = {
8043 a8083063 Iustin Pop
      "EXPORT_NODE": self.op.target_node,
8044 a8083063 Iustin Pop
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
8045 17c3f802 Guido Trotter
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
8046 a8083063 Iustin Pop
      }
8047 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8048 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
8049 a8083063 Iustin Pop
          self.op.target_node]
8050 a8083063 Iustin Pop
    return env, nl, nl
8051 a8083063 Iustin Pop
8052 a8083063 Iustin Pop
  def CheckPrereq(self):
8053 a8083063 Iustin Pop
    """Check prerequisites.
8054 a8083063 Iustin Pop

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

8057 a8083063 Iustin Pop
    """
8058 6657590e Guido Trotter
    instance_name = self.op.instance_name
8059 a8083063 Iustin Pop
    self.instance = self.cfg.GetInstanceInfo(instance_name)
8060 6657590e Guido Trotter
    assert self.instance is not None, \
8061 6657590e Guido Trotter
          "Cannot retrieve locked instance %s" % self.op.instance_name
8062 43017d26 Iustin Pop
    _CheckNodeOnline(self, self.instance.primary_node)
8063 a8083063 Iustin Pop
8064 6657590e Guido Trotter
    self.dst_node = self.cfg.GetNodeInfo(
8065 6657590e Guido Trotter
      self.cfg.ExpandNodeName(self.op.target_node))
8066 a8083063 Iustin Pop
8067 268b8e42 Iustin Pop
    if self.dst_node is None:
8068 268b8e42 Iustin Pop
      # This is wrong node name, not a non-locked node
8069 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node,
8070 5c983ee5 Iustin Pop
                                 errors.ECODE_NOENT)
8071 aeb83a2b Iustin Pop
    _CheckNodeOnline(self, self.dst_node.name)
8072 733a2b6a Iustin Pop
    _CheckNodeNotDrained(self, self.dst_node.name)
8073 a8083063 Iustin Pop
8074 b6023d6c Manuel Franceschini
    # instance disk type verification
8075 b6023d6c Manuel Franceschini
    for disk in self.instance.disks:
8076 b6023d6c Manuel Franceschini
      if disk.dev_type == constants.LD_FILE:
8077 b6023d6c Manuel Franceschini
        raise errors.OpPrereqError("Export not supported for instances with"
8078 5c983ee5 Iustin Pop
                                   " file-based disks", errors.ECODE_INVAL)
8079 b6023d6c Manuel Franceschini
8080 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
8081 a8083063 Iustin Pop
    """Export an instance to an image in the cluster.
8082 a8083063 Iustin Pop

8083 a8083063 Iustin Pop
    """
8084 a8083063 Iustin Pop
    instance = self.instance
8085 a8083063 Iustin Pop
    dst_node = self.dst_node
8086 a8083063 Iustin Pop
    src_node = instance.primary_node
8087 37972df0 Michael Hanselmann
8088 a8083063 Iustin Pop
    if self.op.shutdown:
8089 fb300fb7 Guido Trotter
      # shutdown the instance, but not the disks
8090 37972df0 Michael Hanselmann
      feedback_fn("Shutting down instance %s" % instance.name)
8091 17c3f802 Guido Trotter
      result = self.rpc.call_instance_shutdown(src_node, instance,
8092 17c3f802 Guido Trotter
                                               self.shutdown_timeout)
8093 4c4e4e1e Iustin Pop
      result.Raise("Could not shutdown instance %s on"
8094 4c4e4e1e Iustin Pop
                   " node %s" % (instance.name, src_node))
8095 a8083063 Iustin Pop
8096 a8083063 Iustin Pop
    vgname = self.cfg.GetVGName()
8097 a8083063 Iustin Pop
8098 a8083063 Iustin Pop
    snap_disks = []
8099 a8083063 Iustin Pop
8100 998c712c Iustin Pop
    # set the disks ID correctly since call_instance_start needs the
8101 998c712c Iustin Pop
    # correct drbd minor to create the symlinks
8102 998c712c Iustin Pop
    for disk in instance.disks:
8103 998c712c Iustin Pop
      self.cfg.SetDiskID(disk, src_node)
8104 998c712c Iustin Pop
8105 3e53a60b Michael Hanselmann
    activate_disks = (not instance.admin_up)
8106 3e53a60b Michael Hanselmann
8107 3e53a60b Michael Hanselmann
    if activate_disks:
8108 3e53a60b Michael Hanselmann
      # Activate the instance disks if we'exporting a stopped instance
8109 3e53a60b Michael Hanselmann
      feedback_fn("Activating disks for %s" % instance.name)
8110 3e53a60b Michael Hanselmann
      _StartInstanceDisks(self, instance, None)
8111 3e53a60b Michael Hanselmann
8112 a8083063 Iustin Pop
    try:
8113 3e53a60b Michael Hanselmann
      # per-disk results
8114 3e53a60b Michael Hanselmann
      dresults = []
8115 3e53a60b Michael Hanselmann
      try:
8116 3e53a60b Michael Hanselmann
        for idx, disk in enumerate(instance.disks):
8117 3e53a60b Michael Hanselmann
          feedback_fn("Creating a snapshot of disk/%s on node %s" %
8118 3e53a60b Michael Hanselmann
                      (idx, src_node))
8119 3e53a60b Michael Hanselmann
8120 3e53a60b Michael Hanselmann
          # result.payload will be a snapshot of an lvm leaf of the one we
8121 3e53a60b Michael Hanselmann
          # passed
8122 3e53a60b Michael Hanselmann
          result = self.rpc.call_blockdev_snapshot(src_node, disk)
8123 3e53a60b Michael Hanselmann
          msg = result.fail_msg
8124 3e53a60b Michael Hanselmann
          if msg:
8125 3e53a60b Michael Hanselmann
            self.LogWarning("Could not snapshot disk/%s on node %s: %s",
8126 3e53a60b Michael Hanselmann
                            idx, src_node, msg)
8127 3e53a60b Michael Hanselmann
            snap_disks.append(False)
8128 3e53a60b Michael Hanselmann
          else:
8129 3e53a60b Michael Hanselmann
            disk_id = (vgname, result.payload)
8130 3e53a60b Michael Hanselmann
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
8131 3e53a60b Michael Hanselmann
                                   logical_id=disk_id, physical_id=disk_id,
8132 3e53a60b Michael Hanselmann
                                   iv_name=disk.iv_name)
8133 3e53a60b Michael Hanselmann
            snap_disks.append(new_dev)
8134 37972df0 Michael Hanselmann
8135 3e53a60b Michael Hanselmann
      finally:
8136 3e53a60b Michael Hanselmann
        if self.op.shutdown and instance.admin_up:
8137 3e53a60b Michael Hanselmann
          feedback_fn("Starting instance %s" % instance.name)
8138 3e53a60b Michael Hanselmann
          result = self.rpc.call_instance_start(src_node, instance, None, None)
8139 3e53a60b Michael Hanselmann
          msg = result.fail_msg
8140 3e53a60b Michael Hanselmann
          if msg:
8141 3e53a60b Michael Hanselmann
            _ShutdownInstanceDisks(self, instance)
8142 3e53a60b Michael Hanselmann
            raise errors.OpExecError("Could not start instance: %s" % msg)
8143 3e53a60b Michael Hanselmann
8144 3e53a60b Michael Hanselmann
      # TODO: check for size
8145 3e53a60b Michael Hanselmann
8146 3e53a60b Michael Hanselmann
      cluster_name = self.cfg.GetClusterName()
8147 3e53a60b Michael Hanselmann
      for idx, dev in enumerate(snap_disks):
8148 3e53a60b Michael Hanselmann
        feedback_fn("Exporting snapshot %s from %s to %s" %
8149 3e53a60b Michael Hanselmann
                    (idx, src_node, dst_node.name))
8150 3e53a60b Michael Hanselmann
        if dev:
8151 3e53a60b Michael Hanselmann
          result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
8152 3e53a60b Michael Hanselmann
                                                 instance, cluster_name, idx)
8153 3e53a60b Michael Hanselmann
          msg = result.fail_msg
8154 3e53a60b Michael Hanselmann
          if msg:
8155 3e53a60b Michael Hanselmann
            self.LogWarning("Could not export disk/%s from node %s to"
8156 3e53a60b Michael Hanselmann
                            " node %s: %s", idx, src_node, dst_node.name, msg)
8157 3e53a60b Michael Hanselmann
            dresults.append(False)
8158 3e53a60b Michael Hanselmann
          else:
8159 3e53a60b Michael Hanselmann
            dresults.append(True)
8160 3e53a60b Michael Hanselmann
          msg = self.rpc.call_blockdev_remove(src_node, dev).fail_msg
8161 3e53a60b Michael Hanselmann
          if msg:
8162 3e53a60b Michael Hanselmann
            self.LogWarning("Could not remove snapshot for disk/%d from node"
8163 3e53a60b Michael Hanselmann
                            " %s: %s", idx, src_node, msg)
8164 19d7f90a Guido Trotter
        else:
8165 084f05a5 Iustin Pop
          dresults.append(False)
8166 a8083063 Iustin Pop
8167 3e53a60b Michael Hanselmann
      feedback_fn("Finalizing export on %s" % dst_node.name)
8168 3e53a60b Michael Hanselmann
      result = self.rpc.call_finalize_export(dst_node.name, instance,
8169 3e53a60b Michael Hanselmann
                                             snap_disks)
8170 3e53a60b Michael Hanselmann
      fin_resu = True
8171 3e53a60b Michael Hanselmann
      msg = result.fail_msg
8172 3e53a60b Michael Hanselmann
      if msg:
8173 3e53a60b Michael Hanselmann
        self.LogWarning("Could not finalize export for instance %s"
8174 3e53a60b Michael Hanselmann
                        " on node %s: %s", instance.name, dst_node.name, msg)
8175 3e53a60b Michael Hanselmann
        fin_resu = False
8176 3e53a60b Michael Hanselmann
8177 3e53a60b Michael Hanselmann
    finally:
8178 3e53a60b Michael Hanselmann
      if activate_disks:
8179 3e53a60b Michael Hanselmann
        feedback_fn("Deactivating disks for %s" % instance.name)
8180 3e53a60b Michael Hanselmann
        _ShutdownInstanceDisks(self, instance)
8181 a8083063 Iustin Pop
8182 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
8183 a8083063 Iustin Pop
    nodelist.remove(dst_node.name)
8184 a8083063 Iustin Pop
8185 a8083063 Iustin Pop
    # on one-node clusters nodelist will be empty after the removal
8186 a8083063 Iustin Pop
    # if we proceed the backup would be removed because OpQueryExports
8187 a8083063 Iustin Pop
    # substitutes an empty list with the full cluster node list.
8188 35fbcd11 Iustin Pop
    iname = instance.name
8189 a8083063 Iustin Pop
    if nodelist:
8190 37972df0 Michael Hanselmann
      feedback_fn("Removing old exports for instance %s" % iname)
8191 72737a7f Iustin Pop
      exportlist = self.rpc.call_export_list(nodelist)
8192 a8083063 Iustin Pop
      for node in exportlist:
8193 4c4e4e1e Iustin Pop
        if exportlist[node].fail_msg:
8194 781de953 Iustin Pop
          continue
8195 35fbcd11 Iustin Pop
        if iname in exportlist[node].payload:
8196 4c4e4e1e Iustin Pop
          msg = self.rpc.call_export_remove(node, iname).fail_msg
8197 35fbcd11 Iustin Pop
          if msg:
8198 19d7f90a Guido Trotter
            self.LogWarning("Could not remove older export for instance %s"
8199 35fbcd11 Iustin Pop
                            " on node %s: %s", iname, node, msg)
8200 084f05a5 Iustin Pop
    return fin_resu, dresults
8201 5c947f38 Iustin Pop
8202 5c947f38 Iustin Pop
8203 9ac99fda Guido Trotter
class LURemoveExport(NoHooksLU):
8204 9ac99fda Guido Trotter
  """Remove exports related to the named instance.
8205 9ac99fda Guido Trotter

8206 9ac99fda Guido Trotter
  """
8207 9ac99fda Guido Trotter
  _OP_REQP = ["instance_name"]
8208 3656b3af Guido Trotter
  REQ_BGL = False
8209 3656b3af Guido Trotter
8210 3656b3af Guido Trotter
  def ExpandNames(self):
8211 3656b3af Guido Trotter
    self.needed_locks = {}
8212 3656b3af Guido Trotter
    # We need all nodes to be locked in order for RemoveExport to work, but we
8213 3656b3af Guido Trotter
    # don't need to lock the instance itself, as nothing will happen to it (and
8214 3656b3af Guido Trotter
    # we can remove exports also for a removed instance)
8215 3656b3af Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8216 9ac99fda Guido Trotter
8217 9ac99fda Guido Trotter
  def CheckPrereq(self):
8218 9ac99fda Guido Trotter
    """Check prerequisites.
8219 9ac99fda Guido Trotter
    """
8220 9ac99fda Guido Trotter
    pass
8221 9ac99fda Guido Trotter
8222 9ac99fda Guido Trotter
  def Exec(self, feedback_fn):
8223 9ac99fda Guido Trotter
    """Remove any export.
8224 9ac99fda Guido Trotter

8225 9ac99fda Guido Trotter
    """
8226 9ac99fda Guido Trotter
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
8227 9ac99fda Guido Trotter
    # If the instance was not found we'll try with the name that was passed in.
8228 9ac99fda Guido Trotter
    # This will only work if it was an FQDN, though.
8229 9ac99fda Guido Trotter
    fqdn_warn = False
8230 9ac99fda Guido Trotter
    if not instance_name:
8231 9ac99fda Guido Trotter
      fqdn_warn = True
8232 9ac99fda Guido Trotter
      instance_name = self.op.instance_name
8233 9ac99fda Guido Trotter
8234 1b7bfbb7 Iustin Pop
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
8235 1b7bfbb7 Iustin Pop
    exportlist = self.rpc.call_export_list(locked_nodes)
8236 9ac99fda Guido Trotter
    found = False
8237 9ac99fda Guido Trotter
    for node in exportlist:
8238 4c4e4e1e Iustin Pop
      msg = exportlist[node].fail_msg
8239 1b7bfbb7 Iustin Pop
      if msg:
8240 1b7bfbb7 Iustin Pop
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
8241 781de953 Iustin Pop
        continue
8242 1b7bfbb7 Iustin Pop
      if instance_name in exportlist[node].payload:
8243 9ac99fda Guido Trotter
        found = True
8244 781de953 Iustin Pop
        result = self.rpc.call_export_remove(node, instance_name)
8245 4c4e4e1e Iustin Pop
        msg = result.fail_msg
8246 35fbcd11 Iustin Pop
        if msg:
8247 9a4f63d1 Iustin Pop
          logging.error("Could not remove export for instance %s"
8248 35fbcd11 Iustin Pop
                        " on node %s: %s", instance_name, node, msg)
8249 9ac99fda Guido Trotter
8250 9ac99fda Guido Trotter
    if fqdn_warn and not found:
8251 9ac99fda Guido Trotter
      feedback_fn("Export not found. If trying to remove an export belonging"
8252 9ac99fda Guido Trotter
                  " to a deleted instance please use its Fully Qualified"
8253 9ac99fda Guido Trotter
                  " Domain Name.")
8254 9ac99fda Guido Trotter
8255 9ac99fda Guido Trotter
8256 fe267188 Iustin Pop
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
8257 5c947f38 Iustin Pop
  """Generic tags LU.
8258 5c947f38 Iustin Pop

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

8261 5c947f38 Iustin Pop
  """
8262 5c947f38 Iustin Pop
8263 8646adce Guido Trotter
  def ExpandNames(self):
8264 8646adce Guido Trotter
    self.needed_locks = {}
8265 8646adce Guido Trotter
    if self.op.kind == constants.TAG_NODE:
8266 5c947f38 Iustin Pop
      name = self.cfg.ExpandNodeName(self.op.name)
8267 5c947f38 Iustin Pop
      if name is None:
8268 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid node name (%s)" %
8269 5c983ee5 Iustin Pop
                                   (self.op.name,), errors.ECODE_NOENT)
8270 5c947f38 Iustin Pop
      self.op.name = name
8271 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = name
8272 5c947f38 Iustin Pop
    elif self.op.kind == constants.TAG_INSTANCE:
8273 8f684e16 Iustin Pop
      name = self.cfg.ExpandInstanceName(self.op.name)
8274 5c947f38 Iustin Pop
      if name is None:
8275 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid instance name (%s)" %
8276 5c983ee5 Iustin Pop
                                   (self.op.name,), errors.ECODE_NOENT)
8277 5c947f38 Iustin Pop
      self.op.name = name
8278 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = name
8279 8646adce Guido Trotter
8280 8646adce Guido Trotter
  def CheckPrereq(self):
8281 8646adce Guido Trotter
    """Check prerequisites.
8282 8646adce Guido Trotter

8283 8646adce Guido Trotter
    """
8284 8646adce Guido Trotter
    if self.op.kind == constants.TAG_CLUSTER:
8285 8646adce Guido Trotter
      self.target = self.cfg.GetClusterInfo()
8286 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_NODE:
8287 8646adce Guido Trotter
      self.target = self.cfg.GetNodeInfo(self.op.name)
8288 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_INSTANCE:
8289 8646adce Guido Trotter
      self.target = self.cfg.GetInstanceInfo(self.op.name)
8290 5c947f38 Iustin Pop
    else:
8291 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
8292 5c983ee5 Iustin Pop
                                 str(self.op.kind), errors.ECODE_INVAL)
8293 5c947f38 Iustin Pop
8294 5c947f38 Iustin Pop
8295 5c947f38 Iustin Pop
class LUGetTags(TagsLU):
8296 5c947f38 Iustin Pop
  """Returns the tags of a given object.
8297 5c947f38 Iustin Pop

8298 5c947f38 Iustin Pop
  """
8299 5c947f38 Iustin Pop
  _OP_REQP = ["kind", "name"]
8300 8646adce Guido Trotter
  REQ_BGL = False
8301 5c947f38 Iustin Pop
8302 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
8303 5c947f38 Iustin Pop
    """Returns the tag list.
8304 5c947f38 Iustin Pop

8305 5c947f38 Iustin Pop
    """
8306 5d414478 Oleksiy Mishchenko
    return list(self.target.GetTags())
8307 5c947f38 Iustin Pop
8308 5c947f38 Iustin Pop
8309 73415719 Iustin Pop
class LUSearchTags(NoHooksLU):
8310 73415719 Iustin Pop
  """Searches the tags for a given pattern.
8311 73415719 Iustin Pop

8312 73415719 Iustin Pop
  """
8313 73415719 Iustin Pop
  _OP_REQP = ["pattern"]
8314 8646adce Guido Trotter
  REQ_BGL = False
8315 8646adce Guido Trotter
8316 8646adce Guido Trotter
  def ExpandNames(self):
8317 8646adce Guido Trotter
    self.needed_locks = {}
8318 73415719 Iustin Pop
8319 73415719 Iustin Pop
  def CheckPrereq(self):
8320 73415719 Iustin Pop
    """Check prerequisites.
8321 73415719 Iustin Pop

8322 73415719 Iustin Pop
    This checks the pattern passed for validity by compiling it.
8323 73415719 Iustin Pop

8324 73415719 Iustin Pop
    """
8325 73415719 Iustin Pop
    try:
8326 73415719 Iustin Pop
      self.re = re.compile(self.op.pattern)
8327 73415719 Iustin Pop
    except re.error, err:
8328 73415719 Iustin Pop
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
8329 5c983ee5 Iustin Pop
                                 (self.op.pattern, err), errors.ECODE_INVAL)
8330 73415719 Iustin Pop
8331 73415719 Iustin Pop
  def Exec(self, feedback_fn):
8332 73415719 Iustin Pop
    """Returns the tag list.
8333 73415719 Iustin Pop

8334 73415719 Iustin Pop
    """
8335 73415719 Iustin Pop
    cfg = self.cfg
8336 73415719 Iustin Pop
    tgts = [("/cluster", cfg.GetClusterInfo())]
8337 8646adce Guido Trotter
    ilist = cfg.GetAllInstancesInfo().values()
8338 73415719 Iustin Pop
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
8339 8646adce Guido Trotter
    nlist = cfg.GetAllNodesInfo().values()
8340 73415719 Iustin Pop
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
8341 73415719 Iustin Pop
    results = []
8342 73415719 Iustin Pop
    for path, target in tgts:
8343 73415719 Iustin Pop
      for tag in target.GetTags():
8344 73415719 Iustin Pop
        if self.re.search(tag):
8345 73415719 Iustin Pop
          results.append((path, tag))
8346 73415719 Iustin Pop
    return results
8347 73415719 Iustin Pop
8348 73415719 Iustin Pop
8349 f27302fa Iustin Pop
class LUAddTags(TagsLU):
8350 5c947f38 Iustin Pop
  """Sets a tag on a given object.
8351 5c947f38 Iustin Pop

8352 5c947f38 Iustin Pop
  """
8353 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
8354 8646adce Guido Trotter
  REQ_BGL = False
8355 5c947f38 Iustin Pop
8356 5c947f38 Iustin Pop
  def CheckPrereq(self):
8357 5c947f38 Iustin Pop
    """Check prerequisites.
8358 5c947f38 Iustin Pop

8359 5c947f38 Iustin Pop
    This checks the type and length of the tag name and value.
8360 5c947f38 Iustin Pop

8361 5c947f38 Iustin Pop
    """
8362 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
8363 f27302fa Iustin Pop
    for tag in self.op.tags:
8364 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
8365 5c947f38 Iustin Pop
8366 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
8367 5c947f38 Iustin Pop
    """Sets the tag.
8368 5c947f38 Iustin Pop

8369 5c947f38 Iustin Pop
    """
8370 5c947f38 Iustin Pop
    try:
8371 f27302fa Iustin Pop
      for tag in self.op.tags:
8372 f27302fa Iustin Pop
        self.target.AddTag(tag)
8373 5c947f38 Iustin Pop
    except errors.TagError, err:
8374 3ecf6786 Iustin Pop
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
8375 159d4ec6 Iustin Pop
    self.cfg.Update(self.target, feedback_fn)
8376 5c947f38 Iustin Pop
8377 5c947f38 Iustin Pop
8378 f27302fa Iustin Pop
class LUDelTags(TagsLU):
8379 f27302fa Iustin Pop
  """Delete a list of tags from a given object.
8380 5c947f38 Iustin Pop

8381 5c947f38 Iustin Pop
  """
8382 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
8383 8646adce Guido Trotter
  REQ_BGL = False
8384 5c947f38 Iustin Pop
8385 5c947f38 Iustin Pop
  def CheckPrereq(self):
8386 5c947f38 Iustin Pop
    """Check prerequisites.
8387 5c947f38 Iustin Pop

8388 5c947f38 Iustin Pop
    This checks that we have the given tag.
8389 5c947f38 Iustin Pop

8390 5c947f38 Iustin Pop
    """
8391 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
8392 f27302fa Iustin Pop
    for tag in self.op.tags:
8393 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
8394 f27302fa Iustin Pop
    del_tags = frozenset(self.op.tags)
8395 f27302fa Iustin Pop
    cur_tags = self.target.GetTags()
8396 f27302fa Iustin Pop
    if not del_tags <= cur_tags:
8397 f27302fa Iustin Pop
      diff_tags = del_tags - cur_tags
8398 f27302fa Iustin Pop
      diff_names = ["'%s'" % tag for tag in diff_tags]
8399 f27302fa Iustin Pop
      diff_names.sort()
8400 f27302fa Iustin Pop
      raise errors.OpPrereqError("Tag(s) %s not found" %
8401 5c983ee5 Iustin Pop
                                 (",".join(diff_names)), errors.ECODE_NOENT)
8402 5c947f38 Iustin Pop
8403 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
8404 5c947f38 Iustin Pop
    """Remove the tag from the object.
8405 5c947f38 Iustin Pop

8406 5c947f38 Iustin Pop
    """
8407 f27302fa Iustin Pop
    for tag in self.op.tags:
8408 f27302fa Iustin Pop
      self.target.RemoveTag(tag)
8409 159d4ec6 Iustin Pop
    self.cfg.Update(self.target, feedback_fn)
8410 06009e27 Iustin Pop
8411 0eed6e61 Guido Trotter
8412 06009e27 Iustin Pop
class LUTestDelay(NoHooksLU):
8413 06009e27 Iustin Pop
  """Sleep for a specified amount of time.
8414 06009e27 Iustin Pop

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

8418 06009e27 Iustin Pop
  """
8419 06009e27 Iustin Pop
  _OP_REQP = ["duration", "on_master", "on_nodes"]
8420 fbe9022f Guido Trotter
  REQ_BGL = False
8421 06009e27 Iustin Pop
8422 fbe9022f Guido Trotter
  def ExpandNames(self):
8423 fbe9022f Guido Trotter
    """Expand names and set required locks.
8424 06009e27 Iustin Pop

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

8427 06009e27 Iustin Pop
    """
8428 fbe9022f Guido Trotter
    self.needed_locks = {}
8429 06009e27 Iustin Pop
    if self.op.on_nodes:
8430 fbe9022f Guido Trotter
      # _GetWantedNodes can be used here, but is not always appropriate to use
8431 fbe9022f Guido Trotter
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
8432 fbe9022f Guido Trotter
      # more information.
8433 06009e27 Iustin Pop
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
8434 fbe9022f Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
8435 fbe9022f Guido Trotter
8436 fbe9022f Guido Trotter
  def CheckPrereq(self):
8437 fbe9022f Guido Trotter
    """Check prerequisites.
8438 fbe9022f Guido Trotter

8439 fbe9022f Guido Trotter
    """
8440 06009e27 Iustin Pop
8441 06009e27 Iustin Pop
  def Exec(self, feedback_fn):
8442 06009e27 Iustin Pop
    """Do the actual sleep.
8443 06009e27 Iustin Pop

8444 06009e27 Iustin Pop
    """
8445 06009e27 Iustin Pop
    if self.op.on_master:
8446 06009e27 Iustin Pop
      if not utils.TestDelay(self.op.duration):
8447 06009e27 Iustin Pop
        raise errors.OpExecError("Error during master delay test")
8448 06009e27 Iustin Pop
    if self.op.on_nodes:
8449 72737a7f Iustin Pop
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
8450 06009e27 Iustin Pop
      for node, node_result in result.items():
8451 4c4e4e1e Iustin Pop
        node_result.Raise("Failure during rpc call to node %s" % node)
8452 d61df03e Iustin Pop
8453 d61df03e Iustin Pop
8454 d1c2dd75 Iustin Pop
class IAllocator(object):
8455 d1c2dd75 Iustin Pop
  """IAllocator framework.
8456 d61df03e Iustin Pop

8457 d1c2dd75 Iustin Pop
  An IAllocator instance has three sets of attributes:
8458 d6a02168 Michael Hanselmann
    - cfg that is needed to query the cluster
8459 d1c2dd75 Iustin Pop
    - input data (all members of the _KEYS class attribute are required)
8460 d1c2dd75 Iustin Pop
    - four buffer attributes (in|out_data|text), that represent the
8461 d1c2dd75 Iustin Pop
      input (to the external script) in text and data structure format,
8462 d1c2dd75 Iustin Pop
      and the output from it, again in two formats
8463 d1c2dd75 Iustin Pop
    - the result variables from the script (success, info, nodes) for
8464 d1c2dd75 Iustin Pop
      easy usage
8465 d61df03e Iustin Pop

8466 d61df03e Iustin Pop
  """
8467 7260cfbe Iustin Pop
  # pylint: disable-msg=R0902
8468 7260cfbe Iustin Pop
  # lots of instance attributes
8469 29859cb7 Iustin Pop
  _ALLO_KEYS = [
8470 d1c2dd75 Iustin Pop
    "mem_size", "disks", "disk_template",
8471 8cc7e742 Guido Trotter
    "os", "tags", "nics", "vcpus", "hypervisor",
8472 d1c2dd75 Iustin Pop
    ]
8473 29859cb7 Iustin Pop
  _RELO_KEYS = [
8474 29859cb7 Iustin Pop
    "relocate_from",
8475 29859cb7 Iustin Pop
    ]
8476 d1c2dd75 Iustin Pop
8477 923ddac0 Michael Hanselmann
  def __init__(self, cfg, rpc, mode, name, **kwargs):
8478 923ddac0 Michael Hanselmann
    self.cfg = cfg
8479 923ddac0 Michael Hanselmann
    self.rpc = rpc
8480 d1c2dd75 Iustin Pop
    # init buffer variables
8481 d1c2dd75 Iustin Pop
    self.in_text = self.out_text = self.in_data = self.out_data = None
8482 d1c2dd75 Iustin Pop
    # init all input fields so that pylint is happy
8483 29859cb7 Iustin Pop
    self.mode = mode
8484 29859cb7 Iustin Pop
    self.name = name
8485 d1c2dd75 Iustin Pop
    self.mem_size = self.disks = self.disk_template = None
8486 d1c2dd75 Iustin Pop
    self.os = self.tags = self.nics = self.vcpus = None
8487 a0add446 Iustin Pop
    self.hypervisor = None
8488 29859cb7 Iustin Pop
    self.relocate_from = None
8489 27579978 Iustin Pop
    # computed fields
8490 27579978 Iustin Pop
    self.required_nodes = None
8491 d1c2dd75 Iustin Pop
    # init result fields
8492 d1c2dd75 Iustin Pop
    self.success = self.info = self.nodes = None
8493 29859cb7 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8494 29859cb7 Iustin Pop
      keyset = self._ALLO_KEYS
8495 29859cb7 Iustin Pop
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8496 29859cb7 Iustin Pop
      keyset = self._RELO_KEYS
8497 29859cb7 Iustin Pop
    else:
8498 29859cb7 Iustin Pop
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
8499 29859cb7 Iustin Pop
                                   " IAllocator" % self.mode)
8500 d1c2dd75 Iustin Pop
    for key in kwargs:
8501 29859cb7 Iustin Pop
      if key not in keyset:
8502 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
8503 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
8504 d1c2dd75 Iustin Pop
      setattr(self, key, kwargs[key])
8505 29859cb7 Iustin Pop
    for key in keyset:
8506 d1c2dd75 Iustin Pop
      if key not in kwargs:
8507 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Missing input parameter '%s' to"
8508 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
8509 d1c2dd75 Iustin Pop
    self._BuildInputData()
8510 d1c2dd75 Iustin Pop
8511 d1c2dd75 Iustin Pop
  def _ComputeClusterData(self):
8512 d1c2dd75 Iustin Pop
    """Compute the generic allocator input data.
8513 d1c2dd75 Iustin Pop

8514 d1c2dd75 Iustin Pop
    This is the data that is independent of the actual operation.
8515 d1c2dd75 Iustin Pop

8516 d1c2dd75 Iustin Pop
    """
8517 923ddac0 Michael Hanselmann
    cfg = self.cfg
8518 e69d05fd Iustin Pop
    cluster_info = cfg.GetClusterInfo()
8519 d1c2dd75 Iustin Pop
    # cluster data
8520 d1c2dd75 Iustin Pop
    data = {
8521 77031881 Iustin Pop
      "version": constants.IALLOCATOR_VERSION,
8522 72737a7f Iustin Pop
      "cluster_name": cfg.GetClusterName(),
8523 e69d05fd Iustin Pop
      "cluster_tags": list(cluster_info.GetTags()),
8524 1325da74 Iustin Pop
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
8525 d1c2dd75 Iustin Pop
      # we don't have job IDs
8526 d61df03e Iustin Pop
      }
8527 b57e9819 Guido Trotter
    iinfo = cfg.GetAllInstancesInfo().values()
8528 b57e9819 Guido Trotter
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
8529 6286519f Iustin Pop
8530 d1c2dd75 Iustin Pop
    # node data
8531 d1c2dd75 Iustin Pop
    node_results = {}
8532 d1c2dd75 Iustin Pop
    node_list = cfg.GetNodeList()
8533 8cc7e742 Guido Trotter
8534 8cc7e742 Guido Trotter
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8535 a0add446 Iustin Pop
      hypervisor_name = self.hypervisor
8536 8cc7e742 Guido Trotter
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
8537 a0add446 Iustin Pop
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
8538 8cc7e742 Guido Trotter
8539 923ddac0 Michael Hanselmann
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
8540 923ddac0 Michael Hanselmann
                                        hypervisor_name)
8541 923ddac0 Michael Hanselmann
    node_iinfo = \
8542 923ddac0 Michael Hanselmann
      self.rpc.call_all_instances_info(node_list,
8543 923ddac0 Michael Hanselmann
                                       cluster_info.enabled_hypervisors)
8544 1325da74 Iustin Pop
    for nname, nresult in node_data.items():
8545 1325da74 Iustin Pop
      # first fill in static (config-based) values
8546 d1c2dd75 Iustin Pop
      ninfo = cfg.GetNodeInfo(nname)
8547 d1c2dd75 Iustin Pop
      pnr = {
8548 d1c2dd75 Iustin Pop
        "tags": list(ninfo.GetTags()),
8549 d1c2dd75 Iustin Pop
        "primary_ip": ninfo.primary_ip,
8550 d1c2dd75 Iustin Pop
        "secondary_ip": ninfo.secondary_ip,
8551 fc0fe88c Iustin Pop
        "offline": ninfo.offline,
8552 0b2454b9 Iustin Pop
        "drained": ninfo.drained,
8553 1325da74 Iustin Pop
        "master_candidate": ninfo.master_candidate,
8554 d1c2dd75 Iustin Pop
        }
8555 1325da74 Iustin Pop
8556 0d853843 Iustin Pop
      if not (ninfo.offline or ninfo.drained):
8557 4c4e4e1e Iustin Pop
        nresult.Raise("Can't get data for node %s" % nname)
8558 4c4e4e1e Iustin Pop
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
8559 4c4e4e1e Iustin Pop
                                nname)
8560 070e998b Iustin Pop
        remote_info = nresult.payload
8561 b142ef15 Iustin Pop
8562 1325da74 Iustin Pop
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
8563 1325da74 Iustin Pop
                     'vg_size', 'vg_free', 'cpu_total']:
8564 1325da74 Iustin Pop
          if attr not in remote_info:
8565 1325da74 Iustin Pop
            raise errors.OpExecError("Node '%s' didn't return attribute"
8566 1325da74 Iustin Pop
                                     " '%s'" % (nname, attr))
8567 070e998b Iustin Pop
          if not isinstance(remote_info[attr], int):
8568 1325da74 Iustin Pop
            raise errors.OpExecError("Node '%s' returned invalid value"
8569 070e998b Iustin Pop
                                     " for '%s': %s" %
8570 070e998b Iustin Pop
                                     (nname, attr, remote_info[attr]))
8571 1325da74 Iustin Pop
        # compute memory used by primary instances
8572 1325da74 Iustin Pop
        i_p_mem = i_p_up_mem = 0
8573 1325da74 Iustin Pop
        for iinfo, beinfo in i_list:
8574 1325da74 Iustin Pop
          if iinfo.primary_node == nname:
8575 1325da74 Iustin Pop
            i_p_mem += beinfo[constants.BE_MEMORY]
8576 2fa74ef4 Iustin Pop
            if iinfo.name not in node_iinfo[nname].payload:
8577 1325da74 Iustin Pop
              i_used_mem = 0
8578 1325da74 Iustin Pop
            else:
8579 2fa74ef4 Iustin Pop
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
8580 1325da74 Iustin Pop
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
8581 1325da74 Iustin Pop
            remote_info['memory_free'] -= max(0, i_mem_diff)
8582 1325da74 Iustin Pop
8583 1325da74 Iustin Pop
            if iinfo.admin_up:
8584 1325da74 Iustin Pop
              i_p_up_mem += beinfo[constants.BE_MEMORY]
8585 1325da74 Iustin Pop
8586 1325da74 Iustin Pop
        # compute memory used by instances
8587 1325da74 Iustin Pop
        pnr_dyn = {
8588 1325da74 Iustin Pop
          "total_memory": remote_info['memory_total'],
8589 1325da74 Iustin Pop
          "reserved_memory": remote_info['memory_dom0'],
8590 1325da74 Iustin Pop
          "free_memory": remote_info['memory_free'],
8591 1325da74 Iustin Pop
          "total_disk": remote_info['vg_size'],
8592 1325da74 Iustin Pop
          "free_disk": remote_info['vg_free'],
8593 1325da74 Iustin Pop
          "total_cpus": remote_info['cpu_total'],
8594 1325da74 Iustin Pop
          "i_pri_memory": i_p_mem,
8595 1325da74 Iustin Pop
          "i_pri_up_memory": i_p_up_mem,
8596 1325da74 Iustin Pop
          }
8597 1325da74 Iustin Pop
        pnr.update(pnr_dyn)
8598 1325da74 Iustin Pop
8599 d1c2dd75 Iustin Pop
      node_results[nname] = pnr
8600 d1c2dd75 Iustin Pop
    data["nodes"] = node_results
8601 d1c2dd75 Iustin Pop
8602 d1c2dd75 Iustin Pop
    # instance data
8603 d1c2dd75 Iustin Pop
    instance_data = {}
8604 338e51e8 Iustin Pop
    for iinfo, beinfo in i_list:
8605 a9fe7e8f Guido Trotter
      nic_data = []
8606 a9fe7e8f Guido Trotter
      for nic in iinfo.nics:
8607 a9fe7e8f Guido Trotter
        filled_params = objects.FillDict(
8608 a9fe7e8f Guido Trotter
            cluster_info.nicparams[constants.PP_DEFAULT],
8609 a9fe7e8f Guido Trotter
            nic.nicparams)
8610 a9fe7e8f Guido Trotter
        nic_dict = {"mac": nic.mac,
8611 a9fe7e8f Guido Trotter
                    "ip": nic.ip,
8612 a9fe7e8f Guido Trotter
                    "mode": filled_params[constants.NIC_MODE],
8613 a9fe7e8f Guido Trotter
                    "link": filled_params[constants.NIC_LINK],
8614 a9fe7e8f Guido Trotter
                   }
8615 a9fe7e8f Guido Trotter
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
8616 a9fe7e8f Guido Trotter
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
8617 a9fe7e8f Guido Trotter
        nic_data.append(nic_dict)
8618 d1c2dd75 Iustin Pop
      pir = {
8619 d1c2dd75 Iustin Pop
        "tags": list(iinfo.GetTags()),
8620 1325da74 Iustin Pop
        "admin_up": iinfo.admin_up,
8621 338e51e8 Iustin Pop
        "vcpus": beinfo[constants.BE_VCPUS],
8622 338e51e8 Iustin Pop
        "memory": beinfo[constants.BE_MEMORY],
8623 d1c2dd75 Iustin Pop
        "os": iinfo.os,
8624 1325da74 Iustin Pop
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
8625 d1c2dd75 Iustin Pop
        "nics": nic_data,
8626 1325da74 Iustin Pop
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
8627 d1c2dd75 Iustin Pop
        "disk_template": iinfo.disk_template,
8628 e69d05fd Iustin Pop
        "hypervisor": iinfo.hypervisor,
8629 d1c2dd75 Iustin Pop
        }
8630 88ae4f85 Iustin Pop
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
8631 88ae4f85 Iustin Pop
                                                 pir["disks"])
8632 768f0a80 Iustin Pop
      instance_data[iinfo.name] = pir
8633 d61df03e Iustin Pop
8634 d1c2dd75 Iustin Pop
    data["instances"] = instance_data
8635 d61df03e Iustin Pop
8636 d1c2dd75 Iustin Pop
    self.in_data = data
8637 d61df03e Iustin Pop
8638 d1c2dd75 Iustin Pop
  def _AddNewInstance(self):
8639 d1c2dd75 Iustin Pop
    """Add new instance data to allocator structure.
8640 d61df03e Iustin Pop

8641 d1c2dd75 Iustin Pop
    This in combination with _AllocatorGetClusterData will create the
8642 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
8643 d61df03e Iustin Pop

8644 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
8645 d1c2dd75 Iustin Pop
    done.
8646 d61df03e Iustin Pop

8647 d1c2dd75 Iustin Pop
    """
8648 d1c2dd75 Iustin Pop
    data = self.in_data
8649 d1c2dd75 Iustin Pop
8650 dafc7302 Guido Trotter
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
8651 d1c2dd75 Iustin Pop
8652 27579978 Iustin Pop
    if self.disk_template in constants.DTS_NET_MIRROR:
8653 27579978 Iustin Pop
      self.required_nodes = 2
8654 27579978 Iustin Pop
    else:
8655 27579978 Iustin Pop
      self.required_nodes = 1
8656 d1c2dd75 Iustin Pop
    request = {
8657 d1c2dd75 Iustin Pop
      "type": "allocate",
8658 d1c2dd75 Iustin Pop
      "name": self.name,
8659 d1c2dd75 Iustin Pop
      "disk_template": self.disk_template,
8660 d1c2dd75 Iustin Pop
      "tags": self.tags,
8661 d1c2dd75 Iustin Pop
      "os": self.os,
8662 d1c2dd75 Iustin Pop
      "vcpus": self.vcpus,
8663 d1c2dd75 Iustin Pop
      "memory": self.mem_size,
8664 d1c2dd75 Iustin Pop
      "disks": self.disks,
8665 d1c2dd75 Iustin Pop
      "disk_space_total": disk_space,
8666 d1c2dd75 Iustin Pop
      "nics": self.nics,
8667 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
8668 d1c2dd75 Iustin Pop
      }
8669 d1c2dd75 Iustin Pop
    data["request"] = request
8670 298fe380 Iustin Pop
8671 d1c2dd75 Iustin Pop
  def _AddRelocateInstance(self):
8672 d1c2dd75 Iustin Pop
    """Add relocate instance data to allocator structure.
8673 298fe380 Iustin Pop

8674 d1c2dd75 Iustin Pop
    This in combination with _IAllocatorGetClusterData will create the
8675 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
8676 d61df03e Iustin Pop

8677 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
8678 d1c2dd75 Iustin Pop
    done.
8679 d61df03e Iustin Pop

8680 d1c2dd75 Iustin Pop
    """
8681 923ddac0 Michael Hanselmann
    instance = self.cfg.GetInstanceInfo(self.name)
8682 27579978 Iustin Pop
    if instance is None:
8683 27579978 Iustin Pop
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
8684 27579978 Iustin Pop
                                   " IAllocator" % self.name)
8685 27579978 Iustin Pop
8686 27579978 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
8687 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
8688 5c983ee5 Iustin Pop
                                 errors.ECODE_INVAL)
8689 27579978 Iustin Pop
8690 2a139bb0 Iustin Pop
    if len(instance.secondary_nodes) != 1:
8691 5c983ee5 Iustin Pop
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
8692 5c983ee5 Iustin Pop
                                 errors.ECODE_STATE)
8693 2a139bb0 Iustin Pop
8694 27579978 Iustin Pop
    self.required_nodes = 1
8695 dafc7302 Guido Trotter
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
8696 dafc7302 Guido Trotter
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
8697 27579978 Iustin Pop
8698 d1c2dd75 Iustin Pop
    request = {
8699 2a139bb0 Iustin Pop
      "type": "relocate",
8700 d1c2dd75 Iustin Pop
      "name": self.name,
8701 27579978 Iustin Pop
      "disk_space_total": disk_space,
8702 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
8703 29859cb7 Iustin Pop
      "relocate_from": self.relocate_from,
8704 d1c2dd75 Iustin Pop
      }
8705 27579978 Iustin Pop
    self.in_data["request"] = request
8706 d61df03e Iustin Pop
8707 d1c2dd75 Iustin Pop
  def _BuildInputData(self):
8708 d1c2dd75 Iustin Pop
    """Build input data structures.
8709 d61df03e Iustin Pop

8710 d1c2dd75 Iustin Pop
    """
8711 d1c2dd75 Iustin Pop
    self._ComputeClusterData()
8712 d61df03e Iustin Pop
8713 d1c2dd75 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
8714 d1c2dd75 Iustin Pop
      self._AddNewInstance()
8715 d1c2dd75 Iustin Pop
    else:
8716 d1c2dd75 Iustin Pop
      self._AddRelocateInstance()
8717 d61df03e Iustin Pop
8718 d1c2dd75 Iustin Pop
    self.in_text = serializer.Dump(self.in_data)
8719 d61df03e Iustin Pop
8720 72737a7f Iustin Pop
  def Run(self, name, validate=True, call_fn=None):
8721 d1c2dd75 Iustin Pop
    """Run an instance allocator and return the results.
8722 298fe380 Iustin Pop

8723 d1c2dd75 Iustin Pop
    """
8724 72737a7f Iustin Pop
    if call_fn is None:
8725 923ddac0 Michael Hanselmann
      call_fn = self.rpc.call_iallocator_runner
8726 298fe380 Iustin Pop
8727 923ddac0 Michael Hanselmann
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
8728 4c4e4e1e Iustin Pop
    result.Raise("Failure while running the iallocator script")
8729 8d528b7c Iustin Pop
8730 87f5c298 Iustin Pop
    self.out_text = result.payload
8731 d1c2dd75 Iustin Pop
    if validate:
8732 d1c2dd75 Iustin Pop
      self._ValidateResult()
8733 298fe380 Iustin Pop
8734 d1c2dd75 Iustin Pop
  def _ValidateResult(self):
8735 d1c2dd75 Iustin Pop
    """Process the allocator results.
8736 538475ca Iustin Pop

8737 d1c2dd75 Iustin Pop
    This will process and if successful save the result in
8738 d1c2dd75 Iustin Pop
    self.out_data and the other parameters.
8739 538475ca Iustin Pop

8740 d1c2dd75 Iustin Pop
    """
8741 d1c2dd75 Iustin Pop
    try:
8742 d1c2dd75 Iustin Pop
      rdict = serializer.Load(self.out_text)
8743 d1c2dd75 Iustin Pop
    except Exception, err:
8744 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
8745 d1c2dd75 Iustin Pop
8746 d1c2dd75 Iustin Pop
    if not isinstance(rdict, dict):
8747 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
8748 538475ca Iustin Pop
8749 d1c2dd75 Iustin Pop
    for key in "success", "info", "nodes":
8750 d1c2dd75 Iustin Pop
      if key not in rdict:
8751 d1c2dd75 Iustin Pop
        raise errors.OpExecError("Can't parse iallocator results:"
8752 d1c2dd75 Iustin Pop
                                 " missing key '%s'" % key)
8753 d1c2dd75 Iustin Pop
      setattr(self, key, rdict[key])
8754 538475ca Iustin Pop
8755 d1c2dd75 Iustin Pop
    if not isinstance(rdict["nodes"], list):
8756 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
8757 d1c2dd75 Iustin Pop
                               " is not a list")
8758 d1c2dd75 Iustin Pop
    self.out_data = rdict
8759 538475ca Iustin Pop
8760 538475ca Iustin Pop
8761 d61df03e Iustin Pop
class LUTestAllocator(NoHooksLU):
8762 d61df03e Iustin Pop
  """Run allocator tests.
8763 d61df03e Iustin Pop

8764 d61df03e Iustin Pop
  This LU runs the allocator tests
8765 d61df03e Iustin Pop

8766 d61df03e Iustin Pop
  """
8767 d61df03e Iustin Pop
  _OP_REQP = ["direction", "mode", "name"]
8768 d61df03e Iustin Pop
8769 d61df03e Iustin Pop
  def CheckPrereq(self):
8770 d61df03e Iustin Pop
    """Check prerequisites.
8771 d61df03e Iustin Pop

8772 d61df03e Iustin Pop
    This checks the opcode parameters depending on the director and mode test.
8773 d61df03e Iustin Pop

8774 d61df03e Iustin Pop
    """
8775 298fe380 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8776 d61df03e Iustin Pop
      for attr in ["name", "mem_size", "disks", "disk_template",
8777 d61df03e Iustin Pop
                   "os", "tags", "nics", "vcpus"]:
8778 d61df03e Iustin Pop
        if not hasattr(self.op, attr):
8779 d61df03e Iustin Pop
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
8780 5c983ee5 Iustin Pop
                                     attr, errors.ECODE_INVAL)
8781 d61df03e Iustin Pop
      iname = self.cfg.ExpandInstanceName(self.op.name)
8782 d61df03e Iustin Pop
      if iname is not None:
8783 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
8784 5c983ee5 Iustin Pop
                                   iname, errors.ECODE_EXISTS)
8785 d61df03e Iustin Pop
      if not isinstance(self.op.nics, list):
8786 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'nics'",
8787 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
8788 d61df03e Iustin Pop
      for row in self.op.nics:
8789 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
8790 d61df03e Iustin Pop
            "mac" not in row or
8791 d61df03e Iustin Pop
            "ip" not in row or
8792 d61df03e Iustin Pop
            "bridge" not in row):
8793 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
8794 5c983ee5 Iustin Pop
                                     " parameter", errors.ECODE_INVAL)
8795 d61df03e Iustin Pop
      if not isinstance(self.op.disks, list):
8796 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'disks'",
8797 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
8798 d61df03e Iustin Pop
      for row in self.op.disks:
8799 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
8800 d61df03e Iustin Pop
            "size" not in row or
8801 d61df03e Iustin Pop
            not isinstance(row["size"], int) or
8802 d61df03e Iustin Pop
            "mode" not in row or
8803 d61df03e Iustin Pop
            row["mode"] not in ['r', 'w']):
8804 5c983ee5 Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
8805 5c983ee5 Iustin Pop
                                     " parameter", errors.ECODE_INVAL)
8806 8901997e Iustin Pop
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
8807 8cc7e742 Guido Trotter
        self.op.hypervisor = self.cfg.GetHypervisorType()
8808 298fe380 Iustin Pop
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
8809 d61df03e Iustin Pop
      if not hasattr(self.op, "name"):
8810 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
8811 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
8812 d61df03e Iustin Pop
      fname = self.cfg.ExpandInstanceName(self.op.name)
8813 d61df03e Iustin Pop
      if fname is None:
8814 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
8815 5c983ee5 Iustin Pop
                                   self.op.name, errors.ECODE_NOENT)
8816 d61df03e Iustin Pop
      self.op.name = fname
8817 29859cb7 Iustin Pop
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
8818 d61df03e Iustin Pop
    else:
8819 d61df03e Iustin Pop
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
8820 5c983ee5 Iustin Pop
                                 self.op.mode, errors.ECODE_INVAL)
8821 d61df03e Iustin Pop
8822 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
8823 298fe380 Iustin Pop
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
8824 5c983ee5 Iustin Pop
        raise errors.OpPrereqError("Missing allocator name",
8825 5c983ee5 Iustin Pop
                                   errors.ECODE_INVAL)
8826 298fe380 Iustin Pop
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
8827 d61df03e Iustin Pop
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
8828 5c983ee5 Iustin Pop
                                 self.op.direction, errors.ECODE_INVAL)
8829 d61df03e Iustin Pop
8830 d61df03e Iustin Pop
  def Exec(self, feedback_fn):
8831 d61df03e Iustin Pop
    """Run the allocator test.
8832 d61df03e Iustin Pop

8833 d61df03e Iustin Pop
    """
8834 29859cb7 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
8835 923ddac0 Michael Hanselmann
      ial = IAllocator(self.cfg, self.rpc,
8836 29859cb7 Iustin Pop
                       mode=self.op.mode,
8837 29859cb7 Iustin Pop
                       name=self.op.name,
8838 29859cb7 Iustin Pop
                       mem_size=self.op.mem_size,
8839 29859cb7 Iustin Pop
                       disks=self.op.disks,
8840 29859cb7 Iustin Pop
                       disk_template=self.op.disk_template,
8841 29859cb7 Iustin Pop
                       os=self.op.os,
8842 29859cb7 Iustin Pop
                       tags=self.op.tags,
8843 29859cb7 Iustin Pop
                       nics=self.op.nics,
8844 29859cb7 Iustin Pop
                       vcpus=self.op.vcpus,
8845 8cc7e742 Guido Trotter
                       hypervisor=self.op.hypervisor,
8846 29859cb7 Iustin Pop
                       )
8847 29859cb7 Iustin Pop
    else:
8848 923ddac0 Michael Hanselmann
      ial = IAllocator(self.cfg, self.rpc,
8849 29859cb7 Iustin Pop
                       mode=self.op.mode,
8850 29859cb7 Iustin Pop
                       name=self.op.name,
8851 29859cb7 Iustin Pop
                       relocate_from=list(self.relocate_from),
8852 29859cb7 Iustin Pop
                       )
8853 d61df03e Iustin Pop
8854 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
8855 d1c2dd75 Iustin Pop
      result = ial.in_text
8856 298fe380 Iustin Pop
    else:
8857 d1c2dd75 Iustin Pop
      ial.Run(self.op.allocator, validate=False)
8858 d1c2dd75 Iustin Pop
      result = ial.out_text
8859 298fe380 Iustin Pop
    return result