Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 1492cca7

History | View | Annotate | Download (228.3 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 e7c6e02b Michael Hanselmann
# Copyright (C) 2006, 2007, 2008 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 880478f8 Iustin Pop
"""Module implementing the master-side code."""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
# pylint: disable-msg=W0613,W0201
25 a8083063 Iustin Pop
26 a8083063 Iustin Pop
import os
27 a8083063 Iustin Pop
import os.path
28 a8083063 Iustin Pop
import sha
29 a8083063 Iustin Pop
import time
30 a8083063 Iustin Pop
import tempfile
31 a8083063 Iustin Pop
import re
32 a8083063 Iustin Pop
import platform
33 ffa1c0dc Iustin Pop
import logging
34 74409b12 Iustin Pop
import copy
35 4b7735f9 Iustin Pop
import random
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 a8083063 Iustin Pop
from ganeti import opcodes
45 8d14b30d Iustin Pop
from ganeti import serializer
46 112f18a5 Iustin Pop
from ganeti import ssconf
47 d61df03e Iustin Pop
48 d61df03e Iustin Pop
49 a8083063 Iustin Pop
class LogicalUnit(object):
50 396e1b78 Michael Hanselmann
  """Logical Unit base class.
51 a8083063 Iustin Pop

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

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

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

72 a8083063 Iustin Pop
    This needs to be overriden in derived classes in order to check op
73 a8083063 Iustin Pop
    validity.
74 a8083063 Iustin Pop

75 a8083063 Iustin Pop
    """
76 5bfac263 Iustin Pop
    self.proc = processor
77 a8083063 Iustin Pop
    self.op = op
78 77b657a3 Guido Trotter
    self.cfg = context.cfg
79 77b657a3 Guido Trotter
    self.context = context
80 72737a7f Iustin Pop
    self.rpc = rpc
81 ca2a79e1 Guido Trotter
    # Dicts used to declare locking needs to mcpu
82 d465bdc8 Guido Trotter
    self.needed_locks = None
83 6683bba2 Guido Trotter
    self.acquired_locks = {}
84 3977a4c1 Guido Trotter
    self.share_locks = dict(((i, 0) for i in locking.LEVELS))
85 ca2a79e1 Guido Trotter
    self.add_locks = {}
86 ca2a79e1 Guido Trotter
    self.remove_locks = {}
87 c4a2fee1 Guido Trotter
    # Used to force good behavior when calling helper functions
88 c4a2fee1 Guido Trotter
    self.recalculate_locks = {}
89 c92b310a Michael Hanselmann
    self.__ssh = None
90 86d9d3bb Iustin Pop
    # logging
91 86d9d3bb Iustin Pop
    self.LogWarning = processor.LogWarning
92 86d9d3bb Iustin Pop
    self.LogInfo = processor.LogInfo
93 c92b310a Michael Hanselmann
94 a8083063 Iustin Pop
    for attr_name in self._OP_REQP:
95 a8083063 Iustin Pop
      attr_val = getattr(op, attr_name, None)
96 a8083063 Iustin Pop
      if attr_val is None:
97 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Required parameter '%s' missing" %
98 3ecf6786 Iustin Pop
                                   attr_name)
99 4be4691d Iustin Pop
    self.CheckArguments()
100 a8083063 Iustin Pop
101 c92b310a Michael Hanselmann
  def __GetSSH(self):
102 c92b310a Michael Hanselmann
    """Returns the SshRunner object
103 c92b310a Michael Hanselmann

104 c92b310a Michael Hanselmann
    """
105 c92b310a Michael Hanselmann
    if not self.__ssh:
106 6b0469d2 Iustin Pop
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
107 c92b310a Michael Hanselmann
    return self.__ssh
108 c92b310a Michael Hanselmann
109 c92b310a Michael Hanselmann
  ssh = property(fget=__GetSSH)
110 c92b310a Michael Hanselmann
111 4be4691d Iustin Pop
  def CheckArguments(self):
112 4be4691d Iustin Pop
    """Check syntactic validity for the opcode arguments.
113 4be4691d Iustin Pop

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

119 4be4691d Iustin Pop
      - ExpandNames is left as as purely a lock-related function
120 4be4691d Iustin Pop
      - CheckPrereq is run after we have aquired locks (and possible
121 4be4691d Iustin Pop
        waited for them)
122 4be4691d Iustin Pop

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

126 4be4691d Iustin Pop
    """
127 4be4691d Iustin Pop
    pass
128 4be4691d Iustin Pop
129 d465bdc8 Guido Trotter
  def ExpandNames(self):
130 d465bdc8 Guido Trotter
    """Expand names for this LU.
131 d465bdc8 Guido Trotter

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

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

141 e4376078 Iustin Pop
      - use an empty dict if you don't need any lock
142 e4376078 Iustin Pop
      - if you don't need any lock at a particular level omit that level
143 e4376078 Iustin Pop
      - don't put anything for the BGL level
144 e4376078 Iustin Pop
      - if you want all locks at a level use locking.ALL_SET as a value
145 d465bdc8 Guido Trotter

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

150 e4376078 Iustin Pop
    Examples::
151 e4376078 Iustin Pop

152 e4376078 Iustin Pop
      # Acquire all nodes and one instance
153 e4376078 Iustin Pop
      self.needed_locks = {
154 e4376078 Iustin Pop
        locking.LEVEL_NODE: locking.ALL_SET,
155 e4376078 Iustin Pop
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
156 e4376078 Iustin Pop
      }
157 e4376078 Iustin Pop
      # Acquire just two nodes
158 e4376078 Iustin Pop
      self.needed_locks = {
159 e4376078 Iustin Pop
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
160 e4376078 Iustin Pop
      }
161 e4376078 Iustin Pop
      # Acquire no locks
162 e4376078 Iustin Pop
      self.needed_locks = {} # No, you can't leave it to the default value None
163 d465bdc8 Guido Trotter

164 d465bdc8 Guido Trotter
    """
165 d465bdc8 Guido Trotter
    # The implementation of this method is mandatory only if the new LU is
166 d465bdc8 Guido Trotter
    # concurrent, so that old LUs don't need to be changed all at the same
167 d465bdc8 Guido Trotter
    # time.
168 d465bdc8 Guido Trotter
    if self.REQ_BGL:
169 d465bdc8 Guido Trotter
      self.needed_locks = {} # Exclusive LUs don't need locks.
170 d465bdc8 Guido Trotter
    else:
171 d465bdc8 Guido Trotter
      raise NotImplementedError
172 d465bdc8 Guido Trotter
173 fb8dcb62 Guido Trotter
  def DeclareLocks(self, level):
174 fb8dcb62 Guido Trotter
    """Declare LU locking needs for a level
175 fb8dcb62 Guido Trotter

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

183 fb8dcb62 Guido Trotter
    This function is only called if you have something already set in
184 fb8dcb62 Guido Trotter
    self.needed_locks for the level.
185 fb8dcb62 Guido Trotter

186 fb8dcb62 Guido Trotter
    @param level: Locking level which is going to be locked
187 fb8dcb62 Guido Trotter
    @type level: member of ganeti.locking.LEVELS
188 fb8dcb62 Guido Trotter

189 fb8dcb62 Guido Trotter
    """
190 fb8dcb62 Guido Trotter
191 a8083063 Iustin Pop
  def CheckPrereq(self):
192 a8083063 Iustin Pop
    """Check prerequisites for this LU.
193 a8083063 Iustin Pop

194 a8083063 Iustin Pop
    This method should check that the prerequisites for the execution
195 a8083063 Iustin Pop
    of this LU are fulfilled. It can do internode communication, but
196 a8083063 Iustin Pop
    it should be idempotent - no cluster or system changes are
197 a8083063 Iustin Pop
    allowed.
198 a8083063 Iustin Pop

199 a8083063 Iustin Pop
    The method should raise errors.OpPrereqError in case something is
200 a8083063 Iustin Pop
    not fulfilled. Its return value is ignored.
201 a8083063 Iustin Pop

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

205 a8083063 Iustin Pop
    """
206 a8083063 Iustin Pop
    raise NotImplementedError
207 a8083063 Iustin Pop
208 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
209 a8083063 Iustin Pop
    """Execute the LU.
210 a8083063 Iustin Pop

211 a8083063 Iustin Pop
    This method should implement the actual work. It should raise
212 a8083063 Iustin Pop
    errors.OpExecError for failures that are somewhat dealt with in
213 a8083063 Iustin Pop
    code, or expected.
214 a8083063 Iustin Pop

215 a8083063 Iustin Pop
    """
216 a8083063 Iustin Pop
    raise NotImplementedError
217 a8083063 Iustin Pop
218 a8083063 Iustin Pop
  def BuildHooksEnv(self):
219 a8083063 Iustin Pop
    """Build hooks environment for this LU.
220 a8083063 Iustin Pop

221 a8083063 Iustin Pop
    This method should return a three-node tuple consisting of: a dict
222 a8083063 Iustin Pop
    containing the environment that will be used for running the
223 a8083063 Iustin Pop
    specific hook for this LU, a list of node names on which the hook
224 a8083063 Iustin Pop
    should run before the execution, and a list of node names on which
225 a8083063 Iustin Pop
    the hook should run after the execution.
226 a8083063 Iustin Pop

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

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

234 a8083063 Iustin Pop
    Note that if the HPATH for a LU class is None, this function will
235 a8083063 Iustin Pop
    not be called.
236 a8083063 Iustin Pop

237 a8083063 Iustin Pop
    """
238 a8083063 Iustin Pop
    raise NotImplementedError
239 a8083063 Iustin Pop
240 1fce5219 Guido Trotter
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
241 1fce5219 Guido Trotter
    """Notify the LU about the results of its hooks.
242 1fce5219 Guido Trotter

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

249 e4376078 Iustin Pop
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
250 e4376078 Iustin Pop
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
251 e4376078 Iustin Pop
    @param hook_results: the results of the multi-node hooks rpc call
252 e4376078 Iustin Pop
    @param feedback_fn: function used send feedback back to the caller
253 e4376078 Iustin Pop
    @param lu_result: the previous Exec result this LU had, or None
254 e4376078 Iustin Pop
        in the PRE phase
255 e4376078 Iustin Pop
    @return: the new Exec result, based on the previous result
256 e4376078 Iustin Pop
        and hook results
257 1fce5219 Guido Trotter

258 1fce5219 Guido Trotter
    """
259 1fce5219 Guido Trotter
    return lu_result
260 1fce5219 Guido Trotter
261 43905206 Guido Trotter
  def _ExpandAndLockInstance(self):
262 43905206 Guido Trotter
    """Helper function to expand and lock an instance.
263 43905206 Guido Trotter

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

270 43905206 Guido Trotter
    """
271 43905206 Guido Trotter
    if self.needed_locks is None:
272 43905206 Guido Trotter
      self.needed_locks = {}
273 43905206 Guido Trotter
    else:
274 43905206 Guido Trotter
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
275 43905206 Guido Trotter
        "_ExpandAndLockInstance called with instance-level locks set"
276 43905206 Guido Trotter
    expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name)
277 43905206 Guido Trotter
    if expanded_name is None:
278 43905206 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' not known" %
279 43905206 Guido Trotter
                                  self.op.instance_name)
280 43905206 Guido Trotter
    self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
281 43905206 Guido Trotter
    self.op.instance_name = expanded_name
282 43905206 Guido Trotter
283 a82ce292 Guido Trotter
  def _LockInstancesNodes(self, primary_only=False):
284 c4a2fee1 Guido Trotter
    """Helper function to declare instances' nodes for locking.
285 c4a2fee1 Guido Trotter

286 c4a2fee1 Guido Trotter
    This function should be called after locking one or more instances to lock
287 c4a2fee1 Guido Trotter
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
288 c4a2fee1 Guido Trotter
    with all primary or secondary nodes for instances already locked and
289 c4a2fee1 Guido Trotter
    present in self.needed_locks[locking.LEVEL_INSTANCE].
290 c4a2fee1 Guido Trotter

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

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

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

299 e4376078 Iustin Pop
      if level == locking.LEVEL_NODE:
300 e4376078 Iustin Pop
        self._LockInstancesNodes()
301 c4a2fee1 Guido Trotter

302 a82ce292 Guido Trotter
    @type primary_only: boolean
303 a82ce292 Guido Trotter
    @param primary_only: only lock primary nodes of locked instances
304 a82ce292 Guido Trotter

305 c4a2fee1 Guido Trotter
    """
306 c4a2fee1 Guido Trotter
    assert locking.LEVEL_NODE in self.recalculate_locks, \
307 c4a2fee1 Guido Trotter
      "_LockInstancesNodes helper function called with no nodes to recalculate"
308 c4a2fee1 Guido Trotter
309 c4a2fee1 Guido Trotter
    # TODO: check if we're really been called with the instance locks held
310 c4a2fee1 Guido Trotter
311 c4a2fee1 Guido Trotter
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
312 c4a2fee1 Guido Trotter
    # future we might want to have different behaviors depending on the value
313 c4a2fee1 Guido Trotter
    # of self.recalculate_locks[locking.LEVEL_NODE]
314 c4a2fee1 Guido Trotter
    wanted_nodes = []
315 6683bba2 Guido Trotter
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
316 c4a2fee1 Guido Trotter
      instance = self.context.cfg.GetInstanceInfo(instance_name)
317 c4a2fee1 Guido Trotter
      wanted_nodes.append(instance.primary_node)
318 a82ce292 Guido Trotter
      if not primary_only:
319 a82ce292 Guido Trotter
        wanted_nodes.extend(instance.secondary_nodes)
320 9513b6ab Guido Trotter
321 9513b6ab Guido Trotter
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
322 9513b6ab Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
323 9513b6ab Guido Trotter
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
324 9513b6ab Guido Trotter
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
325 c4a2fee1 Guido Trotter
326 c4a2fee1 Guido Trotter
    del self.recalculate_locks[locking.LEVEL_NODE]
327 c4a2fee1 Guido Trotter
328 a8083063 Iustin Pop
329 a8083063 Iustin Pop
class NoHooksLU(LogicalUnit):
330 a8083063 Iustin Pop
  """Simple LU which runs no hooks.
331 a8083063 Iustin Pop

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

335 a8083063 Iustin Pop
  """
336 a8083063 Iustin Pop
  HPATH = None
337 a8083063 Iustin Pop
  HTYPE = None
338 a8083063 Iustin Pop
339 a8083063 Iustin Pop
340 dcb93971 Michael Hanselmann
def _GetWantedNodes(lu, nodes):
341 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded node names.
342 83120a01 Michael Hanselmann

343 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
344 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
345 e4376078 Iustin Pop
  @type nodes: list
346 e4376078 Iustin Pop
  @param nodes: list of node names or None for all nodes
347 e4376078 Iustin Pop
  @rtype: list
348 e4376078 Iustin Pop
  @return: the list of nodes, sorted
349 e4376078 Iustin Pop
  @raise errors.OpProgrammerError: if the nodes parameter is wrong type
350 83120a01 Michael Hanselmann

351 83120a01 Michael Hanselmann
  """
352 3312b702 Iustin Pop
  if not isinstance(nodes, list):
353 3ecf6786 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
354 dcb93971 Michael Hanselmann
355 ea47808a Guido Trotter
  if not nodes:
356 ea47808a Guido Trotter
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
357 ea47808a Guido Trotter
      " non-empty list of nodes whose name is to be expanded.")
358 dcb93971 Michael Hanselmann
359 ea47808a Guido Trotter
  wanted = []
360 ea47808a Guido Trotter
  for name in nodes:
361 ea47808a Guido Trotter
    node = lu.cfg.ExpandNodeName(name)
362 ea47808a Guido Trotter
    if node is None:
363 ea47808a Guido Trotter
      raise errors.OpPrereqError("No such node name '%s'" % name)
364 ea47808a Guido Trotter
    wanted.append(node)
365 dcb93971 Michael Hanselmann
366 a7ba5e53 Iustin Pop
  return utils.NiceSort(wanted)
367 3312b702 Iustin Pop
368 3312b702 Iustin Pop
369 3312b702 Iustin Pop
def _GetWantedInstances(lu, instances):
370 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded instance names.
371 3312b702 Iustin Pop

372 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
373 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
374 e4376078 Iustin Pop
  @type instances: list
375 e4376078 Iustin Pop
  @param instances: list of instance names or None for all instances
376 e4376078 Iustin Pop
  @rtype: list
377 e4376078 Iustin Pop
  @return: the list of instances, sorted
378 e4376078 Iustin Pop
  @raise errors.OpPrereqError: if the instances parameter is wrong type
379 e4376078 Iustin Pop
  @raise errors.OpPrereqError: if any of the passed instances is not found
380 3312b702 Iustin Pop

381 3312b702 Iustin Pop
  """
382 3312b702 Iustin Pop
  if not isinstance(instances, list):
383 3312b702 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'instances'")
384 3312b702 Iustin Pop
385 3312b702 Iustin Pop
  if instances:
386 3312b702 Iustin Pop
    wanted = []
387 3312b702 Iustin Pop
388 3312b702 Iustin Pop
    for name in instances:
389 a7ba5e53 Iustin Pop
      instance = lu.cfg.ExpandInstanceName(name)
390 3312b702 Iustin Pop
      if instance is None:
391 3312b702 Iustin Pop
        raise errors.OpPrereqError("No such instance name '%s'" % name)
392 3312b702 Iustin Pop
      wanted.append(instance)
393 3312b702 Iustin Pop
394 3312b702 Iustin Pop
  else:
395 a7ba5e53 Iustin Pop
    wanted = lu.cfg.GetInstanceList()
396 a7ba5e53 Iustin Pop
  return utils.NiceSort(wanted)
397 dcb93971 Michael Hanselmann
398 dcb93971 Michael Hanselmann
399 dcb93971 Michael Hanselmann
def _CheckOutputFields(static, dynamic, selected):
400 83120a01 Michael Hanselmann
  """Checks whether all selected fields are valid.
401 83120a01 Michael Hanselmann

402 a2d2e1a7 Iustin Pop
  @type static: L{utils.FieldSet}
403 31bf511f Iustin Pop
  @param static: static fields set
404 a2d2e1a7 Iustin Pop
  @type dynamic: L{utils.FieldSet}
405 31bf511f Iustin Pop
  @param dynamic: dynamic fields set
406 83120a01 Michael Hanselmann

407 83120a01 Michael Hanselmann
  """
408 a2d2e1a7 Iustin Pop
  f = utils.FieldSet()
409 31bf511f Iustin Pop
  f.Extend(static)
410 31bf511f Iustin Pop
  f.Extend(dynamic)
411 dcb93971 Michael Hanselmann
412 31bf511f Iustin Pop
  delta = f.NonMatching(selected)
413 31bf511f Iustin Pop
  if delta:
414 3ecf6786 Iustin Pop
    raise errors.OpPrereqError("Unknown output fields selected: %s"
415 31bf511f Iustin Pop
                               % ",".join(delta))
416 dcb93971 Michael Hanselmann
417 dcb93971 Michael Hanselmann
418 a5961235 Iustin Pop
def _CheckBooleanOpField(op, name):
419 a5961235 Iustin Pop
  """Validates boolean opcode parameters.
420 a5961235 Iustin Pop

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

424 a5961235 Iustin Pop
  """
425 a5961235 Iustin Pop
  val = getattr(op, name, None)
426 a5961235 Iustin Pop
  if not (val is None or isinstance(val, bool)):
427 a5961235 Iustin Pop
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
428 a5961235 Iustin Pop
                               (name, str(val)))
429 a5961235 Iustin Pop
  setattr(op, name, val)
430 a5961235 Iustin Pop
431 a5961235 Iustin Pop
432 a5961235 Iustin Pop
def _CheckNodeOnline(lu, node):
433 a5961235 Iustin Pop
  """Ensure that a given node is online.
434 a5961235 Iustin Pop

435 a5961235 Iustin Pop
  @param lu: the LU on behalf of which we make the check
436 a5961235 Iustin Pop
  @param node: the node to check
437 a5961235 Iustin Pop
  @raise errors.OpPrereqError: if the nodes is offline
438 a5961235 Iustin Pop

439 a5961235 Iustin Pop
  """
440 a5961235 Iustin Pop
  if lu.cfg.GetNodeInfo(node).offline:
441 a5961235 Iustin Pop
    raise errors.OpPrereqError("Can't use offline node %s" % node)
442 a5961235 Iustin Pop
443 a5961235 Iustin Pop
444 ecb215b5 Michael Hanselmann
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
445 396e1b78 Michael Hanselmann
                          memory, vcpus, nics):
446 e4376078 Iustin Pop
  """Builds instance related env variables for hooks
447 e4376078 Iustin Pop

448 e4376078 Iustin Pop
  This builds the hook environment from individual variables.
449 e4376078 Iustin Pop

450 e4376078 Iustin Pop
  @type name: string
451 e4376078 Iustin Pop
  @param name: the name of the instance
452 e4376078 Iustin Pop
  @type primary_node: string
453 e4376078 Iustin Pop
  @param primary_node: the name of the instance's primary node
454 e4376078 Iustin Pop
  @type secondary_nodes: list
455 e4376078 Iustin Pop
  @param secondary_nodes: list of secondary nodes as strings
456 e4376078 Iustin Pop
  @type os_type: string
457 e4376078 Iustin Pop
  @param os_type: the name of the instance's OS
458 e4376078 Iustin Pop
  @type status: string
459 e4376078 Iustin Pop
  @param status: the desired status of the instances
460 e4376078 Iustin Pop
  @type memory: string
461 e4376078 Iustin Pop
  @param memory: the memory size of the instance
462 e4376078 Iustin Pop
  @type vcpus: string
463 e4376078 Iustin Pop
  @param vcpus: the count of VCPUs the instance has
464 e4376078 Iustin Pop
  @type nics: list
465 e4376078 Iustin Pop
  @param nics: list of tuples (ip, bridge, mac) representing
466 e4376078 Iustin Pop
      the NICs the instance  has
467 e4376078 Iustin Pop
  @rtype: dict
468 e4376078 Iustin Pop
  @return: the hook environment for this instance
469 ecb215b5 Michael Hanselmann

470 396e1b78 Michael Hanselmann
  """
471 396e1b78 Michael Hanselmann
  env = {
472 0e137c28 Iustin Pop
    "OP_TARGET": name,
473 396e1b78 Michael Hanselmann
    "INSTANCE_NAME": name,
474 396e1b78 Michael Hanselmann
    "INSTANCE_PRIMARY": primary_node,
475 396e1b78 Michael Hanselmann
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
476 ecb215b5 Michael Hanselmann
    "INSTANCE_OS_TYPE": os_type,
477 396e1b78 Michael Hanselmann
    "INSTANCE_STATUS": status,
478 396e1b78 Michael Hanselmann
    "INSTANCE_MEMORY": memory,
479 396e1b78 Michael Hanselmann
    "INSTANCE_VCPUS": vcpus,
480 396e1b78 Michael Hanselmann
  }
481 396e1b78 Michael Hanselmann
482 396e1b78 Michael Hanselmann
  if nics:
483 396e1b78 Michael Hanselmann
    nic_count = len(nics)
484 53e4e875 Guido Trotter
    for idx, (ip, bridge, mac) in enumerate(nics):
485 396e1b78 Michael Hanselmann
      if ip is None:
486 396e1b78 Michael Hanselmann
        ip = ""
487 396e1b78 Michael Hanselmann
      env["INSTANCE_NIC%d_IP" % idx] = ip
488 396e1b78 Michael Hanselmann
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
489 53e4e875 Guido Trotter
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
490 396e1b78 Michael Hanselmann
  else:
491 396e1b78 Michael Hanselmann
    nic_count = 0
492 396e1b78 Michael Hanselmann
493 396e1b78 Michael Hanselmann
  env["INSTANCE_NIC_COUNT"] = nic_count
494 396e1b78 Michael Hanselmann
495 396e1b78 Michael Hanselmann
  return env
496 396e1b78 Michael Hanselmann
497 396e1b78 Michael Hanselmann
498 338e51e8 Iustin Pop
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
499 ecb215b5 Michael Hanselmann
  """Builds instance related env variables for hooks from an object.
500 ecb215b5 Michael Hanselmann

501 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
502 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
503 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
504 e4376078 Iustin Pop
  @param instance: the instance for which we should build the
505 e4376078 Iustin Pop
      environment
506 e4376078 Iustin Pop
  @type override: dict
507 e4376078 Iustin Pop
  @param override: dictionary with key/values that will override
508 e4376078 Iustin Pop
      our values
509 e4376078 Iustin Pop
  @rtype: dict
510 e4376078 Iustin Pop
  @return: the hook environment dictionary
511 e4376078 Iustin Pop

512 ecb215b5 Michael Hanselmann
  """
513 338e51e8 Iustin Pop
  bep = lu.cfg.GetClusterInfo().FillBE(instance)
514 396e1b78 Michael Hanselmann
  args = {
515 396e1b78 Michael Hanselmann
    'name': instance.name,
516 396e1b78 Michael Hanselmann
    'primary_node': instance.primary_node,
517 396e1b78 Michael Hanselmann
    'secondary_nodes': instance.secondary_nodes,
518 ecb215b5 Michael Hanselmann
    'os_type': instance.os,
519 396e1b78 Michael Hanselmann
    'status': instance.os,
520 338e51e8 Iustin Pop
    'memory': bep[constants.BE_MEMORY],
521 338e51e8 Iustin Pop
    'vcpus': bep[constants.BE_VCPUS],
522 53e4e875 Guido Trotter
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
523 396e1b78 Michael Hanselmann
  }
524 396e1b78 Michael Hanselmann
  if override:
525 396e1b78 Michael Hanselmann
    args.update(override)
526 396e1b78 Michael Hanselmann
  return _BuildInstanceHookEnv(**args)
527 396e1b78 Michael Hanselmann
528 396e1b78 Michael Hanselmann
529 ec0292f1 Iustin Pop
def _AdjustCandidatePool(lu):
530 ec0292f1 Iustin Pop
  """Adjust the candidate pool after node operations.
531 ec0292f1 Iustin Pop

532 ec0292f1 Iustin Pop
  """
533 ec0292f1 Iustin Pop
  mod_list = lu.cfg.MaintainCandidatePool()
534 ec0292f1 Iustin Pop
  if mod_list:
535 ec0292f1 Iustin Pop
    lu.LogInfo("Promoted nodes to master candidate role: %s",
536 ee513a66 Iustin Pop
               ", ".join(node.name for node in mod_list))
537 ec0292f1 Iustin Pop
    for name in mod_list:
538 ec0292f1 Iustin Pop
      lu.context.ReaddNode(name)
539 ec0292f1 Iustin Pop
  mc_now, mc_max = lu.cfg.GetMasterCandidateStats()
540 ec0292f1 Iustin Pop
  if mc_now > mc_max:
541 ec0292f1 Iustin Pop
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
542 ec0292f1 Iustin Pop
               (mc_now, mc_max))
543 ec0292f1 Iustin Pop
544 ec0292f1 Iustin Pop
545 b9bddb6b Iustin Pop
def _CheckInstanceBridgesExist(lu, instance):
546 bf6929a2 Alexander Schreiber
  """Check that the brigdes needed by an instance exist.
547 bf6929a2 Alexander Schreiber

548 bf6929a2 Alexander Schreiber
  """
549 bf6929a2 Alexander Schreiber
  # check bridges existance
550 bf6929a2 Alexander Schreiber
  brlist = [nic.bridge for nic in instance.nics]
551 781de953 Iustin Pop
  result = lu.rpc.call_bridges_exist(instance.primary_node, brlist)
552 781de953 Iustin Pop
  result.Raise()
553 781de953 Iustin Pop
  if not result.data:
554 781de953 Iustin Pop
    raise errors.OpPrereqError("One or more target bridges %s does not"
555 bf6929a2 Alexander Schreiber
                               " exist on destination node '%s'" %
556 bf6929a2 Alexander Schreiber
                               (brlist, instance.primary_node))
557 bf6929a2 Alexander Schreiber
558 bf6929a2 Alexander Schreiber
559 a8083063 Iustin Pop
class LUDestroyCluster(NoHooksLU):
560 a8083063 Iustin Pop
  """Logical unit for destroying the cluster.
561 a8083063 Iustin Pop

562 a8083063 Iustin Pop
  """
563 a8083063 Iustin Pop
  _OP_REQP = []
564 a8083063 Iustin Pop
565 a8083063 Iustin Pop
  def CheckPrereq(self):
566 a8083063 Iustin Pop
    """Check prerequisites.
567 a8083063 Iustin Pop

568 a8083063 Iustin Pop
    This checks whether the cluster is empty.
569 a8083063 Iustin Pop

570 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
571 a8083063 Iustin Pop

572 a8083063 Iustin Pop
    """
573 d6a02168 Michael Hanselmann
    master = self.cfg.GetMasterNode()
574 a8083063 Iustin Pop
575 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
576 db915bd1 Michael Hanselmann
    if len(nodelist) != 1 or nodelist[0] != master:
577 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d node(s) in"
578 3ecf6786 Iustin Pop
                                 " this cluster." % (len(nodelist) - 1))
579 db915bd1 Michael Hanselmann
    instancelist = self.cfg.GetInstanceList()
580 db915bd1 Michael Hanselmann
    if instancelist:
581 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d instance(s) in"
582 3ecf6786 Iustin Pop
                                 " this cluster." % len(instancelist))
583 a8083063 Iustin Pop
584 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
585 a8083063 Iustin Pop
    """Destroys the cluster.
586 a8083063 Iustin Pop

587 a8083063 Iustin Pop
    """
588 d6a02168 Michael Hanselmann
    master = self.cfg.GetMasterNode()
589 781de953 Iustin Pop
    result = self.rpc.call_node_stop_master(master, False)
590 781de953 Iustin Pop
    result.Raise()
591 781de953 Iustin Pop
    if not result.data:
592 c9064964 Iustin Pop
      raise errors.OpExecError("Could not disable the master role")
593 70d9e3d8 Iustin Pop
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
594 70d9e3d8 Iustin Pop
    utils.CreateBackup(priv_key)
595 70d9e3d8 Iustin Pop
    utils.CreateBackup(pub_key)
596 140aa4a8 Iustin Pop
    return master
597 a8083063 Iustin Pop
598 a8083063 Iustin Pop
599 d8fff41c Guido Trotter
class LUVerifyCluster(LogicalUnit):
600 a8083063 Iustin Pop
  """Verifies the cluster status.
601 a8083063 Iustin Pop

602 a8083063 Iustin Pop
  """
603 d8fff41c Guido Trotter
  HPATH = "cluster-verify"
604 d8fff41c Guido Trotter
  HTYPE = constants.HTYPE_CLUSTER
605 e54c4c5e Guido Trotter
  _OP_REQP = ["skip_checks"]
606 d4b9d97f Guido Trotter
  REQ_BGL = False
607 d4b9d97f Guido Trotter
608 d4b9d97f Guido Trotter
  def ExpandNames(self):
609 d4b9d97f Guido Trotter
    self.needed_locks = {
610 d4b9d97f Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
611 d4b9d97f Guido Trotter
      locking.LEVEL_INSTANCE: locking.ALL_SET,
612 d4b9d97f Guido Trotter
    }
613 d4b9d97f Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
614 a8083063 Iustin Pop
615 25361b9a Iustin Pop
  def _VerifyNode(self, nodeinfo, file_list, local_cksum,
616 25361b9a Iustin Pop
                  node_result, feedback_fn, master_files):
617 a8083063 Iustin Pop
    """Run multiple tests against a node.
618 a8083063 Iustin Pop

619 112f18a5 Iustin Pop
    Test list:
620 e4376078 Iustin Pop

621 a8083063 Iustin Pop
      - compares ganeti version
622 a8083063 Iustin Pop
      - checks vg existance and size > 20G
623 a8083063 Iustin Pop
      - checks config file checksum
624 a8083063 Iustin Pop
      - checks ssh to other nodes
625 a8083063 Iustin Pop

626 112f18a5 Iustin Pop
    @type nodeinfo: L{objects.Node}
627 112f18a5 Iustin Pop
    @param nodeinfo: the node to check
628 e4376078 Iustin Pop
    @param file_list: required list of files
629 e4376078 Iustin Pop
    @param local_cksum: dictionary of local files and their checksums
630 e4376078 Iustin Pop
    @param node_result: the results from the node
631 e4376078 Iustin Pop
    @param feedback_fn: function used to accumulate results
632 112f18a5 Iustin Pop
    @param master_files: list of files that only masters should have
633 098c0958 Michael Hanselmann

634 a8083063 Iustin Pop
    """
635 112f18a5 Iustin Pop
    node = nodeinfo.name
636 25361b9a Iustin Pop
637 25361b9a Iustin Pop
    # main result, node_result should be a non-empty dict
638 25361b9a Iustin Pop
    if not node_result or not isinstance(node_result, dict):
639 25361b9a Iustin Pop
      feedback_fn("  - ERROR: unable to verify node %s." % (node,))
640 25361b9a Iustin Pop
      return True
641 25361b9a Iustin Pop
642 a8083063 Iustin Pop
    # compares ganeti version
643 a8083063 Iustin Pop
    local_version = constants.PROTOCOL_VERSION
644 25361b9a Iustin Pop
    remote_version = node_result.get('version', None)
645 a8083063 Iustin Pop
    if not remote_version:
646 c840ae6f Guido Trotter
      feedback_fn("  - ERROR: connection to %s failed" % (node))
647 a8083063 Iustin Pop
      return True
648 a8083063 Iustin Pop
649 a8083063 Iustin Pop
    if local_version != remote_version:
650 a8083063 Iustin Pop
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
651 a8083063 Iustin Pop
                      (local_version, node, remote_version))
652 a8083063 Iustin Pop
      return True
653 a8083063 Iustin Pop
654 a8083063 Iustin Pop
    # checks vg existance and size > 20G
655 a8083063 Iustin Pop
656 a8083063 Iustin Pop
    bad = False
657 25361b9a Iustin Pop
    vglist = node_result.get(constants.NV_VGLIST, None)
658 a8083063 Iustin Pop
    if not vglist:
659 a8083063 Iustin Pop
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
660 a8083063 Iustin Pop
                      (node,))
661 a8083063 Iustin Pop
      bad = True
662 a8083063 Iustin Pop
    else:
663 8d1a2a64 Michael Hanselmann
      vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
664 8d1a2a64 Michael Hanselmann
                                            constants.MIN_VG_SIZE)
665 a8083063 Iustin Pop
      if vgstatus:
666 a8083063 Iustin Pop
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
667 a8083063 Iustin Pop
        bad = True
668 a8083063 Iustin Pop
669 a8083063 Iustin Pop
    # checks config file checksum
670 a8083063 Iustin Pop
671 25361b9a Iustin Pop
    remote_cksum = node_result.get(constants.NV_FILELIST, None)
672 25361b9a Iustin Pop
    if not isinstance(remote_cksum, dict):
673 a8083063 Iustin Pop
      bad = True
674 a8083063 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
675 a8083063 Iustin Pop
    else:
676 a8083063 Iustin Pop
      for file_name in file_list:
677 112f18a5 Iustin Pop
        node_is_mc = nodeinfo.master_candidate
678 112f18a5 Iustin Pop
        must_have_file = file_name not in master_files
679 a8083063 Iustin Pop
        if file_name not in remote_cksum:
680 112f18a5 Iustin Pop
          if node_is_mc or must_have_file:
681 112f18a5 Iustin Pop
            bad = True
682 112f18a5 Iustin Pop
            feedback_fn("  - ERROR: file '%s' missing" % file_name)
683 a8083063 Iustin Pop
        elif remote_cksum[file_name] != local_cksum[file_name]:
684 112f18a5 Iustin Pop
          if node_is_mc or must_have_file:
685 112f18a5 Iustin Pop
            bad = True
686 112f18a5 Iustin Pop
            feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
687 112f18a5 Iustin Pop
          else:
688 112f18a5 Iustin Pop
            # not candidate and this is not a must-have file
689 112f18a5 Iustin Pop
            bad = True
690 112f18a5 Iustin Pop
            feedback_fn("  - ERROR: non master-candidate has old/wrong file"
691 112f18a5 Iustin Pop
                        " '%s'" % file_name)
692 112f18a5 Iustin Pop
        else:
693 112f18a5 Iustin Pop
          # all good, except non-master/non-must have combination
694 112f18a5 Iustin Pop
          if not node_is_mc and not must_have_file:
695 112f18a5 Iustin Pop
            feedback_fn("  - ERROR: file '%s' should not exist on non master"
696 112f18a5 Iustin Pop
                        " candidates" % file_name)
697 a8083063 Iustin Pop
698 25361b9a Iustin Pop
    # checks ssh to any
699 25361b9a Iustin Pop
700 25361b9a Iustin Pop
    if constants.NV_NODELIST not in node_result:
701 a8083063 Iustin Pop
      bad = True
702 9d4bfc96 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned node ssh connectivity data")
703 a8083063 Iustin Pop
    else:
704 25361b9a Iustin Pop
      if node_result[constants.NV_NODELIST]:
705 a8083063 Iustin Pop
        bad = True
706 25361b9a Iustin Pop
        for node in node_result[constants.NV_NODELIST]:
707 9d4bfc96 Iustin Pop
          feedback_fn("  - ERROR: ssh communication with node '%s': %s" %
708 25361b9a Iustin Pop
                          (node, node_result[constants.NV_NODELIST][node]))
709 25361b9a Iustin Pop
710 25361b9a Iustin Pop
    if constants.NV_NODENETTEST not in node_result:
711 9d4bfc96 Iustin Pop
      bad = True
712 9d4bfc96 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned node tcp connectivity data")
713 9d4bfc96 Iustin Pop
    else:
714 25361b9a Iustin Pop
      if node_result[constants.NV_NODENETTEST]:
715 9d4bfc96 Iustin Pop
        bad = True
716 25361b9a Iustin Pop
        nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys())
717 9d4bfc96 Iustin Pop
        for node in nlist:
718 9d4bfc96 Iustin Pop
          feedback_fn("  - ERROR: tcp communication with node '%s': %s" %
719 25361b9a Iustin Pop
                          (node, node_result[constants.NV_NODENETTEST][node]))
720 9d4bfc96 Iustin Pop
721 25361b9a Iustin Pop
    hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
722 e69d05fd Iustin Pop
    if isinstance(hyp_result, dict):
723 e69d05fd Iustin Pop
      for hv_name, hv_result in hyp_result.iteritems():
724 e69d05fd Iustin Pop
        if hv_result is not None:
725 e69d05fd Iustin Pop
          feedback_fn("  - ERROR: hypervisor %s verify failure: '%s'" %
726 e69d05fd Iustin Pop
                      (hv_name, hv_result))
727 a8083063 Iustin Pop
    return bad
728 a8083063 Iustin Pop
729 c5705f58 Guido Trotter
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
730 0a66c968 Iustin Pop
                      node_instance, feedback_fn, n_offline):
731 a8083063 Iustin Pop
    """Verify an instance.
732 a8083063 Iustin Pop

733 a8083063 Iustin Pop
    This function checks to see if the required block devices are
734 a8083063 Iustin Pop
    available on the instance's node.
735 a8083063 Iustin Pop

736 a8083063 Iustin Pop
    """
737 a8083063 Iustin Pop
    bad = False
738 a8083063 Iustin Pop
739 a8083063 Iustin Pop
    node_current = instanceconfig.primary_node
740 a8083063 Iustin Pop
741 a8083063 Iustin Pop
    node_vol_should = {}
742 a8083063 Iustin Pop
    instanceconfig.MapLVsByNode(node_vol_should)
743 a8083063 Iustin Pop
744 a8083063 Iustin Pop
    for node in node_vol_should:
745 0a66c968 Iustin Pop
      if node in n_offline:
746 0a66c968 Iustin Pop
        # ignore missing volumes on offline nodes
747 0a66c968 Iustin Pop
        continue
748 a8083063 Iustin Pop
      for volume in node_vol_should[node]:
749 a8083063 Iustin Pop
        if node not in node_vol_is or volume not in node_vol_is[node]:
750 a8083063 Iustin Pop
          feedback_fn("  - ERROR: volume %s missing on node %s" %
751 a8083063 Iustin Pop
                          (volume, node))
752 a8083063 Iustin Pop
          bad = True
753 a8083063 Iustin Pop
754 a8083063 Iustin Pop
    if not instanceconfig.status == 'down':
755 0a66c968 Iustin Pop
      if ((node_current not in node_instance or
756 0a66c968 Iustin Pop
          not instance in node_instance[node_current]) and
757 0a66c968 Iustin Pop
          node_current not in n_offline):
758 a8083063 Iustin Pop
        feedback_fn("  - ERROR: instance %s not running on node %s" %
759 a8083063 Iustin Pop
                        (instance, node_current))
760 a8083063 Iustin Pop
        bad = True
761 a8083063 Iustin Pop
762 a8083063 Iustin Pop
    for node in node_instance:
763 a8083063 Iustin Pop
      if (not node == node_current):
764 a8083063 Iustin Pop
        if instance in node_instance[node]:
765 a8083063 Iustin Pop
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
766 a8083063 Iustin Pop
                          (instance, node))
767 a8083063 Iustin Pop
          bad = True
768 a8083063 Iustin Pop
769 6a438c98 Michael Hanselmann
    return bad
770 a8083063 Iustin Pop
771 a8083063 Iustin Pop
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
772 a8083063 Iustin Pop
    """Verify if there are any unknown volumes in the cluster.
773 a8083063 Iustin Pop

774 a8083063 Iustin Pop
    The .os, .swap and backup volumes are ignored. All other volumes are
775 a8083063 Iustin Pop
    reported as unknown.
776 a8083063 Iustin Pop

777 a8083063 Iustin Pop
    """
778 a8083063 Iustin Pop
    bad = False
779 a8083063 Iustin Pop
780 a8083063 Iustin Pop
    for node in node_vol_is:
781 a8083063 Iustin Pop
      for volume in node_vol_is[node]:
782 a8083063 Iustin Pop
        if node not in node_vol_should or volume not in node_vol_should[node]:
783 a8083063 Iustin Pop
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
784 a8083063 Iustin Pop
                      (volume, node))
785 a8083063 Iustin Pop
          bad = True
786 a8083063 Iustin Pop
    return bad
787 a8083063 Iustin Pop
788 a8083063 Iustin Pop
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
789 a8083063 Iustin Pop
    """Verify the list of running instances.
790 a8083063 Iustin Pop

791 a8083063 Iustin Pop
    This checks what instances are running but unknown to the cluster.
792 a8083063 Iustin Pop

793 a8083063 Iustin Pop
    """
794 a8083063 Iustin Pop
    bad = False
795 a8083063 Iustin Pop
    for node in node_instance:
796 a8083063 Iustin Pop
      for runninginstance in node_instance[node]:
797 a8083063 Iustin Pop
        if runninginstance not in instancelist:
798 a8083063 Iustin Pop
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
799 a8083063 Iustin Pop
                          (runninginstance, node))
800 a8083063 Iustin Pop
          bad = True
801 a8083063 Iustin Pop
    return bad
802 a8083063 Iustin Pop
803 2b3b6ddd Guido Trotter
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
804 2b3b6ddd Guido Trotter
    """Verify N+1 Memory Resilience.
805 2b3b6ddd Guido Trotter

806 2b3b6ddd Guido Trotter
    Check that if one single node dies we can still start all the instances it
807 2b3b6ddd Guido Trotter
    was primary for.
808 2b3b6ddd Guido Trotter

809 2b3b6ddd Guido Trotter
    """
810 2b3b6ddd Guido Trotter
    bad = False
811 2b3b6ddd Guido Trotter
812 2b3b6ddd Guido Trotter
    for node, nodeinfo in node_info.iteritems():
813 2b3b6ddd Guido Trotter
      # This code checks that every node which is now listed as secondary has
814 2b3b6ddd Guido Trotter
      # enough memory to host all instances it is supposed to should a single
815 2b3b6ddd Guido Trotter
      # other node in the cluster fail.
816 2b3b6ddd Guido Trotter
      # FIXME: not ready for failover to an arbitrary node
817 2b3b6ddd Guido Trotter
      # FIXME: does not support file-backed instances
818 2b3b6ddd Guido Trotter
      # WARNING: we currently take into account down instances as well as up
819 2b3b6ddd Guido Trotter
      # ones, considering that even if they're down someone might want to start
820 2b3b6ddd Guido Trotter
      # them even in the event of a node failure.
821 2b3b6ddd Guido Trotter
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
822 2b3b6ddd Guido Trotter
        needed_mem = 0
823 2b3b6ddd Guido Trotter
        for instance in instances:
824 338e51e8 Iustin Pop
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
825 c0f2b229 Iustin Pop
          if bep[constants.BE_AUTO_BALANCE]:
826 3924700f Iustin Pop
            needed_mem += bep[constants.BE_MEMORY]
827 2b3b6ddd Guido Trotter
        if nodeinfo['mfree'] < needed_mem:
828 2b3b6ddd Guido Trotter
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
829 2b3b6ddd Guido Trotter
                      " failovers should node %s fail" % (node, prinode))
830 2b3b6ddd Guido Trotter
          bad = True
831 2b3b6ddd Guido Trotter
    return bad
832 2b3b6ddd Guido Trotter
833 a8083063 Iustin Pop
  def CheckPrereq(self):
834 a8083063 Iustin Pop
    """Check prerequisites.
835 a8083063 Iustin Pop

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

839 a8083063 Iustin Pop
    """
840 e54c4c5e Guido Trotter
    self.skip_set = frozenset(self.op.skip_checks)
841 e54c4c5e Guido Trotter
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
842 e54c4c5e Guido Trotter
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
843 a8083063 Iustin Pop
844 d8fff41c Guido Trotter
  def BuildHooksEnv(self):
845 d8fff41c Guido Trotter
    """Build hooks env.
846 d8fff41c Guido Trotter

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

850 d8fff41c Guido Trotter
    """
851 d8fff41c Guido Trotter
    all_nodes = self.cfg.GetNodeList()
852 d8fff41c Guido Trotter
    # TODO: populate the environment with useful information for verify hooks
853 d8fff41c Guido Trotter
    env = {}
854 d8fff41c Guido Trotter
    return env, [], all_nodes
855 d8fff41c Guido Trotter
856 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
857 a8083063 Iustin Pop
    """Verify integrity of cluster, performing various test on nodes.
858 a8083063 Iustin Pop

859 a8083063 Iustin Pop
    """
860 a8083063 Iustin Pop
    bad = False
861 a8083063 Iustin Pop
    feedback_fn("* Verifying global settings")
862 8522ceeb Iustin Pop
    for msg in self.cfg.VerifyConfig():
863 8522ceeb Iustin Pop
      feedback_fn("  - ERROR: %s" % msg)
864 a8083063 Iustin Pop
865 a8083063 Iustin Pop
    vg_name = self.cfg.GetVGName()
866 e69d05fd Iustin Pop
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
867 a8083063 Iustin Pop
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
868 9d4bfc96 Iustin Pop
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
869 a8083063 Iustin Pop
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
870 93e4c50b Guido Trotter
    i_non_redundant = [] # Non redundant instances
871 3924700f Iustin Pop
    i_non_a_balanced = [] # Non auto-balanced instances
872 0a66c968 Iustin Pop
    n_offline = [] # List of offline nodes
873 a8083063 Iustin Pop
    node_volume = {}
874 a8083063 Iustin Pop
    node_instance = {}
875 9c9c7d30 Guido Trotter
    node_info = {}
876 26b6af5e Guido Trotter
    instance_cfg = {}
877 a8083063 Iustin Pop
878 a8083063 Iustin Pop
    # FIXME: verify OS list
879 a8083063 Iustin Pop
    # do local checksums
880 112f18a5 Iustin Pop
    master_files = [constants.CLUSTER_CONF_FILE]
881 112f18a5 Iustin Pop
882 112f18a5 Iustin Pop
    file_names = ssconf.SimpleStore().GetFileList()
883 cb91d46e Iustin Pop
    file_names.append(constants.SSL_CERT_FILE)
884 699777f2 Michael Hanselmann
    file_names.append(constants.RAPI_CERT_FILE)
885 112f18a5 Iustin Pop
    file_names.extend(master_files)
886 112f18a5 Iustin Pop
887 a8083063 Iustin Pop
    local_checksums = utils.FingerprintFiles(file_names)
888 a8083063 Iustin Pop
889 a8083063 Iustin Pop
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
890 a8083063 Iustin Pop
    node_verify_param = {
891 25361b9a Iustin Pop
      constants.NV_FILELIST: file_names,
892 82e37788 Iustin Pop
      constants.NV_NODELIST: [node.name for node in nodeinfo
893 82e37788 Iustin Pop
                              if not node.offline],
894 25361b9a Iustin Pop
      constants.NV_HYPERVISOR: hypervisors,
895 25361b9a Iustin Pop
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
896 82e37788 Iustin Pop
                                  node.secondary_ip) for node in nodeinfo
897 82e37788 Iustin Pop
                                 if not node.offline],
898 25361b9a Iustin Pop
      constants.NV_LVLIST: vg_name,
899 25361b9a Iustin Pop
      constants.NV_INSTANCELIST: hypervisors,
900 25361b9a Iustin Pop
      constants.NV_VGLIST: None,
901 25361b9a Iustin Pop
      constants.NV_VERSION: None,
902 25361b9a Iustin Pop
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
903 a8083063 Iustin Pop
      }
904 72737a7f Iustin Pop
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
905 72737a7f Iustin Pop
                                           self.cfg.GetClusterName())
906 a8083063 Iustin Pop
907 3924700f Iustin Pop
    cluster = self.cfg.GetClusterInfo()
908 112f18a5 Iustin Pop
    master_node = self.cfg.GetMasterNode()
909 112f18a5 Iustin Pop
    for node_i in nodeinfo:
910 112f18a5 Iustin Pop
      node = node_i.name
911 25361b9a Iustin Pop
      nresult = all_nvinfo[node].data
912 25361b9a Iustin Pop
913 0a66c968 Iustin Pop
      if node_i.offline:
914 0a66c968 Iustin Pop
        feedback_fn("* Skipping offline node %s" % (node,))
915 0a66c968 Iustin Pop
        n_offline.append(node)
916 0a66c968 Iustin Pop
        continue
917 0a66c968 Iustin Pop
918 112f18a5 Iustin Pop
      if node == master_node:
919 25361b9a Iustin Pop
        ntype = "master"
920 112f18a5 Iustin Pop
      elif node_i.master_candidate:
921 25361b9a Iustin Pop
        ntype = "master candidate"
922 112f18a5 Iustin Pop
      else:
923 25361b9a Iustin Pop
        ntype = "regular"
924 112f18a5 Iustin Pop
      feedback_fn("* Verifying node %s (%s)" % (node, ntype))
925 25361b9a Iustin Pop
926 25361b9a Iustin Pop
      if all_nvinfo[node].failed or not isinstance(nresult, dict):
927 25361b9a Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
928 25361b9a Iustin Pop
        bad = True
929 25361b9a Iustin Pop
        continue
930 25361b9a Iustin Pop
931 112f18a5 Iustin Pop
      result = self._VerifyNode(node_i, file_names, local_checksums,
932 25361b9a Iustin Pop
                                nresult, feedback_fn, master_files)
933 a8083063 Iustin Pop
      bad = bad or result
934 a8083063 Iustin Pop
935 25361b9a Iustin Pop
      lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
936 25361b9a Iustin Pop
      if isinstance(lvdata, basestring):
937 b63ed789 Iustin Pop
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
938 25361b9a Iustin Pop
                    (node, lvdata.encode('string_escape')))
939 b63ed789 Iustin Pop
        bad = True
940 b63ed789 Iustin Pop
        node_volume[node] = {}
941 25361b9a Iustin Pop
      elif not isinstance(lvdata, dict):
942 25361b9a Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed (lvlist)" % (node,))
943 a8083063 Iustin Pop
        bad = True
944 a8083063 Iustin Pop
        continue
945 b63ed789 Iustin Pop
      else:
946 25361b9a Iustin Pop
        node_volume[node] = lvdata
947 a8083063 Iustin Pop
948 a8083063 Iustin Pop
      # node_instance
949 25361b9a Iustin Pop
      idata = nresult.get(constants.NV_INSTANCELIST, None)
950 25361b9a Iustin Pop
      if not isinstance(idata, list):
951 25361b9a Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed (instancelist)" %
952 25361b9a Iustin Pop
                    (node,))
953 a8083063 Iustin Pop
        bad = True
954 a8083063 Iustin Pop
        continue
955 a8083063 Iustin Pop
956 25361b9a Iustin Pop
      node_instance[node] = idata
957 a8083063 Iustin Pop
958 9c9c7d30 Guido Trotter
      # node_info
959 25361b9a Iustin Pop
      nodeinfo = nresult.get(constants.NV_HVINFO, None)
960 9c9c7d30 Guido Trotter
      if not isinstance(nodeinfo, dict):
961 25361b9a Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed (hvinfo)" % (node,))
962 9c9c7d30 Guido Trotter
        bad = True
963 9c9c7d30 Guido Trotter
        continue
964 9c9c7d30 Guido Trotter
965 9c9c7d30 Guido Trotter
      try:
966 9c9c7d30 Guido Trotter
        node_info[node] = {
967 9c9c7d30 Guido Trotter
          "mfree": int(nodeinfo['memory_free']),
968 25361b9a Iustin Pop
          "dfree": int(nresult[constants.NV_VGLIST][vg_name]),
969 93e4c50b Guido Trotter
          "pinst": [],
970 93e4c50b Guido Trotter
          "sinst": [],
971 36e7da50 Guido Trotter
          # dictionary holding all instances this node is secondary for,
972 36e7da50 Guido Trotter
          # grouped by their primary node. Each key is a cluster node, and each
973 36e7da50 Guido Trotter
          # value is a list of instances which have the key as primary and the
974 36e7da50 Guido Trotter
          # current node as secondary.  this is handy to calculate N+1 memory
975 36e7da50 Guido Trotter
          # availability if you can only failover from a primary to its
976 36e7da50 Guido Trotter
          # secondary.
977 36e7da50 Guido Trotter
          "sinst-by-pnode": {},
978 9c9c7d30 Guido Trotter
        }
979 9c9c7d30 Guido Trotter
      except ValueError:
980 9c9c7d30 Guido Trotter
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
981 9c9c7d30 Guido Trotter
        bad = True
982 9c9c7d30 Guido Trotter
        continue
983 9c9c7d30 Guido Trotter
984 a8083063 Iustin Pop
    node_vol_should = {}
985 a8083063 Iustin Pop
986 a8083063 Iustin Pop
    for instance in instancelist:
987 a8083063 Iustin Pop
      feedback_fn("* Verifying instance %s" % instance)
988 a8083063 Iustin Pop
      inst_config = self.cfg.GetInstanceInfo(instance)
989 c5705f58 Guido Trotter
      result =  self._VerifyInstance(instance, inst_config, node_volume,
990 0a66c968 Iustin Pop
                                     node_instance, feedback_fn, n_offline)
991 c5705f58 Guido Trotter
      bad = bad or result
992 832261fd Iustin Pop
      inst_nodes_offline = []
993 a8083063 Iustin Pop
994 a8083063 Iustin Pop
      inst_config.MapLVsByNode(node_vol_should)
995 a8083063 Iustin Pop
996 26b6af5e Guido Trotter
      instance_cfg[instance] = inst_config
997 26b6af5e Guido Trotter
998 93e4c50b Guido Trotter
      pnode = inst_config.primary_node
999 93e4c50b Guido Trotter
      if pnode in node_info:
1000 93e4c50b Guido Trotter
        node_info[pnode]['pinst'].append(instance)
1001 0a66c968 Iustin Pop
      elif pnode not in n_offline:
1002 93e4c50b Guido Trotter
        feedback_fn("  - ERROR: instance %s, connection to primary node"
1003 93e4c50b Guido Trotter
                    " %s failed" % (instance, pnode))
1004 93e4c50b Guido Trotter
        bad = True
1005 93e4c50b Guido Trotter
1006 832261fd Iustin Pop
      if pnode in n_offline:
1007 832261fd Iustin Pop
        inst_nodes_offline.append(pnode)
1008 832261fd Iustin Pop
1009 93e4c50b Guido Trotter
      # If the instance is non-redundant we cannot survive losing its primary
1010 93e4c50b Guido Trotter
      # node, so we are not N+1 compliant. On the other hand we have no disk
1011 93e4c50b Guido Trotter
      # templates with more than one secondary so that situation is not well
1012 93e4c50b Guido Trotter
      # supported either.
1013 93e4c50b Guido Trotter
      # FIXME: does not support file-backed instances
1014 93e4c50b Guido Trotter
      if len(inst_config.secondary_nodes) == 0:
1015 93e4c50b Guido Trotter
        i_non_redundant.append(instance)
1016 93e4c50b Guido Trotter
      elif len(inst_config.secondary_nodes) > 1:
1017 93e4c50b Guido Trotter
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
1018 93e4c50b Guido Trotter
                    % instance)
1019 93e4c50b Guido Trotter
1020 c0f2b229 Iustin Pop
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1021 3924700f Iustin Pop
        i_non_a_balanced.append(instance)
1022 3924700f Iustin Pop
1023 93e4c50b Guido Trotter
      for snode in inst_config.secondary_nodes:
1024 93e4c50b Guido Trotter
        if snode in node_info:
1025 93e4c50b Guido Trotter
          node_info[snode]['sinst'].append(instance)
1026 36e7da50 Guido Trotter
          if pnode not in node_info[snode]['sinst-by-pnode']:
1027 36e7da50 Guido Trotter
            node_info[snode]['sinst-by-pnode'][pnode] = []
1028 36e7da50 Guido Trotter
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
1029 0a66c968 Iustin Pop
        elif snode not in n_offline:
1030 93e4c50b Guido Trotter
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
1031 93e4c50b Guido Trotter
                      " %s failed" % (instance, snode))
1032 832261fd Iustin Pop
          bad = True
1033 832261fd Iustin Pop
        if snode in n_offline:
1034 832261fd Iustin Pop
          inst_nodes_offline.append(snode)
1035 832261fd Iustin Pop
1036 832261fd Iustin Pop
      if inst_nodes_offline:
1037 832261fd Iustin Pop
        # warn that the instance lives on offline nodes, and set bad=True
1038 832261fd Iustin Pop
        feedback_fn("  - ERROR: instance lives on offline node(s) %s" %
1039 832261fd Iustin Pop
                    ", ".join(inst_nodes_offline))
1040 832261fd Iustin Pop
        bad = True
1041 93e4c50b Guido Trotter
1042 a8083063 Iustin Pop
    feedback_fn("* Verifying orphan volumes")
1043 a8083063 Iustin Pop
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
1044 a8083063 Iustin Pop
                                       feedback_fn)
1045 a8083063 Iustin Pop
    bad = bad or result
1046 a8083063 Iustin Pop
1047 a8083063 Iustin Pop
    feedback_fn("* Verifying remaining instances")
1048 a8083063 Iustin Pop
    result = self._VerifyOrphanInstances(instancelist, node_instance,
1049 a8083063 Iustin Pop
                                         feedback_fn)
1050 a8083063 Iustin Pop
    bad = bad or result
1051 a8083063 Iustin Pop
1052 e54c4c5e Guido Trotter
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1053 e54c4c5e Guido Trotter
      feedback_fn("* Verifying N+1 Memory redundancy")
1054 e54c4c5e Guido Trotter
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
1055 e54c4c5e Guido Trotter
      bad = bad or result
1056 2b3b6ddd Guido Trotter
1057 2b3b6ddd Guido Trotter
    feedback_fn("* Other Notes")
1058 2b3b6ddd Guido Trotter
    if i_non_redundant:
1059 2b3b6ddd Guido Trotter
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1060 2b3b6ddd Guido Trotter
                  % len(i_non_redundant))
1061 2b3b6ddd Guido Trotter
1062 3924700f Iustin Pop
    if i_non_a_balanced:
1063 3924700f Iustin Pop
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1064 3924700f Iustin Pop
                  % len(i_non_a_balanced))
1065 3924700f Iustin Pop
1066 0a66c968 Iustin Pop
    if n_offline:
1067 0a66c968 Iustin Pop
      feedback_fn("  - NOTICE: %d offline node(s) found." % len(n_offline))
1068 0a66c968 Iustin Pop
1069 34290825 Michael Hanselmann
    return not bad
1070 a8083063 Iustin Pop
1071 d8fff41c Guido Trotter
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1072 e4376078 Iustin Pop
    """Analize the post-hooks' result
1073 e4376078 Iustin Pop

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

1077 e4376078 Iustin Pop
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1078 e4376078 Iustin Pop
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1079 e4376078 Iustin Pop
    @param hooks_results: the results of the multi-node hooks rpc call
1080 e4376078 Iustin Pop
    @param feedback_fn: function used send feedback back to the caller
1081 e4376078 Iustin Pop
    @param lu_result: previous Exec result
1082 e4376078 Iustin Pop
    @return: the new Exec result, based on the previous result
1083 e4376078 Iustin Pop
        and hook results
1084 d8fff41c Guido Trotter

1085 d8fff41c Guido Trotter
    """
1086 38206f3c Iustin Pop
    # We only really run POST phase hooks, and are only interested in
1087 38206f3c Iustin Pop
    # their results
1088 d8fff41c Guido Trotter
    if phase == constants.HOOKS_PHASE_POST:
1089 d8fff41c Guido Trotter
      # Used to change hooks' output to proper indentation
1090 d8fff41c Guido Trotter
      indent_re = re.compile('^', re.M)
1091 d8fff41c Guido Trotter
      feedback_fn("* Hooks Results")
1092 d8fff41c Guido Trotter
      if not hooks_results:
1093 d8fff41c Guido Trotter
        feedback_fn("  - ERROR: general communication failure")
1094 d8fff41c Guido Trotter
        lu_result = 1
1095 d8fff41c Guido Trotter
      else:
1096 d8fff41c Guido Trotter
        for node_name in hooks_results:
1097 d8fff41c Guido Trotter
          show_node_header = True
1098 d8fff41c Guido Trotter
          res = hooks_results[node_name]
1099 25361b9a Iustin Pop
          if res.failed or res.data is False or not isinstance(res.data, list):
1100 0a66c968 Iustin Pop
            if res.offline:
1101 0a66c968 Iustin Pop
              # no need to warn or set fail return value
1102 0a66c968 Iustin Pop
              continue
1103 25361b9a Iustin Pop
            feedback_fn("    Communication failure in hooks execution")
1104 d8fff41c Guido Trotter
            lu_result = 1
1105 d8fff41c Guido Trotter
            continue
1106 25361b9a Iustin Pop
          for script, hkr, output in res.data:
1107 d8fff41c Guido Trotter
            if hkr == constants.HKR_FAIL:
1108 d8fff41c Guido Trotter
              # The node header is only shown once, if there are
1109 d8fff41c Guido Trotter
              # failing hooks on that node
1110 d8fff41c Guido Trotter
              if show_node_header:
1111 d8fff41c Guido Trotter
                feedback_fn("  Node %s:" % node_name)
1112 d8fff41c Guido Trotter
                show_node_header = False
1113 d8fff41c Guido Trotter
              feedback_fn("    ERROR: Script %s failed, output:" % script)
1114 d8fff41c Guido Trotter
              output = indent_re.sub('      ', output)
1115 d8fff41c Guido Trotter
              feedback_fn("%s" % output)
1116 d8fff41c Guido Trotter
              lu_result = 1
1117 d8fff41c Guido Trotter
1118 d8fff41c Guido Trotter
      return lu_result
1119 d8fff41c Guido Trotter
1120 a8083063 Iustin Pop
1121 2c95a8d4 Iustin Pop
class LUVerifyDisks(NoHooksLU):
1122 2c95a8d4 Iustin Pop
  """Verifies the cluster disks status.
1123 2c95a8d4 Iustin Pop

1124 2c95a8d4 Iustin Pop
  """
1125 2c95a8d4 Iustin Pop
  _OP_REQP = []
1126 d4b9d97f Guido Trotter
  REQ_BGL = False
1127 d4b9d97f Guido Trotter
1128 d4b9d97f Guido Trotter
  def ExpandNames(self):
1129 d4b9d97f Guido Trotter
    self.needed_locks = {
1130 d4b9d97f Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
1131 d4b9d97f Guido Trotter
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1132 d4b9d97f Guido Trotter
    }
1133 d4b9d97f Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
1134 2c95a8d4 Iustin Pop
1135 2c95a8d4 Iustin Pop
  def CheckPrereq(self):
1136 2c95a8d4 Iustin Pop
    """Check prerequisites.
1137 2c95a8d4 Iustin Pop

1138 2c95a8d4 Iustin Pop
    This has no prerequisites.
1139 2c95a8d4 Iustin Pop

1140 2c95a8d4 Iustin Pop
    """
1141 2c95a8d4 Iustin Pop
    pass
1142 2c95a8d4 Iustin Pop
1143 2c95a8d4 Iustin Pop
  def Exec(self, feedback_fn):
1144 2c95a8d4 Iustin Pop
    """Verify integrity of cluster disks.
1145 2c95a8d4 Iustin Pop

1146 2c95a8d4 Iustin Pop
    """
1147 b63ed789 Iustin Pop
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
1148 2c95a8d4 Iustin Pop
1149 2c95a8d4 Iustin Pop
    vg_name = self.cfg.GetVGName()
1150 2c95a8d4 Iustin Pop
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1151 2c95a8d4 Iustin Pop
    instances = [self.cfg.GetInstanceInfo(name)
1152 2c95a8d4 Iustin Pop
                 for name in self.cfg.GetInstanceList()]
1153 2c95a8d4 Iustin Pop
1154 2c95a8d4 Iustin Pop
    nv_dict = {}
1155 2c95a8d4 Iustin Pop
    for inst in instances:
1156 2c95a8d4 Iustin Pop
      inst_lvs = {}
1157 2c95a8d4 Iustin Pop
      if (inst.status != "up" or
1158 2c95a8d4 Iustin Pop
          inst.disk_template not in constants.DTS_NET_MIRROR):
1159 2c95a8d4 Iustin Pop
        continue
1160 2c95a8d4 Iustin Pop
      inst.MapLVsByNode(inst_lvs)
1161 2c95a8d4 Iustin Pop
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1162 2c95a8d4 Iustin Pop
      for node, vol_list in inst_lvs.iteritems():
1163 2c95a8d4 Iustin Pop
        for vol in vol_list:
1164 2c95a8d4 Iustin Pop
          nv_dict[(node, vol)] = inst
1165 2c95a8d4 Iustin Pop
1166 2c95a8d4 Iustin Pop
    if not nv_dict:
1167 2c95a8d4 Iustin Pop
      return result
1168 2c95a8d4 Iustin Pop
1169 72737a7f Iustin Pop
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
1170 2c95a8d4 Iustin Pop
1171 2c95a8d4 Iustin Pop
    to_act = set()
1172 2c95a8d4 Iustin Pop
    for node in nodes:
1173 2c95a8d4 Iustin Pop
      # node_volume
1174 2c95a8d4 Iustin Pop
      lvs = node_lvs[node]
1175 781de953 Iustin Pop
      if lvs.failed:
1176 0a66c968 Iustin Pop
        if not lvs.offline:
1177 0a66c968 Iustin Pop
          self.LogWarning("Connection to node %s failed: %s" %
1178 0a66c968 Iustin Pop
                          (node, lvs.data))
1179 781de953 Iustin Pop
        continue
1180 781de953 Iustin Pop
      lvs = lvs.data
1181 b63ed789 Iustin Pop
      if isinstance(lvs, basestring):
1182 9a4f63d1 Iustin Pop
        logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
1183 b63ed789 Iustin Pop
        res_nlvm[node] = lvs
1184 b63ed789 Iustin Pop
      elif not isinstance(lvs, dict):
1185 9a4f63d1 Iustin Pop
        logging.warning("Connection to node %s failed or invalid data"
1186 9a4f63d1 Iustin Pop
                        " returned", node)
1187 2c95a8d4 Iustin Pop
        res_nodes.append(node)
1188 2c95a8d4 Iustin Pop
        continue
1189 2c95a8d4 Iustin Pop
1190 2c95a8d4 Iustin Pop
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1191 b63ed789 Iustin Pop
        inst = nv_dict.pop((node, lv_name), None)
1192 b63ed789 Iustin Pop
        if (not lv_online and inst is not None
1193 b63ed789 Iustin Pop
            and inst.name not in res_instances):
1194 b08d5a87 Iustin Pop
          res_instances.append(inst.name)
1195 2c95a8d4 Iustin Pop
1196 b63ed789 Iustin Pop
    # any leftover items in nv_dict are missing LVs, let's arrange the
1197 b63ed789 Iustin Pop
    # data better
1198 b63ed789 Iustin Pop
    for key, inst in nv_dict.iteritems():
1199 b63ed789 Iustin Pop
      if inst.name not in res_missing:
1200 b63ed789 Iustin Pop
        res_missing[inst.name] = []
1201 b63ed789 Iustin Pop
      res_missing[inst.name].append(key)
1202 b63ed789 Iustin Pop
1203 2c95a8d4 Iustin Pop
    return result
1204 2c95a8d4 Iustin Pop
1205 2c95a8d4 Iustin Pop
1206 07bd8a51 Iustin Pop
class LURenameCluster(LogicalUnit):
1207 07bd8a51 Iustin Pop
  """Rename the cluster.
1208 07bd8a51 Iustin Pop

1209 07bd8a51 Iustin Pop
  """
1210 07bd8a51 Iustin Pop
  HPATH = "cluster-rename"
1211 07bd8a51 Iustin Pop
  HTYPE = constants.HTYPE_CLUSTER
1212 07bd8a51 Iustin Pop
  _OP_REQP = ["name"]
1213 07bd8a51 Iustin Pop
1214 07bd8a51 Iustin Pop
  def BuildHooksEnv(self):
1215 07bd8a51 Iustin Pop
    """Build hooks env.
1216 07bd8a51 Iustin Pop

1217 07bd8a51 Iustin Pop
    """
1218 07bd8a51 Iustin Pop
    env = {
1219 d6a02168 Michael Hanselmann
      "OP_TARGET": self.cfg.GetClusterName(),
1220 07bd8a51 Iustin Pop
      "NEW_NAME": self.op.name,
1221 07bd8a51 Iustin Pop
      }
1222 d6a02168 Michael Hanselmann
    mn = self.cfg.GetMasterNode()
1223 07bd8a51 Iustin Pop
    return env, [mn], [mn]
1224 07bd8a51 Iustin Pop
1225 07bd8a51 Iustin Pop
  def CheckPrereq(self):
1226 07bd8a51 Iustin Pop
    """Verify that the passed name is a valid one.
1227 07bd8a51 Iustin Pop

1228 07bd8a51 Iustin Pop
    """
1229 89e1fc26 Iustin Pop
    hostname = utils.HostInfo(self.op.name)
1230 07bd8a51 Iustin Pop
1231 bcf043c9 Iustin Pop
    new_name = hostname.name
1232 bcf043c9 Iustin Pop
    self.ip = new_ip = hostname.ip
1233 d6a02168 Michael Hanselmann
    old_name = self.cfg.GetClusterName()
1234 d6a02168 Michael Hanselmann
    old_ip = self.cfg.GetMasterIP()
1235 07bd8a51 Iustin Pop
    if new_name == old_name and new_ip == old_ip:
1236 07bd8a51 Iustin Pop
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1237 07bd8a51 Iustin Pop
                                 " cluster has changed")
1238 07bd8a51 Iustin Pop
    if new_ip != old_ip:
1239 937f983d Guido Trotter
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1240 07bd8a51 Iustin Pop
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1241 07bd8a51 Iustin Pop
                                   " reachable on the network. Aborting." %
1242 07bd8a51 Iustin Pop
                                   new_ip)
1243 07bd8a51 Iustin Pop
1244 07bd8a51 Iustin Pop
    self.op.name = new_name
1245 07bd8a51 Iustin Pop
1246 07bd8a51 Iustin Pop
  def Exec(self, feedback_fn):
1247 07bd8a51 Iustin Pop
    """Rename the cluster.
1248 07bd8a51 Iustin Pop

1249 07bd8a51 Iustin Pop
    """
1250 07bd8a51 Iustin Pop
    clustername = self.op.name
1251 07bd8a51 Iustin Pop
    ip = self.ip
1252 07bd8a51 Iustin Pop
1253 07bd8a51 Iustin Pop
    # shutdown the master IP
1254 d6a02168 Michael Hanselmann
    master = self.cfg.GetMasterNode()
1255 781de953 Iustin Pop
    result = self.rpc.call_node_stop_master(master, False)
1256 781de953 Iustin Pop
    if result.failed or not result.data:
1257 07bd8a51 Iustin Pop
      raise errors.OpExecError("Could not disable the master role")
1258 07bd8a51 Iustin Pop
1259 07bd8a51 Iustin Pop
    try:
1260 55cf7d83 Iustin Pop
      cluster = self.cfg.GetClusterInfo()
1261 55cf7d83 Iustin Pop
      cluster.cluster_name = clustername
1262 55cf7d83 Iustin Pop
      cluster.master_ip = ip
1263 55cf7d83 Iustin Pop
      self.cfg.Update(cluster)
1264 ec85e3d5 Iustin Pop
1265 ec85e3d5 Iustin Pop
      # update the known hosts file
1266 ec85e3d5 Iustin Pop
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
1267 ec85e3d5 Iustin Pop
      node_list = self.cfg.GetNodeList()
1268 ec85e3d5 Iustin Pop
      try:
1269 ec85e3d5 Iustin Pop
        node_list.remove(master)
1270 ec85e3d5 Iustin Pop
      except ValueError:
1271 ec85e3d5 Iustin Pop
        pass
1272 ec85e3d5 Iustin Pop
      result = self.rpc.call_upload_file(node_list,
1273 ec85e3d5 Iustin Pop
                                         constants.SSH_KNOWN_HOSTS_FILE)
1274 ec85e3d5 Iustin Pop
      for to_node, to_result in result.iteritems():
1275 ec85e3d5 Iustin Pop
        if to_result.failed or not to_result.data:
1276 d1dc3548 Iustin Pop
          logging.error("Copy of file %s to node %s failed",
1277 d1dc3548 Iustin Pop
                        constants.SSH_KNOWN_HOSTS_FILE, to_node)
1278 ec85e3d5 Iustin Pop
1279 07bd8a51 Iustin Pop
    finally:
1280 781de953 Iustin Pop
      result = self.rpc.call_node_start_master(master, False)
1281 781de953 Iustin Pop
      if result.failed or not result.data:
1282 86d9d3bb Iustin Pop
        self.LogWarning("Could not re-enable the master role on"
1283 86d9d3bb Iustin Pop
                        " the master, please restart manually.")
1284 07bd8a51 Iustin Pop
1285 07bd8a51 Iustin Pop
1286 8084f9f6 Manuel Franceschini
def _RecursiveCheckIfLVMBased(disk):
1287 8084f9f6 Manuel Franceschini
  """Check if the given disk or its children are lvm-based.
1288 8084f9f6 Manuel Franceschini

1289 e4376078 Iustin Pop
  @type disk: L{objects.Disk}
1290 e4376078 Iustin Pop
  @param disk: the disk to check
1291 e4376078 Iustin Pop
  @rtype: booleean
1292 e4376078 Iustin Pop
  @return: boolean indicating whether a LD_LV dev_type was found or not
1293 8084f9f6 Manuel Franceschini

1294 8084f9f6 Manuel Franceschini
  """
1295 8084f9f6 Manuel Franceschini
  if disk.children:
1296 8084f9f6 Manuel Franceschini
    for chdisk in disk.children:
1297 8084f9f6 Manuel Franceschini
      if _RecursiveCheckIfLVMBased(chdisk):
1298 8084f9f6 Manuel Franceschini
        return True
1299 8084f9f6 Manuel Franceschini
  return disk.dev_type == constants.LD_LV
1300 8084f9f6 Manuel Franceschini
1301 8084f9f6 Manuel Franceschini
1302 8084f9f6 Manuel Franceschini
class LUSetClusterParams(LogicalUnit):
1303 8084f9f6 Manuel Franceschini
  """Change the parameters of the cluster.
1304 8084f9f6 Manuel Franceschini

1305 8084f9f6 Manuel Franceschini
  """
1306 8084f9f6 Manuel Franceschini
  HPATH = "cluster-modify"
1307 8084f9f6 Manuel Franceschini
  HTYPE = constants.HTYPE_CLUSTER
1308 8084f9f6 Manuel Franceschini
  _OP_REQP = []
1309 c53279cf Guido Trotter
  REQ_BGL = False
1310 c53279cf Guido Trotter
1311 4b7735f9 Iustin Pop
  def CheckParameters(self):
1312 4b7735f9 Iustin Pop
    """Check parameters
1313 4b7735f9 Iustin Pop

1314 4b7735f9 Iustin Pop
    """
1315 4b7735f9 Iustin Pop
    if not hasattr(self.op, "candidate_pool_size"):
1316 4b7735f9 Iustin Pop
      self.op.candidate_pool_size = None
1317 4b7735f9 Iustin Pop
    if self.op.candidate_pool_size is not None:
1318 4b7735f9 Iustin Pop
      try:
1319 4b7735f9 Iustin Pop
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
1320 4b7735f9 Iustin Pop
      except ValueError, err:
1321 4b7735f9 Iustin Pop
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
1322 4b7735f9 Iustin Pop
                                   str(err))
1323 4b7735f9 Iustin Pop
      if self.op.candidate_pool_size < 1:
1324 4b7735f9 Iustin Pop
        raise errors.OpPrereqError("At least one master candidate needed")
1325 4b7735f9 Iustin Pop
1326 c53279cf Guido Trotter
  def ExpandNames(self):
1327 c53279cf Guido Trotter
    # FIXME: in the future maybe other cluster params won't require checking on
1328 c53279cf Guido Trotter
    # all nodes to be modified.
1329 c53279cf Guido Trotter
    self.needed_locks = {
1330 c53279cf Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
1331 c53279cf Guido Trotter
    }
1332 c53279cf Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1333 8084f9f6 Manuel Franceschini
1334 8084f9f6 Manuel Franceschini
  def BuildHooksEnv(self):
1335 8084f9f6 Manuel Franceschini
    """Build hooks env.
1336 8084f9f6 Manuel Franceschini

1337 8084f9f6 Manuel Franceschini
    """
1338 8084f9f6 Manuel Franceschini
    env = {
1339 d6a02168 Michael Hanselmann
      "OP_TARGET": self.cfg.GetClusterName(),
1340 8084f9f6 Manuel Franceschini
      "NEW_VG_NAME": self.op.vg_name,
1341 8084f9f6 Manuel Franceschini
      }
1342 d6a02168 Michael Hanselmann
    mn = self.cfg.GetMasterNode()
1343 8084f9f6 Manuel Franceschini
    return env, [mn], [mn]
1344 8084f9f6 Manuel Franceschini
1345 8084f9f6 Manuel Franceschini
  def CheckPrereq(self):
1346 8084f9f6 Manuel Franceschini
    """Check prerequisites.
1347 8084f9f6 Manuel Franceschini

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

1351 8084f9f6 Manuel Franceschini
    """
1352 c53279cf Guido Trotter
    # FIXME: This only works because there is only one parameter that can be
1353 c53279cf Guido Trotter
    # changed or removed.
1354 779c15bb Iustin Pop
    if self.op.vg_name is not None and not self.op.vg_name:
1355 c53279cf Guido Trotter
      instances = self.cfg.GetAllInstancesInfo().values()
1356 8084f9f6 Manuel Franceschini
      for inst in instances:
1357 8084f9f6 Manuel Franceschini
        for disk in inst.disks:
1358 8084f9f6 Manuel Franceschini
          if _RecursiveCheckIfLVMBased(disk):
1359 8084f9f6 Manuel Franceschini
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1360 8084f9f6 Manuel Franceschini
                                       " lvm-based instances exist")
1361 8084f9f6 Manuel Franceschini
1362 779c15bb Iustin Pop
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1363 779c15bb Iustin Pop
1364 8084f9f6 Manuel Franceschini
    # if vg_name not None, checks given volume group on all nodes
1365 8084f9f6 Manuel Franceschini
    if self.op.vg_name:
1366 72737a7f Iustin Pop
      vglist = self.rpc.call_vg_list(node_list)
1367 8084f9f6 Manuel Franceschini
      for node in node_list:
1368 781de953 Iustin Pop
        if vglist[node].failed:
1369 781de953 Iustin Pop
          # ignoring down node
1370 781de953 Iustin Pop
          self.LogWarning("Node %s unreachable/error, ignoring" % node)
1371 781de953 Iustin Pop
          continue
1372 781de953 Iustin Pop
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].data,
1373 781de953 Iustin Pop
                                              self.op.vg_name,
1374 8d1a2a64 Michael Hanselmann
                                              constants.MIN_VG_SIZE)
1375 8084f9f6 Manuel Franceschini
        if vgstatus:
1376 8084f9f6 Manuel Franceschini
          raise errors.OpPrereqError("Error on node '%s': %s" %
1377 8084f9f6 Manuel Franceschini
                                     (node, vgstatus))
1378 8084f9f6 Manuel Franceschini
1379 779c15bb Iustin Pop
    self.cluster = cluster = self.cfg.GetClusterInfo()
1380 d4b72030 Guido Trotter
    # validate beparams changes
1381 779c15bb Iustin Pop
    if self.op.beparams:
1382 d4b72030 Guido Trotter
      utils.CheckBEParams(self.op.beparams)
1383 779c15bb Iustin Pop
      self.new_beparams = cluster.FillDict(
1384 779c15bb Iustin Pop
        cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
1385 779c15bb Iustin Pop
1386 779c15bb Iustin Pop
    # hypervisor list/parameters
1387 779c15bb Iustin Pop
    self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
1388 779c15bb Iustin Pop
    if self.op.hvparams:
1389 779c15bb Iustin Pop
      if not isinstance(self.op.hvparams, dict):
1390 779c15bb Iustin Pop
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input")
1391 779c15bb Iustin Pop
      for hv_name, hv_dict in self.op.hvparams.items():
1392 779c15bb Iustin Pop
        if hv_name not in self.new_hvparams:
1393 779c15bb Iustin Pop
          self.new_hvparams[hv_name] = hv_dict
1394 779c15bb Iustin Pop
        else:
1395 779c15bb Iustin Pop
          self.new_hvparams[hv_name].update(hv_dict)
1396 779c15bb Iustin Pop
1397 779c15bb Iustin Pop
    if self.op.enabled_hypervisors is not None:
1398 779c15bb Iustin Pop
      self.hv_list = self.op.enabled_hypervisors
1399 779c15bb Iustin Pop
    else:
1400 779c15bb Iustin Pop
      self.hv_list = cluster.enabled_hypervisors
1401 779c15bb Iustin Pop
1402 779c15bb Iustin Pop
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
1403 779c15bb Iustin Pop
      # either the enabled list has changed, or the parameters have, validate
1404 779c15bb Iustin Pop
      for hv_name, hv_params in self.new_hvparams.items():
1405 779c15bb Iustin Pop
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
1406 779c15bb Iustin Pop
            (self.op.enabled_hypervisors and
1407 779c15bb Iustin Pop
             hv_name in self.op.enabled_hypervisors)):
1408 779c15bb Iustin Pop
          # either this is a new hypervisor, or its parameters have changed
1409 779c15bb Iustin Pop
          hv_class = hypervisor.GetHypervisor(hv_name)
1410 779c15bb Iustin Pop
          hv_class.CheckParameterSyntax(hv_params)
1411 779c15bb Iustin Pop
          _CheckHVParams(self, node_list, hv_name, hv_params)
1412 779c15bb Iustin Pop
1413 8084f9f6 Manuel Franceschini
  def Exec(self, feedback_fn):
1414 8084f9f6 Manuel Franceschini
    """Change the parameters of the cluster.
1415 8084f9f6 Manuel Franceschini

1416 8084f9f6 Manuel Franceschini
    """
1417 779c15bb Iustin Pop
    if self.op.vg_name is not None:
1418 779c15bb Iustin Pop
      if self.op.vg_name != self.cfg.GetVGName():
1419 779c15bb Iustin Pop
        self.cfg.SetVGName(self.op.vg_name)
1420 779c15bb Iustin Pop
      else:
1421 779c15bb Iustin Pop
        feedback_fn("Cluster LVM configuration already in desired"
1422 779c15bb Iustin Pop
                    " state, not changing")
1423 779c15bb Iustin Pop
    if self.op.hvparams:
1424 779c15bb Iustin Pop
      self.cluster.hvparams = self.new_hvparams
1425 779c15bb Iustin Pop
    if self.op.enabled_hypervisors is not None:
1426 779c15bb Iustin Pop
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
1427 779c15bb Iustin Pop
    if self.op.beparams:
1428 779c15bb Iustin Pop
      self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams
1429 4b7735f9 Iustin Pop
    if self.op.candidate_pool_size is not None:
1430 4b7735f9 Iustin Pop
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
1431 4b7735f9 Iustin Pop
1432 779c15bb Iustin Pop
    self.cfg.Update(self.cluster)
1433 8084f9f6 Manuel Franceschini
1434 4b7735f9 Iustin Pop
    # we want to update nodes after the cluster so that if any errors
1435 4b7735f9 Iustin Pop
    # happen, we have recorded and saved the cluster info
1436 4b7735f9 Iustin Pop
    if self.op.candidate_pool_size is not None:
1437 ec0292f1 Iustin Pop
      _AdjustCandidatePool(self)
1438 4b7735f9 Iustin Pop
1439 8084f9f6 Manuel Franceschini
1440 afee0879 Iustin Pop
class LURedistributeConfig(NoHooksLU):
1441 afee0879 Iustin Pop
  """Force the redistribution of cluster configuration.
1442 afee0879 Iustin Pop

1443 afee0879 Iustin Pop
  This is a very simple LU.
1444 afee0879 Iustin Pop

1445 afee0879 Iustin Pop
  """
1446 afee0879 Iustin Pop
  _OP_REQP = []
1447 afee0879 Iustin Pop
  REQ_BGL = False
1448 afee0879 Iustin Pop
1449 afee0879 Iustin Pop
  def ExpandNames(self):
1450 afee0879 Iustin Pop
    self.needed_locks = {
1451 afee0879 Iustin Pop
      locking.LEVEL_NODE: locking.ALL_SET,
1452 afee0879 Iustin Pop
    }
1453 afee0879 Iustin Pop
    self.share_locks[locking.LEVEL_NODE] = 1
1454 afee0879 Iustin Pop
1455 afee0879 Iustin Pop
  def CheckPrereq(self):
1456 afee0879 Iustin Pop
    """Check prerequisites.
1457 afee0879 Iustin Pop

1458 afee0879 Iustin Pop
    """
1459 afee0879 Iustin Pop
1460 afee0879 Iustin Pop
  def Exec(self, feedback_fn):
1461 afee0879 Iustin Pop
    """Redistribute the configuration.
1462 afee0879 Iustin Pop

1463 afee0879 Iustin Pop
    """
1464 afee0879 Iustin Pop
    self.cfg.Update(self.cfg.GetClusterInfo())
1465 afee0879 Iustin Pop
1466 afee0879 Iustin Pop
1467 b9bddb6b Iustin Pop
def _WaitForSync(lu, instance, oneshot=False, unlock=False):
1468 a8083063 Iustin Pop
  """Sleep and poll for an instance's disk to sync.
1469 a8083063 Iustin Pop

1470 a8083063 Iustin Pop
  """
1471 a8083063 Iustin Pop
  if not instance.disks:
1472 a8083063 Iustin Pop
    return True
1473 a8083063 Iustin Pop
1474 a8083063 Iustin Pop
  if not oneshot:
1475 b9bddb6b Iustin Pop
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1476 a8083063 Iustin Pop
1477 a8083063 Iustin Pop
  node = instance.primary_node
1478 a8083063 Iustin Pop
1479 a8083063 Iustin Pop
  for dev in instance.disks:
1480 b9bddb6b Iustin Pop
    lu.cfg.SetDiskID(dev, node)
1481 a8083063 Iustin Pop
1482 a8083063 Iustin Pop
  retries = 0
1483 a8083063 Iustin Pop
  while True:
1484 a8083063 Iustin Pop
    max_time = 0
1485 a8083063 Iustin Pop
    done = True
1486 a8083063 Iustin Pop
    cumul_degraded = False
1487 72737a7f Iustin Pop
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1488 781de953 Iustin Pop
    if rstats.failed or not rstats.data:
1489 86d9d3bb Iustin Pop
      lu.LogWarning("Can't get any data from node %s", node)
1490 a8083063 Iustin Pop
      retries += 1
1491 a8083063 Iustin Pop
      if retries >= 10:
1492 3ecf6786 Iustin Pop
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1493 3ecf6786 Iustin Pop
                                 " aborting." % node)
1494 a8083063 Iustin Pop
      time.sleep(6)
1495 a8083063 Iustin Pop
      continue
1496 781de953 Iustin Pop
    rstats = rstats.data
1497 a8083063 Iustin Pop
    retries = 0
1498 1492cca7 Iustin Pop
    for i, mstat in enumerate(rstats):
1499 a8083063 Iustin Pop
      if mstat is None:
1500 86d9d3bb Iustin Pop
        lu.LogWarning("Can't compute data for node %s/%s",
1501 86d9d3bb Iustin Pop
                           node, instance.disks[i].iv_name)
1502 a8083063 Iustin Pop
        continue
1503 0834c866 Iustin Pop
      # we ignore the ldisk parameter
1504 0834c866 Iustin Pop
      perc_done, est_time, is_degraded, _ = mstat
1505 a8083063 Iustin Pop
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1506 a8083063 Iustin Pop
      if perc_done is not None:
1507 a8083063 Iustin Pop
        done = False
1508 a8083063 Iustin Pop
        if est_time is not None:
1509 a8083063 Iustin Pop
          rem_time = "%d estimated seconds remaining" % est_time
1510 a8083063 Iustin Pop
          max_time = est_time
1511 a8083063 Iustin Pop
        else:
1512 a8083063 Iustin Pop
          rem_time = "no time estimate"
1513 b9bddb6b Iustin Pop
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1514 b9bddb6b Iustin Pop
                        (instance.disks[i].iv_name, perc_done, rem_time))
1515 a8083063 Iustin Pop
    if done or oneshot:
1516 a8083063 Iustin Pop
      break
1517 a8083063 Iustin Pop
1518 d4fa5c23 Iustin Pop
    time.sleep(min(60, max_time))
1519 a8083063 Iustin Pop
1520 a8083063 Iustin Pop
  if done:
1521 b9bddb6b Iustin Pop
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1522 a8083063 Iustin Pop
  return not cumul_degraded
1523 a8083063 Iustin Pop
1524 a8083063 Iustin Pop
1525 b9bddb6b Iustin Pop
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1526 a8083063 Iustin Pop
  """Check that mirrors are not degraded.
1527 a8083063 Iustin Pop

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

1532 a8083063 Iustin Pop
  """
1533 b9bddb6b Iustin Pop
  lu.cfg.SetDiskID(dev, node)
1534 0834c866 Iustin Pop
  if ldisk:
1535 0834c866 Iustin Pop
    idx = 6
1536 0834c866 Iustin Pop
  else:
1537 0834c866 Iustin Pop
    idx = 5
1538 a8083063 Iustin Pop
1539 a8083063 Iustin Pop
  result = True
1540 a8083063 Iustin Pop
  if on_primary or dev.AssembleOnSecondary():
1541 72737a7f Iustin Pop
    rstats = lu.rpc.call_blockdev_find(node, dev)
1542 781de953 Iustin Pop
    if rstats.failed or not rstats.data:
1543 9a4f63d1 Iustin Pop
      logging.warning("Node %s: disk degraded, not found or node down", node)
1544 a8083063 Iustin Pop
      result = False
1545 a8083063 Iustin Pop
    else:
1546 781de953 Iustin Pop
      result = result and (not rstats.data[idx])
1547 a8083063 Iustin Pop
  if dev.children:
1548 a8083063 Iustin Pop
    for child in dev.children:
1549 b9bddb6b Iustin Pop
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1550 a8083063 Iustin Pop
1551 a8083063 Iustin Pop
  return result
1552 a8083063 Iustin Pop
1553 a8083063 Iustin Pop
1554 a8083063 Iustin Pop
class LUDiagnoseOS(NoHooksLU):
1555 a8083063 Iustin Pop
  """Logical unit for OS diagnose/query.
1556 a8083063 Iustin Pop

1557 a8083063 Iustin Pop
  """
1558 1f9430d6 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1559 6bf01bbb Guido Trotter
  REQ_BGL = False
1560 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet()
1561 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status")
1562 a8083063 Iustin Pop
1563 6bf01bbb Guido Trotter
  def ExpandNames(self):
1564 1f9430d6 Iustin Pop
    if self.op.names:
1565 1f9430d6 Iustin Pop
      raise errors.OpPrereqError("Selective OS query not supported")
1566 1f9430d6 Iustin Pop
1567 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
1568 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
1569 1f9430d6 Iustin Pop
                       selected=self.op.output_fields)
1570 1f9430d6 Iustin Pop
1571 6bf01bbb Guido Trotter
    # Lock all nodes, in shared mode
1572 6bf01bbb Guido Trotter
    self.needed_locks = {}
1573 6bf01bbb Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1574 e310b019 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1575 6bf01bbb Guido Trotter
1576 6bf01bbb Guido Trotter
  def CheckPrereq(self):
1577 6bf01bbb Guido Trotter
    """Check prerequisites.
1578 6bf01bbb Guido Trotter

1579 6bf01bbb Guido Trotter
    """
1580 6bf01bbb Guido Trotter
1581 1f9430d6 Iustin Pop
  @staticmethod
1582 1f9430d6 Iustin Pop
  def _DiagnoseByOS(node_list, rlist):
1583 1f9430d6 Iustin Pop
    """Remaps a per-node return list into an a per-os per-node dictionary
1584 1f9430d6 Iustin Pop

1585 e4376078 Iustin Pop
    @param node_list: a list with the names of all nodes
1586 e4376078 Iustin Pop
    @param rlist: a map with node names as keys and OS objects as values
1587 1f9430d6 Iustin Pop

1588 e4376078 Iustin Pop
    @rtype: dict
1589 e4376078 Iustin Pop
    @returns: a dictionary with osnames as keys and as value another map, with
1590 e4376078 Iustin Pop
        nodes as keys and list of OS objects as values, eg::
1591 e4376078 Iustin Pop

1592 e4376078 Iustin Pop
          {"debian-etch": {"node1": [<object>,...],
1593 e4376078 Iustin Pop
                           "node2": [<object>,]}
1594 e4376078 Iustin Pop
          }
1595 1f9430d6 Iustin Pop

1596 1f9430d6 Iustin Pop
    """
1597 1f9430d6 Iustin Pop
    all_os = {}
1598 1f9430d6 Iustin Pop
    for node_name, nr in rlist.iteritems():
1599 781de953 Iustin Pop
      if nr.failed or not nr.data:
1600 1f9430d6 Iustin Pop
        continue
1601 781de953 Iustin Pop
      for os_obj in nr.data:
1602 b4de68a9 Iustin Pop
        if os_obj.name not in all_os:
1603 1f9430d6 Iustin Pop
          # build a list of nodes for this os containing empty lists
1604 1f9430d6 Iustin Pop
          # for each node in node_list
1605 b4de68a9 Iustin Pop
          all_os[os_obj.name] = {}
1606 1f9430d6 Iustin Pop
          for nname in node_list:
1607 b4de68a9 Iustin Pop
            all_os[os_obj.name][nname] = []
1608 b4de68a9 Iustin Pop
        all_os[os_obj.name][node_name].append(os_obj)
1609 1f9430d6 Iustin Pop
    return all_os
1610 a8083063 Iustin Pop
1611 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1612 a8083063 Iustin Pop
    """Compute the list of OSes.
1613 a8083063 Iustin Pop

1614 a8083063 Iustin Pop
    """
1615 6bf01bbb Guido Trotter
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1616 94a02bb5 Iustin Pop
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()
1617 94a02bb5 Iustin Pop
                   if node in node_list]
1618 94a02bb5 Iustin Pop
    node_data = self.rpc.call_os_diagnose(valid_nodes)
1619 a8083063 Iustin Pop
    if node_data == False:
1620 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't gather the list of OSes")
1621 94a02bb5 Iustin Pop
    pol = self._DiagnoseByOS(valid_nodes, node_data)
1622 1f9430d6 Iustin Pop
    output = []
1623 1f9430d6 Iustin Pop
    for os_name, os_data in pol.iteritems():
1624 1f9430d6 Iustin Pop
      row = []
1625 1f9430d6 Iustin Pop
      for field in self.op.output_fields:
1626 1f9430d6 Iustin Pop
        if field == "name":
1627 1f9430d6 Iustin Pop
          val = os_name
1628 1f9430d6 Iustin Pop
        elif field == "valid":
1629 1f9430d6 Iustin Pop
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1630 1f9430d6 Iustin Pop
        elif field == "node_status":
1631 1f9430d6 Iustin Pop
          val = {}
1632 1f9430d6 Iustin Pop
          for node_name, nos_list in os_data.iteritems():
1633 1f9430d6 Iustin Pop
            val[node_name] = [(v.status, v.path) for v in nos_list]
1634 1f9430d6 Iustin Pop
        else:
1635 1f9430d6 Iustin Pop
          raise errors.ParameterError(field)
1636 1f9430d6 Iustin Pop
        row.append(val)
1637 1f9430d6 Iustin Pop
      output.append(row)
1638 1f9430d6 Iustin Pop
1639 1f9430d6 Iustin Pop
    return output
1640 a8083063 Iustin Pop
1641 a8083063 Iustin Pop
1642 a8083063 Iustin Pop
class LURemoveNode(LogicalUnit):
1643 a8083063 Iustin Pop
  """Logical unit for removing a node.
1644 a8083063 Iustin Pop

1645 a8083063 Iustin Pop
  """
1646 a8083063 Iustin Pop
  HPATH = "node-remove"
1647 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1648 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1649 a8083063 Iustin Pop
1650 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1651 a8083063 Iustin Pop
    """Build hooks env.
1652 a8083063 Iustin Pop

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

1656 a8083063 Iustin Pop
    """
1657 396e1b78 Michael Hanselmann
    env = {
1658 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1659 396e1b78 Michael Hanselmann
      "NODE_NAME": self.op.node_name,
1660 396e1b78 Michael Hanselmann
      }
1661 a8083063 Iustin Pop
    all_nodes = self.cfg.GetNodeList()
1662 a8083063 Iustin Pop
    all_nodes.remove(self.op.node_name)
1663 396e1b78 Michael Hanselmann
    return env, all_nodes, all_nodes
1664 a8083063 Iustin Pop
1665 a8083063 Iustin Pop
  def CheckPrereq(self):
1666 a8083063 Iustin Pop
    """Check prerequisites.
1667 a8083063 Iustin Pop

1668 a8083063 Iustin Pop
    This checks:
1669 a8083063 Iustin Pop
     - the node exists in the configuration
1670 a8083063 Iustin Pop
     - it does not have primary or secondary instances
1671 a8083063 Iustin Pop
     - it's not the master
1672 a8083063 Iustin Pop

1673 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1674 a8083063 Iustin Pop

1675 a8083063 Iustin Pop
    """
1676 a8083063 Iustin Pop
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1677 a8083063 Iustin Pop
    if node is None:
1678 a02bc76e Iustin Pop
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1679 a8083063 Iustin Pop
1680 a8083063 Iustin Pop
    instance_list = self.cfg.GetInstanceList()
1681 a8083063 Iustin Pop
1682 d6a02168 Michael Hanselmann
    masternode = self.cfg.GetMasterNode()
1683 a8083063 Iustin Pop
    if node.name == masternode:
1684 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node is the master node,"
1685 3ecf6786 Iustin Pop
                                 " you need to failover first.")
1686 a8083063 Iustin Pop
1687 a8083063 Iustin Pop
    for instance_name in instance_list:
1688 a8083063 Iustin Pop
      instance = self.cfg.GetInstanceInfo(instance_name)
1689 6b12959c Iustin Pop
      if node.name in instance.all_nodes:
1690 6b12959c Iustin Pop
        raise errors.OpPrereqError("Instance %s is still running on the node,"
1691 3ecf6786 Iustin Pop
                                   " please remove first." % instance_name)
1692 a8083063 Iustin Pop
    self.op.node_name = node.name
1693 a8083063 Iustin Pop
    self.node = node
1694 a8083063 Iustin Pop
1695 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1696 a8083063 Iustin Pop
    """Removes the node from the cluster.
1697 a8083063 Iustin Pop

1698 a8083063 Iustin Pop
    """
1699 a8083063 Iustin Pop
    node = self.node
1700 9a4f63d1 Iustin Pop
    logging.info("Stopping the node daemon and removing configs from node %s",
1701 9a4f63d1 Iustin Pop
                 node.name)
1702 a8083063 Iustin Pop
1703 d8470559 Michael Hanselmann
    self.context.RemoveNode(node.name)
1704 a8083063 Iustin Pop
1705 72737a7f Iustin Pop
    self.rpc.call_node_leave_cluster(node.name)
1706 c8a0948f Michael Hanselmann
1707 eb1742d5 Guido Trotter
    # Promote nodes to master candidate as needed
1708 ec0292f1 Iustin Pop
    _AdjustCandidatePool(self)
1709 eb1742d5 Guido Trotter
1710 a8083063 Iustin Pop
1711 a8083063 Iustin Pop
class LUQueryNodes(NoHooksLU):
1712 a8083063 Iustin Pop
  """Logical unit for querying nodes.
1713 a8083063 Iustin Pop

1714 a8083063 Iustin Pop
  """
1715 246e180a Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1716 35705d8f Guido Trotter
  REQ_BGL = False
1717 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet(
1718 31bf511f Iustin Pop
    "dtotal", "dfree",
1719 31bf511f Iustin Pop
    "mtotal", "mnode", "mfree",
1720 31bf511f Iustin Pop
    "bootid",
1721 31bf511f Iustin Pop
    "ctotal",
1722 31bf511f Iustin Pop
    )
1723 31bf511f Iustin Pop
1724 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet(
1725 31bf511f Iustin Pop
    "name", "pinst_cnt", "sinst_cnt",
1726 31bf511f Iustin Pop
    "pinst_list", "sinst_list",
1727 31bf511f Iustin Pop
    "pip", "sip", "tags",
1728 31bf511f Iustin Pop
    "serial_no",
1729 0e67cdbe Iustin Pop
    "master_candidate",
1730 0e67cdbe Iustin Pop
    "master",
1731 9ddb5e45 Iustin Pop
    "offline",
1732 31bf511f Iustin Pop
    )
1733 a8083063 Iustin Pop
1734 35705d8f Guido Trotter
  def ExpandNames(self):
1735 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
1736 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
1737 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
1738 a8083063 Iustin Pop
1739 35705d8f Guido Trotter
    self.needed_locks = {}
1740 35705d8f Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1741 c8d8b4c8 Iustin Pop
1742 c8d8b4c8 Iustin Pop
    if self.op.names:
1743 c8d8b4c8 Iustin Pop
      self.wanted = _GetWantedNodes(self, self.op.names)
1744 35705d8f Guido Trotter
    else:
1745 c8d8b4c8 Iustin Pop
      self.wanted = locking.ALL_SET
1746 c8d8b4c8 Iustin Pop
1747 31bf511f Iustin Pop
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
1748 c8d8b4c8 Iustin Pop
    if self.do_locking:
1749 c8d8b4c8 Iustin Pop
      # if we don't request only static fields, we need to lock the nodes
1750 c8d8b4c8 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1751 c8d8b4c8 Iustin Pop
1752 35705d8f Guido Trotter
1753 35705d8f Guido Trotter
  def CheckPrereq(self):
1754 35705d8f Guido Trotter
    """Check prerequisites.
1755 35705d8f Guido Trotter

1756 35705d8f Guido Trotter
    """
1757 c8d8b4c8 Iustin Pop
    # The validation of the node list is done in the _GetWantedNodes,
1758 c8d8b4c8 Iustin Pop
    # if non empty, and if empty, there's no validation to do
1759 c8d8b4c8 Iustin Pop
    pass
1760 a8083063 Iustin Pop
1761 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1762 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
1763 a8083063 Iustin Pop

1764 a8083063 Iustin Pop
    """
1765 c8d8b4c8 Iustin Pop
    all_info = self.cfg.GetAllNodesInfo()
1766 c8d8b4c8 Iustin Pop
    if self.do_locking:
1767 c8d8b4c8 Iustin Pop
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1768 3fa93523 Guido Trotter
    elif self.wanted != locking.ALL_SET:
1769 3fa93523 Guido Trotter
      nodenames = self.wanted
1770 3fa93523 Guido Trotter
      missing = set(nodenames).difference(all_info.keys())
1771 3fa93523 Guido Trotter
      if missing:
1772 7b3a8fb5 Iustin Pop
        raise errors.OpExecError(
1773 3fa93523 Guido Trotter
          "Some nodes were removed before retrieving their data: %s" % missing)
1774 c8d8b4c8 Iustin Pop
    else:
1775 c8d8b4c8 Iustin Pop
      nodenames = all_info.keys()
1776 c1f1cbb2 Iustin Pop
1777 c1f1cbb2 Iustin Pop
    nodenames = utils.NiceSort(nodenames)
1778 c8d8b4c8 Iustin Pop
    nodelist = [all_info[name] for name in nodenames]
1779 a8083063 Iustin Pop
1780 a8083063 Iustin Pop
    # begin data gathering
1781 a8083063 Iustin Pop
1782 31bf511f Iustin Pop
    if self.do_locking:
1783 a8083063 Iustin Pop
      live_data = {}
1784 72737a7f Iustin Pop
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1785 72737a7f Iustin Pop
                                          self.cfg.GetHypervisorType())
1786 a8083063 Iustin Pop
      for name in nodenames:
1787 781de953 Iustin Pop
        nodeinfo = node_data[name]
1788 781de953 Iustin Pop
        if not nodeinfo.failed and nodeinfo.data:
1789 781de953 Iustin Pop
          nodeinfo = nodeinfo.data
1790 d599d686 Iustin Pop
          fn = utils.TryConvert
1791 a8083063 Iustin Pop
          live_data[name] = {
1792 d599d686 Iustin Pop
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
1793 d599d686 Iustin Pop
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
1794 d599d686 Iustin Pop
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
1795 d599d686 Iustin Pop
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
1796 d599d686 Iustin Pop
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
1797 d599d686 Iustin Pop
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
1798 d599d686 Iustin Pop
            "bootid": nodeinfo.get('bootid', None),
1799 a8083063 Iustin Pop
            }
1800 a8083063 Iustin Pop
        else:
1801 a8083063 Iustin Pop
          live_data[name] = {}
1802 a8083063 Iustin Pop
    else:
1803 a8083063 Iustin Pop
      live_data = dict.fromkeys(nodenames, {})
1804 a8083063 Iustin Pop
1805 ec223efb Iustin Pop
    node_to_primary = dict([(name, set()) for name in nodenames])
1806 ec223efb Iustin Pop
    node_to_secondary = dict([(name, set()) for name in nodenames])
1807 a8083063 Iustin Pop
1808 ec223efb Iustin Pop
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1809 ec223efb Iustin Pop
                             "sinst_cnt", "sinst_list"))
1810 ec223efb Iustin Pop
    if inst_fields & frozenset(self.op.output_fields):
1811 a8083063 Iustin Pop
      instancelist = self.cfg.GetInstanceList()
1812 a8083063 Iustin Pop
1813 ec223efb Iustin Pop
      for instance_name in instancelist:
1814 ec223efb Iustin Pop
        inst = self.cfg.GetInstanceInfo(instance_name)
1815 ec223efb Iustin Pop
        if inst.primary_node in node_to_primary:
1816 ec223efb Iustin Pop
          node_to_primary[inst.primary_node].add(inst.name)
1817 ec223efb Iustin Pop
        for secnode in inst.secondary_nodes:
1818 ec223efb Iustin Pop
          if secnode in node_to_secondary:
1819 ec223efb Iustin Pop
            node_to_secondary[secnode].add(inst.name)
1820 a8083063 Iustin Pop
1821 0e67cdbe Iustin Pop
    master_node = self.cfg.GetMasterNode()
1822 0e67cdbe Iustin Pop
1823 a8083063 Iustin Pop
    # end data gathering
1824 a8083063 Iustin Pop
1825 a8083063 Iustin Pop
    output = []
1826 a8083063 Iustin Pop
    for node in nodelist:
1827 a8083063 Iustin Pop
      node_output = []
1828 a8083063 Iustin Pop
      for field in self.op.output_fields:
1829 a8083063 Iustin Pop
        if field == "name":
1830 a8083063 Iustin Pop
          val = node.name
1831 ec223efb Iustin Pop
        elif field == "pinst_list":
1832 ec223efb Iustin Pop
          val = list(node_to_primary[node.name])
1833 ec223efb Iustin Pop
        elif field == "sinst_list":
1834 ec223efb Iustin Pop
          val = list(node_to_secondary[node.name])
1835 ec223efb Iustin Pop
        elif field == "pinst_cnt":
1836 ec223efb Iustin Pop
          val = len(node_to_primary[node.name])
1837 ec223efb Iustin Pop
        elif field == "sinst_cnt":
1838 ec223efb Iustin Pop
          val = len(node_to_secondary[node.name])
1839 a8083063 Iustin Pop
        elif field == "pip":
1840 a8083063 Iustin Pop
          val = node.primary_ip
1841 a8083063 Iustin Pop
        elif field == "sip":
1842 a8083063 Iustin Pop
          val = node.secondary_ip
1843 130a6a6f Iustin Pop
        elif field == "tags":
1844 130a6a6f Iustin Pop
          val = list(node.GetTags())
1845 38d7239a Iustin Pop
        elif field == "serial_no":
1846 38d7239a Iustin Pop
          val = node.serial_no
1847 0e67cdbe Iustin Pop
        elif field == "master_candidate":
1848 0e67cdbe Iustin Pop
          val = node.master_candidate
1849 0e67cdbe Iustin Pop
        elif field == "master":
1850 0e67cdbe Iustin Pop
          val = node.name == master_node
1851 9ddb5e45 Iustin Pop
        elif field == "offline":
1852 9ddb5e45 Iustin Pop
          val = node.offline
1853 31bf511f Iustin Pop
        elif self._FIELDS_DYNAMIC.Matches(field):
1854 ec223efb Iustin Pop
          val = live_data[node.name].get(field, None)
1855 a8083063 Iustin Pop
        else:
1856 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
1857 a8083063 Iustin Pop
        node_output.append(val)
1858 a8083063 Iustin Pop
      output.append(node_output)
1859 a8083063 Iustin Pop
1860 a8083063 Iustin Pop
    return output
1861 a8083063 Iustin Pop
1862 a8083063 Iustin Pop
1863 dcb93971 Michael Hanselmann
class LUQueryNodeVolumes(NoHooksLU):
1864 dcb93971 Michael Hanselmann
  """Logical unit for getting volumes on node(s).
1865 dcb93971 Michael Hanselmann

1866 dcb93971 Michael Hanselmann
  """
1867 dcb93971 Michael Hanselmann
  _OP_REQP = ["nodes", "output_fields"]
1868 21a15682 Guido Trotter
  REQ_BGL = False
1869 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
1870 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet("node")
1871 21a15682 Guido Trotter
1872 21a15682 Guido Trotter
  def ExpandNames(self):
1873 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
1874 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
1875 21a15682 Guido Trotter
                       selected=self.op.output_fields)
1876 21a15682 Guido Trotter
1877 21a15682 Guido Trotter
    self.needed_locks = {}
1878 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1879 21a15682 Guido Trotter
    if not self.op.nodes:
1880 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1881 21a15682 Guido Trotter
    else:
1882 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
1883 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
1884 dcb93971 Michael Hanselmann
1885 dcb93971 Michael Hanselmann
  def CheckPrereq(self):
1886 dcb93971 Michael Hanselmann
    """Check prerequisites.
1887 dcb93971 Michael Hanselmann

1888 dcb93971 Michael Hanselmann
    This checks that the fields required are valid output fields.
1889 dcb93971 Michael Hanselmann

1890 dcb93971 Michael Hanselmann
    """
1891 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1892 dcb93971 Michael Hanselmann
1893 dcb93971 Michael Hanselmann
  def Exec(self, feedback_fn):
1894 dcb93971 Michael Hanselmann
    """Computes the list of nodes and their attributes.
1895 dcb93971 Michael Hanselmann

1896 dcb93971 Michael Hanselmann
    """
1897 a7ba5e53 Iustin Pop
    nodenames = self.nodes
1898 72737a7f Iustin Pop
    volumes = self.rpc.call_node_volumes(nodenames)
1899 dcb93971 Michael Hanselmann
1900 dcb93971 Michael Hanselmann
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1901 dcb93971 Michael Hanselmann
             in self.cfg.GetInstanceList()]
1902 dcb93971 Michael Hanselmann
1903 dcb93971 Michael Hanselmann
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1904 dcb93971 Michael Hanselmann
1905 dcb93971 Michael Hanselmann
    output = []
1906 dcb93971 Michael Hanselmann
    for node in nodenames:
1907 781de953 Iustin Pop
      if node not in volumes or volumes[node].failed or not volumes[node].data:
1908 37d19eb2 Michael Hanselmann
        continue
1909 37d19eb2 Michael Hanselmann
1910 781de953 Iustin Pop
      node_vols = volumes[node].data[:]
1911 dcb93971 Michael Hanselmann
      node_vols.sort(key=lambda vol: vol['dev'])
1912 dcb93971 Michael Hanselmann
1913 dcb93971 Michael Hanselmann
      for vol in node_vols:
1914 dcb93971 Michael Hanselmann
        node_output = []
1915 dcb93971 Michael Hanselmann
        for field in self.op.output_fields:
1916 dcb93971 Michael Hanselmann
          if field == "node":
1917 dcb93971 Michael Hanselmann
            val = node
1918 dcb93971 Michael Hanselmann
          elif field == "phys":
1919 dcb93971 Michael Hanselmann
            val = vol['dev']
1920 dcb93971 Michael Hanselmann
          elif field == "vg":
1921 dcb93971 Michael Hanselmann
            val = vol['vg']
1922 dcb93971 Michael Hanselmann
          elif field == "name":
1923 dcb93971 Michael Hanselmann
            val = vol['name']
1924 dcb93971 Michael Hanselmann
          elif field == "size":
1925 dcb93971 Michael Hanselmann
            val = int(float(vol['size']))
1926 dcb93971 Michael Hanselmann
          elif field == "instance":
1927 dcb93971 Michael Hanselmann
            for inst in ilist:
1928 dcb93971 Michael Hanselmann
              if node not in lv_by_node[inst]:
1929 dcb93971 Michael Hanselmann
                continue
1930 dcb93971 Michael Hanselmann
              if vol['name'] in lv_by_node[inst][node]:
1931 dcb93971 Michael Hanselmann
                val = inst.name
1932 dcb93971 Michael Hanselmann
                break
1933 dcb93971 Michael Hanselmann
            else:
1934 dcb93971 Michael Hanselmann
              val = '-'
1935 dcb93971 Michael Hanselmann
          else:
1936 3ecf6786 Iustin Pop
            raise errors.ParameterError(field)
1937 dcb93971 Michael Hanselmann
          node_output.append(str(val))
1938 dcb93971 Michael Hanselmann
1939 dcb93971 Michael Hanselmann
        output.append(node_output)
1940 dcb93971 Michael Hanselmann
1941 dcb93971 Michael Hanselmann
    return output
1942 dcb93971 Michael Hanselmann
1943 dcb93971 Michael Hanselmann
1944 a8083063 Iustin Pop
class LUAddNode(LogicalUnit):
1945 a8083063 Iustin Pop
  """Logical unit for adding node to the cluster.
1946 a8083063 Iustin Pop

1947 a8083063 Iustin Pop
  """
1948 a8083063 Iustin Pop
  HPATH = "node-add"
1949 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1950 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1951 a8083063 Iustin Pop
1952 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1953 a8083063 Iustin Pop
    """Build hooks env.
1954 a8083063 Iustin Pop

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

1957 a8083063 Iustin Pop
    """
1958 a8083063 Iustin Pop
    env = {
1959 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1960 a8083063 Iustin Pop
      "NODE_NAME": self.op.node_name,
1961 a8083063 Iustin Pop
      "NODE_PIP": self.op.primary_ip,
1962 a8083063 Iustin Pop
      "NODE_SIP": self.op.secondary_ip,
1963 a8083063 Iustin Pop
      }
1964 a8083063 Iustin Pop
    nodes_0 = self.cfg.GetNodeList()
1965 a8083063 Iustin Pop
    nodes_1 = nodes_0 + [self.op.node_name, ]
1966 a8083063 Iustin Pop
    return env, nodes_0, nodes_1
1967 a8083063 Iustin Pop
1968 a8083063 Iustin Pop
  def CheckPrereq(self):
1969 a8083063 Iustin Pop
    """Check prerequisites.
1970 a8083063 Iustin Pop

1971 a8083063 Iustin Pop
    This checks:
1972 a8083063 Iustin Pop
     - the new node is not already in the config
1973 a8083063 Iustin Pop
     - it is resolvable
1974 a8083063 Iustin Pop
     - its parameters (single/dual homed) matches the cluster
1975 a8083063 Iustin Pop

1976 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1977 a8083063 Iustin Pop

1978 a8083063 Iustin Pop
    """
1979 a8083063 Iustin Pop
    node_name = self.op.node_name
1980 a8083063 Iustin Pop
    cfg = self.cfg
1981 a8083063 Iustin Pop
1982 89e1fc26 Iustin Pop
    dns_data = utils.HostInfo(node_name)
1983 a8083063 Iustin Pop
1984 bcf043c9 Iustin Pop
    node = dns_data.name
1985 bcf043c9 Iustin Pop
    primary_ip = self.op.primary_ip = dns_data.ip
1986 a8083063 Iustin Pop
    secondary_ip = getattr(self.op, "secondary_ip", None)
1987 a8083063 Iustin Pop
    if secondary_ip is None:
1988 a8083063 Iustin Pop
      secondary_ip = primary_ip
1989 a8083063 Iustin Pop
    if not utils.IsValidIP(secondary_ip):
1990 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid secondary IP given")
1991 a8083063 Iustin Pop
    self.op.secondary_ip = secondary_ip
1992 e7c6e02b Michael Hanselmann
1993 a8083063 Iustin Pop
    node_list = cfg.GetNodeList()
1994 e7c6e02b Michael Hanselmann
    if not self.op.readd and node in node_list:
1995 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1996 e7c6e02b Michael Hanselmann
                                 node)
1997 e7c6e02b Michael Hanselmann
    elif self.op.readd and node not in node_list:
1998 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1999 a8083063 Iustin Pop
2000 a8083063 Iustin Pop
    for existing_node_name in node_list:
2001 a8083063 Iustin Pop
      existing_node = cfg.GetNodeInfo(existing_node_name)
2002 e7c6e02b Michael Hanselmann
2003 e7c6e02b Michael Hanselmann
      if self.op.readd and node == existing_node_name:
2004 e7c6e02b Michael Hanselmann
        if (existing_node.primary_ip != primary_ip or
2005 e7c6e02b Michael Hanselmann
            existing_node.secondary_ip != secondary_ip):
2006 e7c6e02b Michael Hanselmann
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
2007 e7c6e02b Michael Hanselmann
                                     " address configuration as before")
2008 e7c6e02b Michael Hanselmann
        continue
2009 e7c6e02b Michael Hanselmann
2010 a8083063 Iustin Pop
      if (existing_node.primary_ip == primary_ip or
2011 a8083063 Iustin Pop
          existing_node.secondary_ip == primary_ip or
2012 a8083063 Iustin Pop
          existing_node.primary_ip == secondary_ip or
2013 a8083063 Iustin Pop
          existing_node.secondary_ip == secondary_ip):
2014 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("New node ip address(es) conflict with"
2015 3ecf6786 Iustin Pop
                                   " existing node %s" % existing_node.name)
2016 a8083063 Iustin Pop
2017 a8083063 Iustin Pop
    # check that the type of the node (single versus dual homed) is the
2018 a8083063 Iustin Pop
    # same as for the master
2019 d6a02168 Michael Hanselmann
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
2020 a8083063 Iustin Pop
    master_singlehomed = myself.secondary_ip == myself.primary_ip
2021 a8083063 Iustin Pop
    newbie_singlehomed = secondary_ip == primary_ip
2022 a8083063 Iustin Pop
    if master_singlehomed != newbie_singlehomed:
2023 a8083063 Iustin Pop
      if master_singlehomed:
2024 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has no private ip but the"
2025 3ecf6786 Iustin Pop
                                   " new node has one")
2026 a8083063 Iustin Pop
      else:
2027 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has a private ip but the"
2028 3ecf6786 Iustin Pop
                                   " new node doesn't have one")
2029 a8083063 Iustin Pop
2030 a8083063 Iustin Pop
    # checks reachablity
2031 b15d625f Iustin Pop
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
2032 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node not reachable by ping")
2033 a8083063 Iustin Pop
2034 a8083063 Iustin Pop
    if not newbie_singlehomed:
2035 a8083063 Iustin Pop
      # check reachability from my secondary ip to newbie's secondary ip
2036 b15d625f Iustin Pop
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
2037 b15d625f Iustin Pop
                           source=myself.secondary_ip):
2038 f4bc1f2c Michael Hanselmann
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
2039 f4bc1f2c Michael Hanselmann
                                   " based ping to noded port")
2040 a8083063 Iustin Pop
2041 0fff97e9 Guido Trotter
    cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2042 ec0292f1 Iustin Pop
    mc_now, _ = self.cfg.GetMasterCandidateStats()
2043 ec0292f1 Iustin Pop
    master_candidate = mc_now < cp_size
2044 0fff97e9 Guido Trotter
2045 a8083063 Iustin Pop
    self.new_node = objects.Node(name=node,
2046 a8083063 Iustin Pop
                                 primary_ip=primary_ip,
2047 0fff97e9 Guido Trotter
                                 secondary_ip=secondary_ip,
2048 fc0fe88c Iustin Pop
                                 master_candidate=master_candidate,
2049 fc0fe88c Iustin Pop
                                 offline=False)
2050 a8083063 Iustin Pop
2051 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2052 a8083063 Iustin Pop
    """Adds the new node to the cluster.
2053 a8083063 Iustin Pop

2054 a8083063 Iustin Pop
    """
2055 a8083063 Iustin Pop
    new_node = self.new_node
2056 a8083063 Iustin Pop
    node = new_node.name
2057 a8083063 Iustin Pop
2058 a8083063 Iustin Pop
    # check connectivity
2059 72737a7f Iustin Pop
    result = self.rpc.call_version([node])[node]
2060 781de953 Iustin Pop
    result.Raise()
2061 781de953 Iustin Pop
    if result.data:
2062 781de953 Iustin Pop
      if constants.PROTOCOL_VERSION == result.data:
2063 9a4f63d1 Iustin Pop
        logging.info("Communication to node %s fine, sw version %s match",
2064 781de953 Iustin Pop
                     node, result.data)
2065 a8083063 Iustin Pop
      else:
2066 3ecf6786 Iustin Pop
        raise errors.OpExecError("Version mismatch master version %s,"
2067 3ecf6786 Iustin Pop
                                 " node version %s" %
2068 781de953 Iustin Pop
                                 (constants.PROTOCOL_VERSION, result.data))
2069 a8083063 Iustin Pop
    else:
2070 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot get version from the new node")
2071 a8083063 Iustin Pop
2072 a8083063 Iustin Pop
    # setup ssh on node
2073 9a4f63d1 Iustin Pop
    logging.info("Copy ssh key to node %s", node)
2074 70d9e3d8 Iustin Pop
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
2075 a8083063 Iustin Pop
    keyarray = []
2076 70d9e3d8 Iustin Pop
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
2077 70d9e3d8 Iustin Pop
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
2078 70d9e3d8 Iustin Pop
                priv_key, pub_key]
2079 a8083063 Iustin Pop
2080 a8083063 Iustin Pop
    for i in keyfiles:
2081 a8083063 Iustin Pop
      f = open(i, 'r')
2082 a8083063 Iustin Pop
      try:
2083 a8083063 Iustin Pop
        keyarray.append(f.read())
2084 a8083063 Iustin Pop
      finally:
2085 a8083063 Iustin Pop
        f.close()
2086 a8083063 Iustin Pop
2087 72737a7f Iustin Pop
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
2088 72737a7f Iustin Pop
                                    keyarray[2],
2089 72737a7f Iustin Pop
                                    keyarray[3], keyarray[4], keyarray[5])
2090 a8083063 Iustin Pop
2091 781de953 Iustin Pop
    if result.failed or not result.data:
2092 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
2093 a8083063 Iustin Pop
2094 a8083063 Iustin Pop
    # Add node to our /etc/hosts, and add key to known_hosts
2095 d9c02ca6 Michael Hanselmann
    utils.AddHostToEtcHosts(new_node.name)
2096 c8a0948f Michael Hanselmann
2097 a8083063 Iustin Pop
    if new_node.secondary_ip != new_node.primary_ip:
2098 781de953 Iustin Pop
      result = self.rpc.call_node_has_ip_address(new_node.name,
2099 781de953 Iustin Pop
                                                 new_node.secondary_ip)
2100 781de953 Iustin Pop
      if result.failed or not result.data:
2101 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
2102 f4bc1f2c Michael Hanselmann
                                 " you gave (%s). Please fix and re-run this"
2103 f4bc1f2c Michael Hanselmann
                                 " command." % new_node.secondary_ip)
2104 a8083063 Iustin Pop
2105 d6a02168 Michael Hanselmann
    node_verify_list = [self.cfg.GetMasterNode()]
2106 5c0527ed Guido Trotter
    node_verify_param = {
2107 5c0527ed Guido Trotter
      'nodelist': [node],
2108 5c0527ed Guido Trotter
      # TODO: do a node-net-test as well?
2109 5c0527ed Guido Trotter
    }
2110 5c0527ed Guido Trotter
2111 72737a7f Iustin Pop
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
2112 72737a7f Iustin Pop
                                       self.cfg.GetClusterName())
2113 5c0527ed Guido Trotter
    for verifier in node_verify_list:
2114 f08ce603 Guido Trotter
      if result[verifier].failed or not result[verifier].data:
2115 5c0527ed Guido Trotter
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
2116 5c0527ed Guido Trotter
                                 " for remote verification" % verifier)
2117 781de953 Iustin Pop
      if result[verifier].data['nodelist']:
2118 781de953 Iustin Pop
        for failed in result[verifier].data['nodelist']:
2119 5c0527ed Guido Trotter
          feedback_fn("ssh/hostname verification failed %s -> %s" %
2120 5c0527ed Guido Trotter
                      (verifier, result[verifier]['nodelist'][failed]))
2121 5c0527ed Guido Trotter
        raise errors.OpExecError("ssh/hostname verification failed.")
2122 ff98055b Iustin Pop
2123 a8083063 Iustin Pop
    # Distribute updated /etc/hosts and known_hosts to all nodes,
2124 a8083063 Iustin Pop
    # including the node just added
2125 d6a02168 Michael Hanselmann
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
2126 102b115b Michael Hanselmann
    dist_nodes = self.cfg.GetNodeList()
2127 102b115b Michael Hanselmann
    if not self.op.readd:
2128 102b115b Michael Hanselmann
      dist_nodes.append(node)
2129 a8083063 Iustin Pop
    if myself.name in dist_nodes:
2130 a8083063 Iustin Pop
      dist_nodes.remove(myself.name)
2131 a8083063 Iustin Pop
2132 9a4f63d1 Iustin Pop
    logging.debug("Copying hosts and known_hosts to all nodes")
2133 107711b0 Michael Hanselmann
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
2134 72737a7f Iustin Pop
      result = self.rpc.call_upload_file(dist_nodes, fname)
2135 ec85e3d5 Iustin Pop
      for to_node, to_result in result.iteritems():
2136 ec85e3d5 Iustin Pop
        if to_result.failed or not to_result.data:
2137 9a4f63d1 Iustin Pop
          logging.error("Copy of file %s to node %s failed", fname, to_node)
2138 a8083063 Iustin Pop
2139 d6a02168 Michael Hanselmann
    to_copy = []
2140 00cd937c Iustin Pop
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
2141 2a6469d5 Alexander Schreiber
      to_copy.append(constants.VNC_PASSWORD_FILE)
2142 a8083063 Iustin Pop
    for fname in to_copy:
2143 72737a7f Iustin Pop
      result = self.rpc.call_upload_file([node], fname)
2144 781de953 Iustin Pop
      if result[node].failed or not result[node]:
2145 9a4f63d1 Iustin Pop
        logging.error("Could not copy file %s to node %s", fname, node)
2146 a8083063 Iustin Pop
2147 d8470559 Michael Hanselmann
    if self.op.readd:
2148 d8470559 Michael Hanselmann
      self.context.ReaddNode(new_node)
2149 d8470559 Michael Hanselmann
    else:
2150 d8470559 Michael Hanselmann
      self.context.AddNode(new_node)
2151 a8083063 Iustin Pop
2152 a8083063 Iustin Pop
2153 b31c8676 Iustin Pop
class LUSetNodeParams(LogicalUnit):
2154 b31c8676 Iustin Pop
  """Modifies the parameters of a node.
2155 b31c8676 Iustin Pop

2156 b31c8676 Iustin Pop
  """
2157 b31c8676 Iustin Pop
  HPATH = "node-modify"
2158 b31c8676 Iustin Pop
  HTYPE = constants.HTYPE_NODE
2159 b31c8676 Iustin Pop
  _OP_REQP = ["node_name"]
2160 b31c8676 Iustin Pop
  REQ_BGL = False
2161 b31c8676 Iustin Pop
2162 b31c8676 Iustin Pop
  def CheckArguments(self):
2163 b31c8676 Iustin Pop
    node_name = self.cfg.ExpandNodeName(self.op.node_name)
2164 b31c8676 Iustin Pop
    if node_name is None:
2165 b31c8676 Iustin Pop
      raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name)
2166 b31c8676 Iustin Pop
    self.op.node_name = node_name
2167 3a5ba66a Iustin Pop
    _CheckBooleanOpField(self.op, 'master_candidate')
2168 3a5ba66a Iustin Pop
    _CheckBooleanOpField(self.op, 'offline')
2169 3a5ba66a Iustin Pop
    if self.op.master_candidate is None and self.op.offline is None:
2170 b31c8676 Iustin Pop
      raise errors.OpPrereqError("Please pass at least one modification")
2171 3a5ba66a Iustin Pop
    if self.op.offline == True and self.op.master_candidate == True:
2172 3a5ba66a Iustin Pop
      raise errors.OpPrereqError("Can't set the node into offline and"
2173 3a5ba66a Iustin Pop
                                 " master_candidate at the same time")
2174 b31c8676 Iustin Pop
2175 b31c8676 Iustin Pop
  def ExpandNames(self):
2176 b31c8676 Iustin Pop
    self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
2177 b31c8676 Iustin Pop
2178 b31c8676 Iustin Pop
  def BuildHooksEnv(self):
2179 b31c8676 Iustin Pop
    """Build hooks env.
2180 b31c8676 Iustin Pop

2181 b31c8676 Iustin Pop
    This runs on the master node.
2182 b31c8676 Iustin Pop

2183 b31c8676 Iustin Pop
    """
2184 b31c8676 Iustin Pop
    env = {
2185 b31c8676 Iustin Pop
      "OP_TARGET": self.op.node_name,
2186 b31c8676 Iustin Pop
      "MASTER_CANDIDATE": str(self.op.master_candidate),
2187 3a5ba66a Iustin Pop
      "OFFLINE": str(self.op.offline),
2188 b31c8676 Iustin Pop
      }
2189 b31c8676 Iustin Pop
    nl = [self.cfg.GetMasterNode(),
2190 b31c8676 Iustin Pop
          self.op.node_name]
2191 b31c8676 Iustin Pop
    return env, nl, nl
2192 b31c8676 Iustin Pop
2193 b31c8676 Iustin Pop
  def CheckPrereq(self):
2194 b31c8676 Iustin Pop
    """Check prerequisites.
2195 b31c8676 Iustin Pop

2196 b31c8676 Iustin Pop
    This only checks the instance list against the existing names.
2197 b31c8676 Iustin Pop

2198 b31c8676 Iustin Pop
    """
2199 3a5ba66a Iustin Pop
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
2200 b31c8676 Iustin Pop
2201 3a5ba66a Iustin Pop
    if ((self.op.master_candidate == False or self.op.offline == True)
2202 3a5ba66a Iustin Pop
        and node.master_candidate):
2203 3a5ba66a Iustin Pop
      # we will demote the node from master_candidate
2204 3a26773f Iustin Pop
      if self.op.node_name == self.cfg.GetMasterNode():
2205 3a26773f Iustin Pop
        raise errors.OpPrereqError("The master node has to be a"
2206 3a5ba66a Iustin Pop
                                   " master candidate and online")
2207 3e83dd48 Iustin Pop
      cp_size = self.cfg.GetClusterInfo().candidate_pool_size
2208 3a5ba66a Iustin Pop
      num_candidates, _ = self.cfg.GetMasterCandidateStats()
2209 3e83dd48 Iustin Pop
      if num_candidates <= cp_size:
2210 3e83dd48 Iustin Pop
        msg = ("Not enough master candidates (desired"
2211 3e83dd48 Iustin Pop
               " %d, new value will be %d)" % (cp_size, num_candidates-1))
2212 3a5ba66a Iustin Pop
        if self.op.force:
2213 3e83dd48 Iustin Pop
          self.LogWarning(msg)
2214 3e83dd48 Iustin Pop
        else:
2215 3e83dd48 Iustin Pop
          raise errors.OpPrereqError(msg)
2216 3e83dd48 Iustin Pop
2217 3a5ba66a Iustin Pop
    if (self.op.master_candidate == True and node.offline and
2218 3a5ba66a Iustin Pop
        not self.op.offline == False):
2219 3a5ba66a Iustin Pop
      raise errors.OpPrereqError("Can't set an offline node to"
2220 3a5ba66a Iustin Pop
                                 " master_candidate")
2221 3a5ba66a Iustin Pop
2222 b31c8676 Iustin Pop
    return
2223 b31c8676 Iustin Pop
2224 b31c8676 Iustin Pop
  def Exec(self, feedback_fn):
2225 b31c8676 Iustin Pop
    """Modifies a node.
2226 b31c8676 Iustin Pop

2227 b31c8676 Iustin Pop
    """
2228 3a5ba66a Iustin Pop
    node = self.node
2229 b31c8676 Iustin Pop
2230 b31c8676 Iustin Pop
    result = []
2231 b31c8676 Iustin Pop
2232 3a5ba66a Iustin Pop
    if self.op.offline is not None:
2233 3a5ba66a Iustin Pop
      node.offline = self.op.offline
2234 3a5ba66a Iustin Pop
      result.append(("offline", str(self.op.offline)))
2235 3a5ba66a Iustin Pop
      if self.op.offline == True and node.master_candidate:
2236 3a5ba66a Iustin Pop
        node.master_candidate = False
2237 3a5ba66a Iustin Pop
        result.append(("master_candidate", "auto-demotion due to offline"))
2238 3a5ba66a Iustin Pop
2239 b31c8676 Iustin Pop
    if self.op.master_candidate is not None:
2240 b31c8676 Iustin Pop
      node.master_candidate = self.op.master_candidate
2241 b31c8676 Iustin Pop
      result.append(("master_candidate", str(self.op.master_candidate)))
2242 56aa9fd5 Iustin Pop
      if self.op.master_candidate == False:
2243 56aa9fd5 Iustin Pop
        rrc = self.rpc.call_node_demote_from_mc(node.name)
2244 56aa9fd5 Iustin Pop
        if (rrc.failed or not isinstance(rrc.data, (tuple, list))
2245 56aa9fd5 Iustin Pop
            or len(rrc.data) != 2):
2246 56aa9fd5 Iustin Pop
          self.LogWarning("Node rpc error: %s" % rrc.error)
2247 56aa9fd5 Iustin Pop
        elif not rrc.data[0]:
2248 56aa9fd5 Iustin Pop
          self.LogWarning("Node failed to demote itself: %s" % rrc.data[1])
2249 b31c8676 Iustin Pop
2250 b31c8676 Iustin Pop
    # this will trigger configuration file update, if needed
2251 b31c8676 Iustin Pop
    self.cfg.Update(node)
2252 b31c8676 Iustin Pop
    # this will trigger job queue propagation or cleanup
2253 3a26773f Iustin Pop
    if self.op.node_name != self.cfg.GetMasterNode():
2254 3a26773f Iustin Pop
      self.context.ReaddNode(node)
2255 b31c8676 Iustin Pop
2256 b31c8676 Iustin Pop
    return result
2257 b31c8676 Iustin Pop
2258 b31c8676 Iustin Pop
2259 a8083063 Iustin Pop
class LUQueryClusterInfo(NoHooksLU):
2260 a8083063 Iustin Pop
  """Query cluster configuration.
2261 a8083063 Iustin Pop

2262 a8083063 Iustin Pop
  """
2263 a8083063 Iustin Pop
  _OP_REQP = []
2264 642339cf Guido Trotter
  REQ_BGL = False
2265 642339cf Guido Trotter
2266 642339cf Guido Trotter
  def ExpandNames(self):
2267 642339cf Guido Trotter
    self.needed_locks = {}
2268 a8083063 Iustin Pop
2269 a8083063 Iustin Pop
  def CheckPrereq(self):
2270 a8083063 Iustin Pop
    """No prerequsites needed for this LU.
2271 a8083063 Iustin Pop

2272 a8083063 Iustin Pop
    """
2273 a8083063 Iustin Pop
    pass
2274 a8083063 Iustin Pop
2275 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2276 a8083063 Iustin Pop
    """Return cluster config.
2277 a8083063 Iustin Pop

2278 a8083063 Iustin Pop
    """
2279 469f88e1 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
2280 a8083063 Iustin Pop
    result = {
2281 a8083063 Iustin Pop
      "software_version": constants.RELEASE_VERSION,
2282 a8083063 Iustin Pop
      "protocol_version": constants.PROTOCOL_VERSION,
2283 a8083063 Iustin Pop
      "config_version": constants.CONFIG_VERSION,
2284 a8083063 Iustin Pop
      "os_api_version": constants.OS_API_VERSION,
2285 a8083063 Iustin Pop
      "export_version": constants.EXPORT_VERSION,
2286 a8083063 Iustin Pop
      "architecture": (platform.architecture()[0], platform.machine()),
2287 469f88e1 Iustin Pop
      "name": cluster.cluster_name,
2288 469f88e1 Iustin Pop
      "master": cluster.master_node,
2289 02691904 Alexander Schreiber
      "default_hypervisor": cluster.default_hypervisor,
2290 469f88e1 Iustin Pop
      "enabled_hypervisors": cluster.enabled_hypervisors,
2291 469f88e1 Iustin Pop
      "hvparams": cluster.hvparams,
2292 469f88e1 Iustin Pop
      "beparams": cluster.beparams,
2293 4b7735f9 Iustin Pop
      "candidate_pool_size": cluster.candidate_pool_size,
2294 a8083063 Iustin Pop
      }
2295 a8083063 Iustin Pop
2296 a8083063 Iustin Pop
    return result
2297 a8083063 Iustin Pop
2298 a8083063 Iustin Pop
2299 ae5849b5 Michael Hanselmann
class LUQueryConfigValues(NoHooksLU):
2300 ae5849b5 Michael Hanselmann
  """Return configuration values.
2301 a8083063 Iustin Pop

2302 a8083063 Iustin Pop
  """
2303 a8083063 Iustin Pop
  _OP_REQP = []
2304 642339cf Guido Trotter
  REQ_BGL = False
2305 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet()
2306 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag")
2307 642339cf Guido Trotter
2308 642339cf Guido Trotter
  def ExpandNames(self):
2309 642339cf Guido Trotter
    self.needed_locks = {}
2310 a8083063 Iustin Pop
2311 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
2312 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
2313 ae5849b5 Michael Hanselmann
                       selected=self.op.output_fields)
2314 ae5849b5 Michael Hanselmann
2315 a8083063 Iustin Pop
  def CheckPrereq(self):
2316 a8083063 Iustin Pop
    """No prerequisites.
2317 a8083063 Iustin Pop

2318 a8083063 Iustin Pop
    """
2319 a8083063 Iustin Pop
    pass
2320 a8083063 Iustin Pop
2321 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2322 a8083063 Iustin Pop
    """Dump a representation of the cluster config to the standard output.
2323 a8083063 Iustin Pop

2324 a8083063 Iustin Pop
    """
2325 ae5849b5 Michael Hanselmann
    values = []
2326 ae5849b5 Michael Hanselmann
    for field in self.op.output_fields:
2327 ae5849b5 Michael Hanselmann
      if field == "cluster_name":
2328 3ccafd0e Iustin Pop
        entry = self.cfg.GetClusterName()
2329 ae5849b5 Michael Hanselmann
      elif field == "master_node":
2330 3ccafd0e Iustin Pop
        entry = self.cfg.GetMasterNode()
2331 3ccafd0e Iustin Pop
      elif field == "drain_flag":
2332 3ccafd0e Iustin Pop
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
2333 ae5849b5 Michael Hanselmann
      else:
2334 ae5849b5 Michael Hanselmann
        raise errors.ParameterError(field)
2335 3ccafd0e Iustin Pop
      values.append(entry)
2336 ae5849b5 Michael Hanselmann
    return values
2337 a8083063 Iustin Pop
2338 a8083063 Iustin Pop
2339 a8083063 Iustin Pop
class LUActivateInstanceDisks(NoHooksLU):
2340 a8083063 Iustin Pop
  """Bring up an instance's disks.
2341 a8083063 Iustin Pop

2342 a8083063 Iustin Pop
  """
2343 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2344 f22a8ba3 Guido Trotter
  REQ_BGL = False
2345 f22a8ba3 Guido Trotter
2346 f22a8ba3 Guido Trotter
  def ExpandNames(self):
2347 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
2348 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2349 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2350 f22a8ba3 Guido Trotter
2351 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
2352 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
2353 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
2354 a8083063 Iustin Pop
2355 a8083063 Iustin Pop
  def CheckPrereq(self):
2356 a8083063 Iustin Pop
    """Check prerequisites.
2357 a8083063 Iustin Pop

2358 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2359 a8083063 Iustin Pop

2360 a8083063 Iustin Pop
    """
2361 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2362 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
2363 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2364 43017d26 Iustin Pop
    _CheckNodeOnline(self, self.instance.primary_node)
2365 a8083063 Iustin Pop
2366 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2367 a8083063 Iustin Pop
    """Activate the disks.
2368 a8083063 Iustin Pop

2369 a8083063 Iustin Pop
    """
2370 b9bddb6b Iustin Pop
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
2371 a8083063 Iustin Pop
    if not disks_ok:
2372 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot activate block devices")
2373 a8083063 Iustin Pop
2374 a8083063 Iustin Pop
    return disks_info
2375 a8083063 Iustin Pop
2376 a8083063 Iustin Pop
2377 b9bddb6b Iustin Pop
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
2378 a8083063 Iustin Pop
  """Prepare the block devices for an instance.
2379 a8083063 Iustin Pop

2380 a8083063 Iustin Pop
  This sets up the block devices on all nodes.
2381 a8083063 Iustin Pop

2382 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
2383 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
2384 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
2385 e4376078 Iustin Pop
  @param instance: the instance for whose disks we assemble
2386 e4376078 Iustin Pop
  @type ignore_secondaries: boolean
2387 e4376078 Iustin Pop
  @param ignore_secondaries: if true, errors on secondary nodes
2388 e4376078 Iustin Pop
      won't result in an error return from the function
2389 e4376078 Iustin Pop
  @return: False if the operation failed, otherwise a list of
2390 e4376078 Iustin Pop
      (host, instance_visible_name, node_visible_name)
2391 e4376078 Iustin Pop
      with the mapping from node devices to instance devices
2392 a8083063 Iustin Pop

2393 a8083063 Iustin Pop
  """
2394 a8083063 Iustin Pop
  device_info = []
2395 a8083063 Iustin Pop
  disks_ok = True
2396 fdbd668d Iustin Pop
  iname = instance.name
2397 fdbd668d Iustin Pop
  # With the two passes mechanism we try to reduce the window of
2398 fdbd668d Iustin Pop
  # opportunity for the race condition of switching DRBD to primary
2399 fdbd668d Iustin Pop
  # before handshaking occured, but we do not eliminate it
2400 fdbd668d Iustin Pop
2401 fdbd668d Iustin Pop
  # The proper fix would be to wait (with some limits) until the
2402 fdbd668d Iustin Pop
  # connection has been made and drbd transitions from WFConnection
2403 fdbd668d Iustin Pop
  # into any other network-connected state (Connected, SyncTarget,
2404 fdbd668d Iustin Pop
  # SyncSource, etc.)
2405 fdbd668d Iustin Pop
2406 fdbd668d Iustin Pop
  # 1st pass, assemble on all nodes in secondary mode
2407 a8083063 Iustin Pop
  for inst_disk in instance.disks:
2408 a8083063 Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2409 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(node_disk, node)
2410 72737a7f Iustin Pop
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
2411 781de953 Iustin Pop
      if result.failed or not result:
2412 86d9d3bb Iustin Pop
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2413 86d9d3bb Iustin Pop
                           " (is_primary=False, pass=1)",
2414 86d9d3bb Iustin Pop
                           inst_disk.iv_name, node)
2415 fdbd668d Iustin Pop
        if not ignore_secondaries:
2416 a8083063 Iustin Pop
          disks_ok = False
2417 fdbd668d Iustin Pop
2418 fdbd668d Iustin Pop
  # FIXME: race condition on drbd migration to primary
2419 fdbd668d Iustin Pop
2420 fdbd668d Iustin Pop
  # 2nd pass, do only the primary node
2421 fdbd668d Iustin Pop
  for inst_disk in instance.disks:
2422 fdbd668d Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2423 fdbd668d Iustin Pop
      if node != instance.primary_node:
2424 fdbd668d Iustin Pop
        continue
2425 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(node_disk, node)
2426 72737a7f Iustin Pop
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2427 781de953 Iustin Pop
      if result.failed or not result:
2428 86d9d3bb Iustin Pop
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
2429 86d9d3bb Iustin Pop
                           " (is_primary=True, pass=2)",
2430 86d9d3bb Iustin Pop
                           inst_disk.iv_name, node)
2431 fdbd668d Iustin Pop
        disks_ok = False
2432 2b17c3c4 Iustin Pop
    device_info.append((instance.primary_node, inst_disk.iv_name, result.data))
2433 a8083063 Iustin Pop
2434 b352ab5b Iustin Pop
  # leave the disks configured for the primary node
2435 b352ab5b Iustin Pop
  # this is a workaround that would be fixed better by
2436 b352ab5b Iustin Pop
  # improving the logical/physical id handling
2437 b352ab5b Iustin Pop
  for disk in instance.disks:
2438 b9bddb6b Iustin Pop
    lu.cfg.SetDiskID(disk, instance.primary_node)
2439 b352ab5b Iustin Pop
2440 a8083063 Iustin Pop
  return disks_ok, device_info
2441 a8083063 Iustin Pop
2442 a8083063 Iustin Pop
2443 b9bddb6b Iustin Pop
def _StartInstanceDisks(lu, instance, force):
2444 3ecf6786 Iustin Pop
  """Start the disks of an instance.
2445 3ecf6786 Iustin Pop

2446 3ecf6786 Iustin Pop
  """
2447 b9bddb6b Iustin Pop
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2448 fe7b0351 Michael Hanselmann
                                           ignore_secondaries=force)
2449 fe7b0351 Michael Hanselmann
  if not disks_ok:
2450 b9bddb6b Iustin Pop
    _ShutdownInstanceDisks(lu, instance)
2451 fe7b0351 Michael Hanselmann
    if force is not None and not force:
2452 86d9d3bb Iustin Pop
      lu.proc.LogWarning("", hint="If the message above refers to a"
2453 86d9d3bb Iustin Pop
                         " secondary node,"
2454 86d9d3bb Iustin Pop
                         " you can retry the operation using '--force'.")
2455 3ecf6786 Iustin Pop
    raise errors.OpExecError("Disk consistency error")
2456 fe7b0351 Michael Hanselmann
2457 fe7b0351 Michael Hanselmann
2458 a8083063 Iustin Pop
class LUDeactivateInstanceDisks(NoHooksLU):
2459 a8083063 Iustin Pop
  """Shutdown an instance's disks.
2460 a8083063 Iustin Pop

2461 a8083063 Iustin Pop
  """
2462 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2463 f22a8ba3 Guido Trotter
  REQ_BGL = False
2464 f22a8ba3 Guido Trotter
2465 f22a8ba3 Guido Trotter
  def ExpandNames(self):
2466 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
2467 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2468 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2469 f22a8ba3 Guido Trotter
2470 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
2471 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
2472 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
2473 a8083063 Iustin Pop
2474 a8083063 Iustin Pop
  def CheckPrereq(self):
2475 a8083063 Iustin Pop
    """Check prerequisites.
2476 a8083063 Iustin Pop

2477 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2478 a8083063 Iustin Pop

2479 a8083063 Iustin Pop
    """
2480 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2481 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
2482 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2483 a8083063 Iustin Pop
2484 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2485 a8083063 Iustin Pop
    """Deactivate the disks
2486 a8083063 Iustin Pop

2487 a8083063 Iustin Pop
    """
2488 a8083063 Iustin Pop
    instance = self.instance
2489 b9bddb6b Iustin Pop
    _SafeShutdownInstanceDisks(self, instance)
2490 a8083063 Iustin Pop
2491 a8083063 Iustin Pop
2492 b9bddb6b Iustin Pop
def _SafeShutdownInstanceDisks(lu, instance):
2493 155d6c75 Guido Trotter
  """Shutdown block devices of an instance.
2494 155d6c75 Guido Trotter

2495 155d6c75 Guido Trotter
  This function checks if an instance is running, before calling
2496 155d6c75 Guido Trotter
  _ShutdownInstanceDisks.
2497 155d6c75 Guido Trotter

2498 155d6c75 Guido Trotter
  """
2499 72737a7f Iustin Pop
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2500 72737a7f Iustin Pop
                                      [instance.hypervisor])
2501 155d6c75 Guido Trotter
  ins_l = ins_l[instance.primary_node]
2502 781de953 Iustin Pop
  if ins_l.failed or not isinstance(ins_l.data, list):
2503 155d6c75 Guido Trotter
    raise errors.OpExecError("Can't contact node '%s'" %
2504 155d6c75 Guido Trotter
                             instance.primary_node)
2505 155d6c75 Guido Trotter
2506 781de953 Iustin Pop
  if instance.name in ins_l.data:
2507 155d6c75 Guido Trotter
    raise errors.OpExecError("Instance is running, can't shutdown"
2508 155d6c75 Guido Trotter
                             " block devices.")
2509 155d6c75 Guido Trotter
2510 b9bddb6b Iustin Pop
  _ShutdownInstanceDisks(lu, instance)
2511 a8083063 Iustin Pop
2512 a8083063 Iustin Pop
2513 b9bddb6b Iustin Pop
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2514 a8083063 Iustin Pop
  """Shutdown block devices of an instance.
2515 a8083063 Iustin Pop

2516 a8083063 Iustin Pop
  This does the shutdown on all nodes of the instance.
2517 a8083063 Iustin Pop

2518 a8083063 Iustin Pop
  If the ignore_primary is false, errors on the primary node are
2519 a8083063 Iustin Pop
  ignored.
2520 a8083063 Iustin Pop

2521 a8083063 Iustin Pop
  """
2522 a8083063 Iustin Pop
  result = True
2523 a8083063 Iustin Pop
  for disk in instance.disks:
2524 a8083063 Iustin Pop
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2525 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(top_disk, node)
2526 781de953 Iustin Pop
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
2527 781de953 Iustin Pop
      if result.failed or not result.data:
2528 9a4f63d1 Iustin Pop
        logging.error("Could not shutdown block device %s on node %s",
2529 9a4f63d1 Iustin Pop
                      disk.iv_name, node)
2530 a8083063 Iustin Pop
        if not ignore_primary or node != instance.primary_node:
2531 a8083063 Iustin Pop
          result = False
2532 a8083063 Iustin Pop
  return result
2533 a8083063 Iustin Pop
2534 a8083063 Iustin Pop
2535 9ca87a96 Iustin Pop
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
2536 d4f16fd9 Iustin Pop
  """Checks if a node has enough free memory.
2537 d4f16fd9 Iustin Pop

2538 d4f16fd9 Iustin Pop
  This function check if a given node has the needed amount of free
2539 d4f16fd9 Iustin Pop
  memory. In case the node has less memory or we cannot get the
2540 d4f16fd9 Iustin Pop
  information from the node, this function raise an OpPrereqError
2541 d4f16fd9 Iustin Pop
  exception.
2542 d4f16fd9 Iustin Pop

2543 b9bddb6b Iustin Pop
  @type lu: C{LogicalUnit}
2544 b9bddb6b Iustin Pop
  @param lu: a logical unit from which we get configuration data
2545 e69d05fd Iustin Pop
  @type node: C{str}
2546 e69d05fd Iustin Pop
  @param node: the node to check
2547 e69d05fd Iustin Pop
  @type reason: C{str}
2548 e69d05fd Iustin Pop
  @param reason: string to use in the error message
2549 e69d05fd Iustin Pop
  @type requested: C{int}
2550 e69d05fd Iustin Pop
  @param requested: the amount of memory in MiB to check for
2551 9ca87a96 Iustin Pop
  @type hypervisor_name: C{str}
2552 9ca87a96 Iustin Pop
  @param hypervisor_name: the hypervisor to ask for memory stats
2553 e69d05fd Iustin Pop
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2554 e69d05fd Iustin Pop
      we cannot check the node
2555 d4f16fd9 Iustin Pop

2556 d4f16fd9 Iustin Pop
  """
2557 9ca87a96 Iustin Pop
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
2558 781de953 Iustin Pop
  nodeinfo[node].Raise()
2559 781de953 Iustin Pop
  free_mem = nodeinfo[node].data.get('memory_free')
2560 d4f16fd9 Iustin Pop
  if not isinstance(free_mem, int):
2561 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2562 d4f16fd9 Iustin Pop
                             " was '%s'" % (node, free_mem))
2563 d4f16fd9 Iustin Pop
  if requested > free_mem:
2564 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2565 d4f16fd9 Iustin Pop
                             " needed %s MiB, available %s MiB" %
2566 d4f16fd9 Iustin Pop
                             (node, reason, requested, free_mem))
2567 d4f16fd9 Iustin Pop
2568 d4f16fd9 Iustin Pop
2569 a8083063 Iustin Pop
class LUStartupInstance(LogicalUnit):
2570 a8083063 Iustin Pop
  """Starts an instance.
2571 a8083063 Iustin Pop

2572 a8083063 Iustin Pop
  """
2573 a8083063 Iustin Pop
  HPATH = "instance-start"
2574 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2575 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "force"]
2576 e873317a Guido Trotter
  REQ_BGL = False
2577 e873317a Guido Trotter
2578 e873317a Guido Trotter
  def ExpandNames(self):
2579 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2580 a8083063 Iustin Pop
2581 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2582 a8083063 Iustin Pop
    """Build hooks env.
2583 a8083063 Iustin Pop

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

2586 a8083063 Iustin Pop
    """
2587 a8083063 Iustin Pop
    env = {
2588 a8083063 Iustin Pop
      "FORCE": self.op.force,
2589 a8083063 Iustin Pop
      }
2590 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2591 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2592 a8083063 Iustin Pop
    return env, nl, nl
2593 a8083063 Iustin Pop
2594 a8083063 Iustin Pop
  def CheckPrereq(self):
2595 a8083063 Iustin Pop
    """Check prerequisites.
2596 a8083063 Iustin Pop

2597 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2598 a8083063 Iustin Pop

2599 a8083063 Iustin Pop
    """
2600 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2601 e873317a Guido Trotter
    assert self.instance is not None, \
2602 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2603 a8083063 Iustin Pop
2604 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
2605 7527a8a4 Iustin Pop
2606 338e51e8 Iustin Pop
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2607 a8083063 Iustin Pop
    # check bridges existance
2608 b9bddb6b Iustin Pop
    _CheckInstanceBridgesExist(self, instance)
2609 a8083063 Iustin Pop
2610 b9bddb6b Iustin Pop
    _CheckNodeFreeMemory(self, instance.primary_node,
2611 d4f16fd9 Iustin Pop
                         "starting instance %s" % instance.name,
2612 338e51e8 Iustin Pop
                         bep[constants.BE_MEMORY], instance.hypervisor)
2613 d4f16fd9 Iustin Pop
2614 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2615 a8083063 Iustin Pop
    """Start the instance.
2616 a8083063 Iustin Pop

2617 a8083063 Iustin Pop
    """
2618 a8083063 Iustin Pop
    instance = self.instance
2619 a8083063 Iustin Pop
    force = self.op.force
2620 a8083063 Iustin Pop
    extra_args = getattr(self.op, "extra_args", "")
2621 a8083063 Iustin Pop
2622 fe482621 Iustin Pop
    self.cfg.MarkInstanceUp(instance.name)
2623 fe482621 Iustin Pop
2624 a8083063 Iustin Pop
    node_current = instance.primary_node
2625 a8083063 Iustin Pop
2626 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, instance, force)
2627 a8083063 Iustin Pop
2628 781de953 Iustin Pop
    result = self.rpc.call_instance_start(node_current, instance, extra_args)
2629 dd279568 Iustin Pop
    msg = result.RemoteFailMsg()
2630 dd279568 Iustin Pop
    if msg:
2631 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, instance)
2632 dd279568 Iustin Pop
      raise errors.OpExecError("Could not start instance: %s" % msg)
2633 a8083063 Iustin Pop
2634 a8083063 Iustin Pop
2635 bf6929a2 Alexander Schreiber
class LURebootInstance(LogicalUnit):
2636 bf6929a2 Alexander Schreiber
  """Reboot an instance.
2637 bf6929a2 Alexander Schreiber

2638 bf6929a2 Alexander Schreiber
  """
2639 bf6929a2 Alexander Schreiber
  HPATH = "instance-reboot"
2640 bf6929a2 Alexander Schreiber
  HTYPE = constants.HTYPE_INSTANCE
2641 bf6929a2 Alexander Schreiber
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2642 e873317a Guido Trotter
  REQ_BGL = False
2643 e873317a Guido Trotter
2644 e873317a Guido Trotter
  def ExpandNames(self):
2645 0fcc5db3 Guido Trotter
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2646 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
2647 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL]:
2648 0fcc5db3 Guido Trotter
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2649 0fcc5db3 Guido Trotter
                                  (constants.INSTANCE_REBOOT_SOFT,
2650 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
2651 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL))
2652 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2653 bf6929a2 Alexander Schreiber
2654 bf6929a2 Alexander Schreiber
  def BuildHooksEnv(self):
2655 bf6929a2 Alexander Schreiber
    """Build hooks env.
2656 bf6929a2 Alexander Schreiber

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

2659 bf6929a2 Alexander Schreiber
    """
2660 bf6929a2 Alexander Schreiber
    env = {
2661 bf6929a2 Alexander Schreiber
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2662 bf6929a2 Alexander Schreiber
      }
2663 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2664 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2665 bf6929a2 Alexander Schreiber
    return env, nl, nl
2666 bf6929a2 Alexander Schreiber
2667 bf6929a2 Alexander Schreiber
  def CheckPrereq(self):
2668 bf6929a2 Alexander Schreiber
    """Check prerequisites.
2669 bf6929a2 Alexander Schreiber

2670 bf6929a2 Alexander Schreiber
    This checks that the instance is in the cluster.
2671 bf6929a2 Alexander Schreiber

2672 bf6929a2 Alexander Schreiber
    """
2673 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2674 e873317a Guido Trotter
    assert self.instance is not None, \
2675 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2676 bf6929a2 Alexander Schreiber
2677 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
2678 7527a8a4 Iustin Pop
2679 bf6929a2 Alexander Schreiber
    # check bridges existance
2680 b9bddb6b Iustin Pop
    _CheckInstanceBridgesExist(self, instance)
2681 bf6929a2 Alexander Schreiber
2682 bf6929a2 Alexander Schreiber
  def Exec(self, feedback_fn):
2683 bf6929a2 Alexander Schreiber
    """Reboot the instance.
2684 bf6929a2 Alexander Schreiber

2685 bf6929a2 Alexander Schreiber
    """
2686 bf6929a2 Alexander Schreiber
    instance = self.instance
2687 bf6929a2 Alexander Schreiber
    ignore_secondaries = self.op.ignore_secondaries
2688 bf6929a2 Alexander Schreiber
    reboot_type = self.op.reboot_type
2689 bf6929a2 Alexander Schreiber
    extra_args = getattr(self.op, "extra_args", "")
2690 bf6929a2 Alexander Schreiber
2691 bf6929a2 Alexander Schreiber
    node_current = instance.primary_node
2692 bf6929a2 Alexander Schreiber
2693 bf6929a2 Alexander Schreiber
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2694 bf6929a2 Alexander Schreiber
                       constants.INSTANCE_REBOOT_HARD]:
2695 781de953 Iustin Pop
      result = self.rpc.call_instance_reboot(node_current, instance,
2696 781de953 Iustin Pop
                                             reboot_type, extra_args)
2697 781de953 Iustin Pop
      if result.failed or not result.data:
2698 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("Could not reboot instance")
2699 bf6929a2 Alexander Schreiber
    else:
2700 72737a7f Iustin Pop
      if not self.rpc.call_instance_shutdown(node_current, instance):
2701 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("could not shutdown instance for full reboot")
2702 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, instance)
2703 b9bddb6b Iustin Pop
      _StartInstanceDisks(self, instance, ignore_secondaries)
2704 781de953 Iustin Pop
      result = self.rpc.call_instance_start(node_current, instance, extra_args)
2705 dd279568 Iustin Pop
      msg = result.RemoteFailMsg()
2706 dd279568 Iustin Pop
      if msg:
2707 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
2708 dd279568 Iustin Pop
        raise errors.OpExecError("Could not start instance for"
2709 dd279568 Iustin Pop
                                 " full reboot: %s" % msg)
2710 bf6929a2 Alexander Schreiber
2711 bf6929a2 Alexander Schreiber
    self.cfg.MarkInstanceUp(instance.name)
2712 bf6929a2 Alexander Schreiber
2713 bf6929a2 Alexander Schreiber
2714 a8083063 Iustin Pop
class LUShutdownInstance(LogicalUnit):
2715 a8083063 Iustin Pop
  """Shutdown an instance.
2716 a8083063 Iustin Pop

2717 a8083063 Iustin Pop
  """
2718 a8083063 Iustin Pop
  HPATH = "instance-stop"
2719 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2720 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2721 e873317a Guido Trotter
  REQ_BGL = False
2722 e873317a Guido Trotter
2723 e873317a Guido Trotter
  def ExpandNames(self):
2724 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2725 a8083063 Iustin Pop
2726 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2727 a8083063 Iustin Pop
    """Build hooks env.
2728 a8083063 Iustin Pop

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

2731 a8083063 Iustin Pop
    """
2732 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2733 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2734 a8083063 Iustin Pop
    return env, nl, nl
2735 a8083063 Iustin Pop
2736 a8083063 Iustin Pop
  def CheckPrereq(self):
2737 a8083063 Iustin Pop
    """Check prerequisites.
2738 a8083063 Iustin Pop

2739 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2740 a8083063 Iustin Pop

2741 a8083063 Iustin Pop
    """
2742 e873317a Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2743 e873317a Guido Trotter
    assert self.instance is not None, \
2744 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2745 43017d26 Iustin Pop
    _CheckNodeOnline(self, self.instance.primary_node)
2746 a8083063 Iustin Pop
2747 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2748 a8083063 Iustin Pop
    """Shutdown the instance.
2749 a8083063 Iustin Pop

2750 a8083063 Iustin Pop
    """
2751 a8083063 Iustin Pop
    instance = self.instance
2752 a8083063 Iustin Pop
    node_current = instance.primary_node
2753 fe482621 Iustin Pop
    self.cfg.MarkInstanceDown(instance.name)
2754 781de953 Iustin Pop
    result = self.rpc.call_instance_shutdown(node_current, instance)
2755 781de953 Iustin Pop
    if result.failed or not result.data:
2756 86d9d3bb Iustin Pop
      self.proc.LogWarning("Could not shutdown instance")
2757 a8083063 Iustin Pop
2758 b9bddb6b Iustin Pop
    _ShutdownInstanceDisks(self, instance)
2759 a8083063 Iustin Pop
2760 a8083063 Iustin Pop
2761 fe7b0351 Michael Hanselmann
class LUReinstallInstance(LogicalUnit):
2762 fe7b0351 Michael Hanselmann
  """Reinstall an instance.
2763 fe7b0351 Michael Hanselmann

2764 fe7b0351 Michael Hanselmann
  """
2765 fe7b0351 Michael Hanselmann
  HPATH = "instance-reinstall"
2766 fe7b0351 Michael Hanselmann
  HTYPE = constants.HTYPE_INSTANCE
2767 fe7b0351 Michael Hanselmann
  _OP_REQP = ["instance_name"]
2768 4e0b4d2d Guido Trotter
  REQ_BGL = False
2769 4e0b4d2d Guido Trotter
2770 4e0b4d2d Guido Trotter
  def ExpandNames(self):
2771 4e0b4d2d Guido Trotter
    self._ExpandAndLockInstance()
2772 fe7b0351 Michael Hanselmann
2773 fe7b0351 Michael Hanselmann
  def BuildHooksEnv(self):
2774 fe7b0351 Michael Hanselmann
    """Build hooks env.
2775 fe7b0351 Michael Hanselmann

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

2778 fe7b0351 Michael Hanselmann
    """
2779 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2780 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2781 fe7b0351 Michael Hanselmann
    return env, nl, nl
2782 fe7b0351 Michael Hanselmann
2783 fe7b0351 Michael Hanselmann
  def CheckPrereq(self):
2784 fe7b0351 Michael Hanselmann
    """Check prerequisites.
2785 fe7b0351 Michael Hanselmann

2786 fe7b0351 Michael Hanselmann
    This checks that the instance is in the cluster and is not running.
2787 fe7b0351 Michael Hanselmann

2788 fe7b0351 Michael Hanselmann
    """
2789 4e0b4d2d Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2790 4e0b4d2d Guido Trotter
    assert instance is not None, \
2791 4e0b4d2d Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2792 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
2793 4e0b4d2d Guido Trotter
2794 fe7b0351 Michael Hanselmann
    if instance.disk_template == constants.DT_DISKLESS:
2795 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2796 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2797 fe7b0351 Michael Hanselmann
    if instance.status != "down":
2798 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2799 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2800 72737a7f Iustin Pop
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2801 72737a7f Iustin Pop
                                              instance.name,
2802 72737a7f Iustin Pop
                                              instance.hypervisor)
2803 781de953 Iustin Pop
    if remote_info.failed or remote_info.data:
2804 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2805 3ecf6786 Iustin Pop
                                 (self.op.instance_name,
2806 3ecf6786 Iustin Pop
                                  instance.primary_node))
2807 d0834de3 Michael Hanselmann
2808 d0834de3 Michael Hanselmann
    self.op.os_type = getattr(self.op, "os_type", None)
2809 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2810 d0834de3 Michael Hanselmann
      # OS verification
2811 d0834de3 Michael Hanselmann
      pnode = self.cfg.GetNodeInfo(
2812 d0834de3 Michael Hanselmann
        self.cfg.ExpandNodeName(instance.primary_node))
2813 d0834de3 Michael Hanselmann
      if pnode is None:
2814 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2815 3ecf6786 Iustin Pop
                                   self.op.pnode)
2816 781de953 Iustin Pop
      result = self.rpc.call_os_get(pnode.name, self.op.os_type)
2817 781de953 Iustin Pop
      result.Raise()
2818 781de953 Iustin Pop
      if not isinstance(result.data, objects.OS):
2819 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2820 3ecf6786 Iustin Pop
                                   " primary node"  % self.op.os_type)
2821 d0834de3 Michael Hanselmann
2822 fe7b0351 Michael Hanselmann
    self.instance = instance
2823 fe7b0351 Michael Hanselmann
2824 fe7b0351 Michael Hanselmann
  def Exec(self, feedback_fn):
2825 fe7b0351 Michael Hanselmann
    """Reinstall the instance.
2826 fe7b0351 Michael Hanselmann

2827 fe7b0351 Michael Hanselmann
    """
2828 fe7b0351 Michael Hanselmann
    inst = self.instance
2829 fe7b0351 Michael Hanselmann
2830 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2831 d0834de3 Michael Hanselmann
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2832 d0834de3 Michael Hanselmann
      inst.os = self.op.os_type
2833 97abc79f Iustin Pop
      self.cfg.Update(inst)
2834 d0834de3 Michael Hanselmann
2835 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, inst, None)
2836 fe7b0351 Michael Hanselmann
    try:
2837 fe7b0351 Michael Hanselmann
      feedback_fn("Running the instance OS create scripts...")
2838 781de953 Iustin Pop
      result = self.rpc.call_instance_os_add(inst.primary_node, inst)
2839 20e01edd Iustin Pop
      msg = result.RemoteFailMsg()
2840 20e01edd Iustin Pop
      if msg:
2841 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Could not install OS for instance %s"
2842 20e01edd Iustin Pop
                                 " on node %s: %s" %
2843 20e01edd Iustin Pop
                                 (inst.name, inst.primary_node, msg))
2844 fe7b0351 Michael Hanselmann
    finally:
2845 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, inst)
2846 fe7b0351 Michael Hanselmann
2847 fe7b0351 Michael Hanselmann
2848 decd5f45 Iustin Pop
class LURenameInstance(LogicalUnit):
2849 decd5f45 Iustin Pop
  """Rename an instance.
2850 decd5f45 Iustin Pop

2851 decd5f45 Iustin Pop
  """
2852 decd5f45 Iustin Pop
  HPATH = "instance-rename"
2853 decd5f45 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2854 decd5f45 Iustin Pop
  _OP_REQP = ["instance_name", "new_name"]
2855 decd5f45 Iustin Pop
2856 decd5f45 Iustin Pop
  def BuildHooksEnv(self):
2857 decd5f45 Iustin Pop
    """Build hooks env.
2858 decd5f45 Iustin Pop

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

2861 decd5f45 Iustin Pop
    """
2862 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2863 decd5f45 Iustin Pop
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2864 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2865 decd5f45 Iustin Pop
    return env, nl, nl
2866 decd5f45 Iustin Pop
2867 decd5f45 Iustin Pop
  def CheckPrereq(self):
2868 decd5f45 Iustin Pop
    """Check prerequisites.
2869 decd5f45 Iustin Pop

2870 decd5f45 Iustin Pop
    This checks that the instance is in the cluster and is not running.
2871 decd5f45 Iustin Pop

2872 decd5f45 Iustin Pop
    """
2873 decd5f45 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2874 decd5f45 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2875 decd5f45 Iustin Pop
    if instance is None:
2876 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2877 decd5f45 Iustin Pop
                                 self.op.instance_name)
2878 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, instance.primary_node)
2879 7527a8a4 Iustin Pop
2880 decd5f45 Iustin Pop
    if instance.status != "down":
2881 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2882 decd5f45 Iustin Pop
                                 self.op.instance_name)
2883 72737a7f Iustin Pop
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2884 72737a7f Iustin Pop
                                              instance.name,
2885 72737a7f Iustin Pop
                                              instance.hypervisor)
2886 781de953 Iustin Pop
    remote_info.Raise()
2887 781de953 Iustin Pop
    if remote_info.data:
2888 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2889 decd5f45 Iustin Pop
                                 (self.op.instance_name,
2890 decd5f45 Iustin Pop
                                  instance.primary_node))
2891 decd5f45 Iustin Pop
    self.instance = instance
2892 decd5f45 Iustin Pop
2893 decd5f45 Iustin Pop
    # new name verification
2894 89e1fc26 Iustin Pop
    name_info = utils.HostInfo(self.op.new_name)
2895 decd5f45 Iustin Pop
2896 89e1fc26 Iustin Pop
    self.op.new_name = new_name = name_info.name
2897 7bde3275 Guido Trotter
    instance_list = self.cfg.GetInstanceList()
2898 7bde3275 Guido Trotter
    if new_name in instance_list:
2899 7bde3275 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2900 c09f363f Manuel Franceschini
                                 new_name)
2901 7bde3275 Guido Trotter
2902 decd5f45 Iustin Pop
    if not getattr(self.op, "ignore_ip", False):
2903 937f983d Guido Trotter
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2904 decd5f45 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2905 89e1fc26 Iustin Pop
                                   (name_info.ip, new_name))
2906 decd5f45 Iustin Pop
2907 decd5f45 Iustin Pop
2908 decd5f45 Iustin Pop
  def Exec(self, feedback_fn):
2909 decd5f45 Iustin Pop
    """Reinstall the instance.
2910 decd5f45 Iustin Pop

2911 decd5f45 Iustin Pop
    """
2912 decd5f45 Iustin Pop
    inst = self.instance
2913 decd5f45 Iustin Pop
    old_name = inst.name
2914 decd5f45 Iustin Pop
2915 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2916 b23c4333 Manuel Franceschini
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2917 b23c4333 Manuel Franceschini
2918 decd5f45 Iustin Pop
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2919 74b5913f Guido Trotter
    # Change the instance lock. This is definitely safe while we hold the BGL
2920 cb4e8387 Iustin Pop
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
2921 74b5913f Guido Trotter
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2922 decd5f45 Iustin Pop
2923 decd5f45 Iustin Pop
    # re-read the instance from the configuration after rename
2924 decd5f45 Iustin Pop
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2925 decd5f45 Iustin Pop
2926 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2927 b23c4333 Manuel Franceschini
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2928 72737a7f Iustin Pop
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2929 72737a7f Iustin Pop
                                                     old_file_storage_dir,
2930 72737a7f Iustin Pop
                                                     new_file_storage_dir)
2931 781de953 Iustin Pop
      result.Raise()
2932 781de953 Iustin Pop
      if not result.data:
2933 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2934 b23c4333 Manuel Franceschini
                                 " directory '%s' to '%s' (but the instance"
2935 b23c4333 Manuel Franceschini
                                 " has been renamed in Ganeti)" % (
2936 b23c4333 Manuel Franceschini
                                 inst.primary_node, old_file_storage_dir,
2937 b23c4333 Manuel Franceschini
                                 new_file_storage_dir))
2938 b23c4333 Manuel Franceschini
2939 781de953 Iustin Pop
      if not result.data[0]:
2940 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2941 b23c4333 Manuel Franceschini
                                 " (but the instance has been renamed in"
2942 b23c4333 Manuel Franceschini
                                 " Ganeti)" % (old_file_storage_dir,
2943 b23c4333 Manuel Franceschini
                                               new_file_storage_dir))
2944 b23c4333 Manuel Franceschini
2945 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, inst, None)
2946 decd5f45 Iustin Pop
    try:
2947 781de953 Iustin Pop
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
2948 781de953 Iustin Pop
                                                 old_name)
2949 781de953 Iustin Pop
      if result.failed or not result.data:
2950 6291574d Alexander Schreiber
        msg = ("Could not run OS rename script for instance %s on node %s"
2951 6291574d Alexander Schreiber
               " (but the instance has been renamed in Ganeti)" %
2952 decd5f45 Iustin Pop
               (inst.name, inst.primary_node))
2953 86d9d3bb Iustin Pop
        self.proc.LogWarning(msg)
2954 decd5f45 Iustin Pop
    finally:
2955 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, inst)
2956 decd5f45 Iustin Pop
2957 decd5f45 Iustin Pop
2958 a8083063 Iustin Pop
class LURemoveInstance(LogicalUnit):
2959 a8083063 Iustin Pop
  """Remove an instance.
2960 a8083063 Iustin Pop

2961 a8083063 Iustin Pop
  """
2962 a8083063 Iustin Pop
  HPATH = "instance-remove"
2963 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2964 5c54b832 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_failures"]
2965 cf472233 Guido Trotter
  REQ_BGL = False
2966 cf472233 Guido Trotter
2967 cf472233 Guido Trotter
  def ExpandNames(self):
2968 cf472233 Guido Trotter
    self._ExpandAndLockInstance()
2969 cf472233 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2970 cf472233 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2971 cf472233 Guido Trotter
2972 cf472233 Guido Trotter
  def DeclareLocks(self, level):
2973 cf472233 Guido Trotter
    if level == locking.LEVEL_NODE:
2974 cf472233 Guido Trotter
      self._LockInstancesNodes()
2975 a8083063 Iustin Pop
2976 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2977 a8083063 Iustin Pop
    """Build hooks env.
2978 a8083063 Iustin Pop

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

2981 a8083063 Iustin Pop
    """
2982 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2983 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()]
2984 a8083063 Iustin Pop
    return env, nl, nl
2985 a8083063 Iustin Pop
2986 a8083063 Iustin Pop
  def CheckPrereq(self):
2987 a8083063 Iustin Pop
    """Check prerequisites.
2988 a8083063 Iustin Pop

2989 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2990 a8083063 Iustin Pop

2991 a8083063 Iustin Pop
    """
2992 cf472233 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2993 cf472233 Guido Trotter
    assert self.instance is not None, \
2994 cf472233 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2995 a8083063 Iustin Pop
2996 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2997 a8083063 Iustin Pop
    """Remove the instance.
2998 a8083063 Iustin Pop

2999 a8083063 Iustin Pop
    """
3000 a8083063 Iustin Pop
    instance = self.instance
3001 9a4f63d1 Iustin Pop
    logging.info("Shutting down instance %s on node %s",
3002 9a4f63d1 Iustin Pop
                 instance.name, instance.primary_node)
3003 a8083063 Iustin Pop
3004 781de953 Iustin Pop
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
3005 781de953 Iustin Pop
    if result.failed or not result.data:
3006 1d67656e Iustin Pop
      if self.op.ignore_failures:
3007 1d67656e Iustin Pop
        feedback_fn("Warning: can't shutdown instance")
3008 1d67656e Iustin Pop
      else:
3009 1d67656e Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3010 1d67656e Iustin Pop
                                 (instance.name, instance.primary_node))
3011 a8083063 Iustin Pop
3012 9a4f63d1 Iustin Pop
    logging.info("Removing block devices for instance %s", instance.name)
3013 a8083063 Iustin Pop
3014 b9bddb6b Iustin Pop
    if not _RemoveDisks(self, instance):
3015 1d67656e Iustin Pop
      if self.op.ignore_failures:
3016 1d67656e Iustin Pop
        feedback_fn("Warning: can't remove instance's disks")
3017 1d67656e Iustin Pop
      else:
3018 1d67656e Iustin Pop
        raise errors.OpExecError("Can't remove instance's disks")
3019 a8083063 Iustin Pop
3020 9a4f63d1 Iustin Pop
    logging.info("Removing instance %s out of cluster config", instance.name)
3021 a8083063 Iustin Pop
3022 a8083063 Iustin Pop
    self.cfg.RemoveInstance(instance.name)
3023 cf472233 Guido Trotter
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
3024 a8083063 Iustin Pop
3025 a8083063 Iustin Pop
3026 a8083063 Iustin Pop
class LUQueryInstances(NoHooksLU):
3027 a8083063 Iustin Pop
  """Logical unit for querying instances.
3028 a8083063 Iustin Pop

3029 a8083063 Iustin Pop
  """
3030 069dcc86 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
3031 7eb9d8f7 Guido Trotter
  REQ_BGL = False
3032 a2d2e1a7 Iustin Pop
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
3033 a2d2e1a7 Iustin Pop
                                    "admin_state", "admin_ram",
3034 a2d2e1a7 Iustin Pop
                                    "disk_template", "ip", "mac", "bridge",
3035 a2d2e1a7 Iustin Pop
                                    "sda_size", "sdb_size", "vcpus", "tags",
3036 a2d2e1a7 Iustin Pop
                                    "network_port", "beparams",
3037 a2d2e1a7 Iustin Pop
                                    "(disk).(size)/([0-9]+)",
3038 a2d2e1a7 Iustin Pop
                                    "(disk).(sizes)",
3039 a2d2e1a7 Iustin Pop
                                    "(nic).(mac|ip|bridge)/([0-9]+)",
3040 a2d2e1a7 Iustin Pop
                                    "(nic).(macs|ips|bridges)",
3041 a2d2e1a7 Iustin Pop
                                    "(disk|nic).(count)",
3042 a2d2e1a7 Iustin Pop
                                    "serial_no", "hypervisor", "hvparams",] +
3043 a2d2e1a7 Iustin Pop
                                  ["hv/%s" % name
3044 a2d2e1a7 Iustin Pop
                                   for name in constants.HVS_PARAMETERS] +
3045 a2d2e1a7 Iustin Pop
                                  ["be/%s" % name
3046 a2d2e1a7 Iustin Pop
                                   for name in constants.BES_PARAMETERS])
3047 a2d2e1a7 Iustin Pop
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
3048 31bf511f Iustin Pop
3049 a8083063 Iustin Pop
3050 7eb9d8f7 Guido Trotter
  def ExpandNames(self):
3051 31bf511f Iustin Pop
    _CheckOutputFields(static=self._FIELDS_STATIC,
3052 31bf511f Iustin Pop
                       dynamic=self._FIELDS_DYNAMIC,
3053 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
3054 a8083063 Iustin Pop
3055 7eb9d8f7 Guido Trotter
    self.needed_locks = {}
3056 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_INSTANCE] = 1
3057 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
3058 7eb9d8f7 Guido Trotter
3059 57a2fb91 Iustin Pop
    if self.op.names:
3060 57a2fb91 Iustin Pop
      self.wanted = _GetWantedInstances(self, self.op.names)
3061 7eb9d8f7 Guido Trotter
    else:
3062 57a2fb91 Iustin Pop
      self.wanted = locking.ALL_SET
3063 7eb9d8f7 Guido Trotter
3064 31bf511f Iustin Pop
    self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3065 57a2fb91 Iustin Pop
    if self.do_locking:
3066 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3067 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = []
3068 57a2fb91 Iustin Pop
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3069 7eb9d8f7 Guido Trotter
3070 7eb9d8f7 Guido Trotter
  def DeclareLocks(self, level):
3071 57a2fb91 Iustin Pop
    if level == locking.LEVEL_NODE and self.do_locking:
3072 7eb9d8f7 Guido Trotter
      self._LockInstancesNodes()
3073 7eb9d8f7 Guido Trotter
3074 7eb9d8f7 Guido Trotter
  def CheckPrereq(self):
3075 7eb9d8f7 Guido Trotter
    """Check prerequisites.
3076 7eb9d8f7 Guido Trotter

3077 7eb9d8f7 Guido Trotter
    """
3078 57a2fb91 Iustin Pop
    pass
3079 069dcc86 Iustin Pop
3080 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3081 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
3082 a8083063 Iustin Pop

3083 a8083063 Iustin Pop
    """
3084 57a2fb91 Iustin Pop
    all_info = self.cfg.GetAllInstancesInfo()
3085 57a2fb91 Iustin Pop
    if self.do_locking:
3086 57a2fb91 Iustin Pop
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
3087 3fa93523 Guido Trotter
    elif self.wanted != locking.ALL_SET:
3088 3fa93523 Guido Trotter
      instance_names = self.wanted
3089 3fa93523 Guido Trotter
      missing = set(instance_names).difference(all_info.keys())
3090 3fa93523 Guido Trotter
      if missing:
3091 7b3a8fb5 Iustin Pop
        raise errors.OpExecError(
3092 3fa93523 Guido Trotter
          "Some instances were removed before retrieving their data: %s"
3093 3fa93523 Guido Trotter
          % missing)
3094 57a2fb91 Iustin Pop
    else:
3095 57a2fb91 Iustin Pop
      instance_names = all_info.keys()
3096 c1f1cbb2 Iustin Pop
3097 c1f1cbb2 Iustin Pop
    instance_names = utils.NiceSort(instance_names)
3098 57a2fb91 Iustin Pop
    instance_list = [all_info[iname] for iname in instance_names]
3099 a8083063 Iustin Pop
3100 a8083063 Iustin Pop
    # begin data gathering
3101 a8083063 Iustin Pop
3102 a8083063 Iustin Pop
    nodes = frozenset([inst.primary_node for inst in instance_list])
3103 e69d05fd Iustin Pop
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3104 a8083063 Iustin Pop
3105 a8083063 Iustin Pop
    bad_nodes = []
3106 cbfc4681 Iustin Pop
    off_nodes = []
3107 31bf511f Iustin Pop
    if self.do_locking:
3108 a8083063 Iustin Pop
      live_data = {}
3109 72737a7f Iustin Pop
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
3110 a8083063 Iustin Pop
      for name in nodes:
3111 a8083063 Iustin Pop
        result = node_data[name]
3112 cbfc4681 Iustin Pop
        if result.offline:
3113 cbfc4681 Iustin Pop
          # offline nodes will be in both lists
3114 cbfc4681 Iustin Pop
          off_nodes.append(name)
3115 781de953 Iustin Pop
        if result.failed:
3116 a8083063 Iustin Pop
          bad_nodes.append(name)
3117 781de953 Iustin Pop
        else:
3118 781de953 Iustin Pop
          if result.data:
3119 781de953 Iustin Pop
            live_data.update(result.data)
3120 781de953 Iustin Pop
            # else no instance is alive
3121 a8083063 Iustin Pop
    else:
3122 a8083063 Iustin Pop
      live_data = dict([(name, {}) for name in instance_names])
3123 a8083063 Iustin Pop
3124 a8083063 Iustin Pop
    # end data gathering
3125 a8083063 Iustin Pop
3126 5018a335 Iustin Pop
    HVPREFIX = "hv/"
3127 338e51e8 Iustin Pop
    BEPREFIX = "be/"
3128 a8083063 Iustin Pop
    output = []
3129 a8083063 Iustin Pop
    for instance in instance_list:
3130 a8083063 Iustin Pop
      iout = []
3131 5018a335 Iustin Pop
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
3132 338e51e8 Iustin Pop
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
3133 a8083063 Iustin Pop
      for field in self.op.output_fields:
3134 71c1af58 Iustin Pop
        st_match = self._FIELDS_STATIC.Matches(field)
3135 a8083063 Iustin Pop
        if field == "name":
3136 a8083063 Iustin Pop
          val = instance.name
3137 a8083063 Iustin Pop
        elif field == "os":
3138 a8083063 Iustin Pop
          val = instance.os
3139 a8083063 Iustin Pop
        elif field == "pnode":
3140 a8083063 Iustin Pop
          val = instance.primary_node
3141 a8083063 Iustin Pop
        elif field == "snodes":
3142 8a23d2d3 Iustin Pop
          val = list(instance.secondary_nodes)
3143 a8083063 Iustin Pop
        elif field == "admin_state":
3144 8a23d2d3 Iustin Pop
          val = (instance.status != "down")
3145 a8083063 Iustin Pop
        elif field == "oper_state":
3146 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
3147 8a23d2d3 Iustin Pop
            val = None
3148 a8083063 Iustin Pop
          else:
3149 8a23d2d3 Iustin Pop
            val = bool(live_data.get(instance.name))
3150 d8052456 Iustin Pop
        elif field == "status":
3151 cbfc4681 Iustin Pop
          if instance.primary_node in off_nodes:
3152 cbfc4681 Iustin Pop
            val = "ERROR_nodeoffline"
3153 cbfc4681 Iustin Pop
          elif instance.primary_node in bad_nodes:
3154 d8052456 Iustin Pop
            val = "ERROR_nodedown"
3155 d8052456 Iustin Pop
          else:
3156 d8052456 Iustin Pop
            running = bool(live_data.get(instance.name))
3157 d8052456 Iustin Pop
            if running:
3158 d8052456 Iustin Pop
              if instance.status != "down":
3159 d8052456 Iustin Pop
                val = "running"
3160 d8052456 Iustin Pop
              else:
3161 d8052456 Iustin Pop
                val = "ERROR_up"
3162 d8052456 Iustin Pop
            else:
3163 d8052456 Iustin Pop
              if instance.status != "down":
3164 d8052456 Iustin Pop
                val = "ERROR_down"
3165 d8052456 Iustin Pop
              else:
3166 d8052456 Iustin Pop
                val = "ADMIN_down"
3167 a8083063 Iustin Pop
        elif field == "oper_ram":
3168 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
3169 8a23d2d3 Iustin Pop
            val = None
3170 a8083063 Iustin Pop
          elif instance.name in live_data:
3171 a8083063 Iustin Pop
            val = live_data[instance.name].get("memory", "?")
3172 a8083063 Iustin Pop
          else:
3173 a8083063 Iustin Pop
            val = "-"
3174 a8083063 Iustin Pop
        elif field == "disk_template":
3175 a8083063 Iustin Pop
          val = instance.disk_template
3176 a8083063 Iustin Pop
        elif field == "ip":
3177 a8083063 Iustin Pop
          val = instance.nics[0].ip
3178 a8083063 Iustin Pop
        elif field == "bridge":
3179 a8083063 Iustin Pop
          val = instance.nics[0].bridge
3180 a8083063 Iustin Pop
        elif field == "mac":
3181 a8083063 Iustin Pop
          val = instance.nics[0].mac
3182 644eeef9 Iustin Pop
        elif field == "sda_size" or field == "sdb_size":
3183 ad24e046 Iustin Pop
          idx = ord(field[2]) - ord('a')
3184 ad24e046 Iustin Pop
          try:
3185 ad24e046 Iustin Pop
            val = instance.FindDisk(idx).size
3186 ad24e046 Iustin Pop
          except errors.OpPrereqError:
3187 8a23d2d3 Iustin Pop
            val = None
3188 130a6a6f Iustin Pop
        elif field == "tags":
3189 130a6a6f Iustin Pop
          val = list(instance.GetTags())
3190 38d7239a Iustin Pop
        elif field == "serial_no":
3191 38d7239a Iustin Pop
          val = instance.serial_no
3192 5018a335 Iustin Pop
        elif field == "network_port":
3193 5018a335 Iustin Pop
          val = instance.network_port
3194 338e51e8 Iustin Pop
        elif field == "hypervisor":
3195 338e51e8 Iustin Pop
          val = instance.hypervisor
3196 338e51e8 Iustin Pop
        elif field == "hvparams":
3197 338e51e8 Iustin Pop
          val = i_hv
3198 5018a335 Iustin Pop
        elif (field.startswith(HVPREFIX) and
3199 5018a335 Iustin Pop
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
3200 5018a335 Iustin Pop
          val = i_hv.get(field[len(HVPREFIX):], None)
3201 338e51e8 Iustin Pop
        elif field == "beparams":
3202 338e51e8 Iustin Pop
          val = i_be
3203 338e51e8 Iustin Pop
        elif (field.startswith(BEPREFIX) and
3204 338e51e8 Iustin Pop
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
3205 338e51e8 Iustin Pop
          val = i_be.get(field[len(BEPREFIX):], None)
3206 71c1af58 Iustin Pop
        elif st_match and st_match.groups():
3207 71c1af58 Iustin Pop
          # matches a variable list
3208 71c1af58 Iustin Pop
          st_groups = st_match.groups()
3209 71c1af58 Iustin Pop
          if st_groups and st_groups[0] == "disk":
3210 71c1af58 Iustin Pop
            if st_groups[1] == "count":
3211 71c1af58 Iustin Pop
              val = len(instance.disks)
3212 41a776da Iustin Pop
            elif st_groups[1] == "sizes":
3213 41a776da Iustin Pop
              val = [disk.size for disk in instance.disks]
3214 71c1af58 Iustin Pop
            elif st_groups[1] == "size":
3215 3e0cea06 Iustin Pop
              try:
3216 3e0cea06 Iustin Pop
                val = instance.FindDisk(st_groups[2]).size
3217 3e0cea06 Iustin Pop
              except errors.OpPrereqError:
3218 71c1af58 Iustin Pop
                val = None
3219 71c1af58 Iustin Pop
            else:
3220 71c1af58 Iustin Pop
              assert False, "Unhandled disk parameter"
3221 71c1af58 Iustin Pop
          elif st_groups[0] == "nic":
3222 71c1af58 Iustin Pop
            if st_groups[1] == "count":
3223 71c1af58 Iustin Pop
              val = len(instance.nics)
3224 41a776da Iustin Pop
            elif st_groups[1] == "macs":
3225 41a776da Iustin Pop
              val = [nic.mac for nic in instance.nics]
3226 41a776da Iustin Pop
            elif st_groups[1] == "ips":
3227 41a776da Iustin Pop
              val = [nic.ip for nic in instance.nics]
3228 41a776da Iustin Pop
            elif st_groups[1] == "bridges":
3229 41a776da Iustin Pop
              val = [nic.bridge for nic in instance.nics]
3230 71c1af58 Iustin Pop
            else:
3231 71c1af58 Iustin Pop
              # index-based item
3232 71c1af58 Iustin Pop
              nic_idx = int(st_groups[2])
3233 71c1af58 Iustin Pop
              if nic_idx >= len(instance.nics):
3234 71c1af58 Iustin Pop
                val = None
3235 71c1af58 Iustin Pop
              else:
3236 71c1af58 Iustin Pop
                if st_groups[1] == "mac":
3237 71c1af58 Iustin Pop
                  val = instance.nics[nic_idx].mac
3238 71c1af58 Iustin Pop
                elif st_groups[1] == "ip":
3239 71c1af58 Iustin Pop
                  val = instance.nics[nic_idx].ip
3240 71c1af58 Iustin Pop
                elif st_groups[1] == "bridge":
3241 71c1af58 Iustin Pop
                  val = instance.nics[nic_idx].bridge
3242 71c1af58 Iustin Pop
                else:
3243 71c1af58 Iustin Pop
                  assert False, "Unhandled NIC parameter"
3244 71c1af58 Iustin Pop
          else:
3245 71c1af58 Iustin Pop
            assert False, "Unhandled variable parameter"
3246 a8083063 Iustin Pop
        else:
3247 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
3248 a8083063 Iustin Pop
        iout.append(val)
3249 a8083063 Iustin Pop
      output.append(iout)
3250 a8083063 Iustin Pop
3251 a8083063 Iustin Pop
    return output
3252 a8083063 Iustin Pop
3253 a8083063 Iustin Pop
3254 a8083063 Iustin Pop
class LUFailoverInstance(LogicalUnit):
3255 a8083063 Iustin Pop
  """Failover an instance.
3256 a8083063 Iustin Pop

3257 a8083063 Iustin Pop
  """
3258 a8083063 Iustin Pop
  HPATH = "instance-failover"
3259 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3260 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_consistency"]
3261 c9e5c064 Guido Trotter
  REQ_BGL = False
3262 c9e5c064 Guido Trotter
3263 c9e5c064 Guido Trotter
  def ExpandNames(self):
3264 c9e5c064 Guido Trotter
    self._ExpandAndLockInstance()
3265 c9e5c064 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
3266 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3267 c9e5c064 Guido Trotter
3268 c9e5c064 Guido Trotter
  def DeclareLocks(self, level):
3269 c9e5c064 Guido Trotter
    if level == locking.LEVEL_NODE:
3270 c9e5c064 Guido Trotter
      self._LockInstancesNodes()
3271 a8083063 Iustin Pop
3272 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3273 a8083063 Iustin Pop
    """Build hooks env.
3274 a8083063 Iustin Pop

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

3277 a8083063 Iustin Pop
    """
3278 a8083063 Iustin Pop
    env = {
3279 a8083063 Iustin Pop
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
3280 a8083063 Iustin Pop
      }
3281 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3282 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3283 a8083063 Iustin Pop
    return env, nl, nl
3284 a8083063 Iustin Pop
3285 a8083063 Iustin Pop
  def CheckPrereq(self):
3286 a8083063 Iustin Pop
    """Check prerequisites.
3287 a8083063 Iustin Pop

3288 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3289 a8083063 Iustin Pop

3290 a8083063 Iustin Pop
    """
3291 c9e5c064 Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3292 c9e5c064 Guido Trotter
    assert self.instance is not None, \
3293 c9e5c064 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3294 a8083063 Iustin Pop
3295 338e51e8 Iustin Pop
    bep = self.cfg.GetClusterInfo().FillBE(instance)
3296 a1f445d3 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3297 2a710df1 Michael Hanselmann
      raise errors.OpPrereqError("Instance's disk layout is not"
3298 a1f445d3 Iustin Pop
                                 " network mirrored, cannot failover.")
3299 2a710df1 Michael Hanselmann
3300 2a710df1 Michael Hanselmann
    secondary_nodes = instance.secondary_nodes
3301 2a710df1 Michael Hanselmann
    if not secondary_nodes:
3302 2a710df1 Michael Hanselmann
      raise errors.ProgrammerError("no secondary node but using "
3303 abdf0113 Iustin Pop
                                   "a mirrored disk template")
3304 2a710df1 Michael Hanselmann
3305 2a710df1 Michael Hanselmann
    target_node = secondary_nodes[0]
3306 7527a8a4 Iustin Pop
    _CheckNodeOnline(self, target_node)
3307 d4f16fd9 Iustin Pop
    # check memory requirements on the secondary node
3308 b9bddb6b Iustin Pop
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
3309 338e51e8 Iustin Pop
                         instance.name, bep[constants.BE_MEMORY],
3310 e69d05fd Iustin Pop
                         instance.hypervisor)
3311 3a7c308e Guido Trotter
3312 a8083063 Iustin Pop
    # check bridge existance
3313 a8083063 Iustin Pop
    brlist = [nic.bridge for nic in instance.nics]
3314 781de953 Iustin Pop
    result = self.rpc.call_bridges_exist(target_node, brlist)
3315 781de953 Iustin Pop
    result.Raise()
3316 781de953 Iustin Pop
    if not result.data:
3317 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("One or more target bridges %s does not"
3318 3ecf6786 Iustin Pop
                                 " exist on destination node '%s'" %
3319 50ff9a7a Iustin Pop
                                 (brlist, target_node))
3320 a8083063 Iustin Pop
3321 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3322 a8083063 Iustin Pop
    """Failover an instance.
3323 a8083063 Iustin Pop

3324 a8083063 Iustin Pop
    The failover is done by shutting it down on its present node and
3325 a8083063 Iustin Pop
    starting it on the secondary.
3326 a8083063 Iustin Pop

3327 a8083063 Iustin Pop
    """
3328 a8083063 Iustin Pop
    instance = self.instance
3329 a8083063 Iustin Pop
3330 a8083063 Iustin Pop
    source_node = instance.primary_node
3331 a8083063 Iustin Pop
    target_node = instance.secondary_nodes[0]
3332 a8083063 Iustin Pop
3333 a8083063 Iustin Pop
    feedback_fn("* checking disk consistency between source and target")
3334 a8083063 Iustin Pop
    for dev in instance.disks:
3335 abdf0113 Iustin Pop
      # for drbd, these are drbd over lvm
3336 b9bddb6b Iustin Pop
      if not _CheckDiskConsistency(self, dev, target_node, False):
3337 a0aaa0d0 Guido Trotter
        if instance.status == "up" and not self.op.ignore_consistency:
3338 3ecf6786 Iustin Pop
          raise errors.OpExecError("Disk %s is degraded on target node,"
3339 3ecf6786 Iustin Pop
                                   " aborting failover." % dev.iv_name)
3340 a8083063 Iustin Pop
3341 a8083063 Iustin Pop
    feedback_fn("* shutting down instance on source node")
3342 9a4f63d1 Iustin Pop
    logging.info("Shutting down instance %s on node %s",
3343 9a4f63d1 Iustin Pop
                 instance.name, source_node)
3344 a8083063 Iustin Pop
3345 781de953 Iustin Pop
    result = self.rpc.call_instance_shutdown(source_node, instance)
3346 781de953 Iustin Pop
    if result.failed or not result.data:
3347 24a40d57 Iustin Pop
      if self.op.ignore_consistency:
3348 86d9d3bb Iustin Pop
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
3349 86d9d3bb Iustin Pop
                             " Proceeding"
3350 86d9d3bb Iustin Pop
                             " anyway. Please make sure node %s is down",
3351 86d9d3bb Iustin Pop
                             instance.name, source_node, source_node)
3352 24a40d57 Iustin Pop
      else:
3353 24a40d57 Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
3354 24a40d57 Iustin Pop
                                 (instance.name, source_node))
3355 a8083063 Iustin Pop
3356 a8083063 Iustin Pop
    feedback_fn("* deactivating the instance's disks on source node")
3357 b9bddb6b Iustin Pop
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
3358 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't shut down the instance's disks.")
3359 a8083063 Iustin Pop
3360 a8083063 Iustin Pop
    instance.primary_node = target_node
3361 a8083063 Iustin Pop
    # distribute new instance config to the other nodes
3362 b6102dab Guido Trotter
    self.cfg.Update(instance)
3363 a8083063 Iustin Pop
3364 12a0cfbe Guido Trotter
    # Only start the instance if it's marked as up
3365 12a0cfbe Guido Trotter
    if instance.status == "up":
3366 12a0cfbe Guido Trotter
      feedback_fn("* activating the instance's disks on target node")
3367 9a4f63d1 Iustin Pop
      logging.info("Starting instance %s on node %s",
3368 9a4f63d1 Iustin Pop
                   instance.name, target_node)
3369 12a0cfbe Guido Trotter
3370 b9bddb6b Iustin Pop
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
3371 12a0cfbe Guido Trotter
                                               ignore_secondaries=True)
3372 12a0cfbe Guido Trotter
      if not disks_ok:
3373 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
3374 12a0cfbe Guido Trotter
        raise errors.OpExecError("Can't activate the instance's disks")
3375 a8083063 Iustin Pop
3376 12a0cfbe Guido Trotter
      feedback_fn("* starting the instance on the target node")
3377 781de953 Iustin Pop
      result = self.rpc.call_instance_start(target_node, instance, None)
3378 dd279568 Iustin Pop
      msg = result.RemoteFailMsg()
3379 dd279568 Iustin Pop
      if msg:
3380 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
3381 dd279568 Iustin Pop
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
3382 dd279568 Iustin Pop
                                 (instance.name, target_node, msg))
3383 a8083063 Iustin Pop
3384 a8083063 Iustin Pop
3385 53c776b5 Iustin Pop
class LUMigrateInstance(LogicalUnit):
3386 53c776b5 Iustin Pop
  """Migrate an instance.
3387 53c776b5 Iustin Pop

3388 53c776b5 Iustin Pop
  This is migration without shutting down, compared to the failover,
3389 53c776b5 Iustin Pop
  which is done with shutdown.
3390 53c776b5 Iustin Pop

3391 53c776b5 Iustin Pop
  """
3392 53c776b5 Iustin Pop
  HPATH = "instance-migrate"
3393 53c776b5 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3394 53c776b5 Iustin Pop
  _OP_REQP = ["instance_name", "live", "cleanup"]
3395 53c776b5 Iustin Pop
3396 53c776b5 Iustin Pop
  REQ_BGL = False
3397 53c776b5 Iustin Pop
3398 53c776b5 Iustin Pop
  def ExpandNames(self):
3399 53c776b5 Iustin Pop
    self._ExpandAndLockInstance()
3400 53c776b5 Iustin Pop
    self.needed_locks[locking.LEVEL_NODE] = []
3401 53c776b5 Iustin Pop
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3402 53c776b5 Iustin Pop
3403 53c776b5 Iustin Pop
  def DeclareLocks(self, level):
3404 53c776b5 Iustin Pop
    if level == locking.LEVEL_NODE:
3405 53c776b5 Iustin Pop
      self._LockInstancesNodes()
3406 53c776b5 Iustin Pop
3407 53c776b5 Iustin Pop
  def BuildHooksEnv(self):
3408 53c776b5 Iustin Pop
    """Build hooks env.
3409 53c776b5 Iustin Pop

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

3412 53c776b5 Iustin Pop
    """
3413 53c776b5 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
3414 53c776b5 Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
3415 53c776b5 Iustin Pop
    return env, nl, nl
3416 53c776b5 Iustin Pop
3417 53c776b5 Iustin Pop
  def CheckPrereq(self):
3418 53c776b5 Iustin Pop
    """Check prerequisites.
3419 53c776b5 Iustin Pop

3420 53c776b5 Iustin Pop
    This checks that the instance is in the cluster.
3421 53c776b5 Iustin Pop

3422 53c776b5 Iustin Pop
    """
3423 53c776b5 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
3424 53c776b5 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
3425 53c776b5 Iustin Pop
    if instance is None:
3426 53c776b5 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
3427 53c776b5 Iustin Pop
                                 self.op.instance_name)
3428 53c776b5 Iustin Pop
3429 53c776b5 Iustin Pop
    if instance.disk_template != constants.DT_DRBD8:
3430 53c776b5 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout is not"
3431 53c776b5 Iustin Pop
                                 " drbd8, cannot migrate.")
3432 53c776b5 Iustin Pop
3433 53c776b5 Iustin Pop
    secondary_nodes = instance.secondary_nodes
3434 53c776b5 Iustin Pop
    if not secondary_nodes:
3435 53c776b5 Iustin Pop
      raise errors.ProgrammerError("no secondary node but using "
3436 53c776b5 Iustin Pop
                                   "drbd8 disk template")
3437 53c776b5 Iustin Pop
3438 53c776b5 Iustin Pop
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
3439 53c776b5 Iustin Pop
3440 53c776b5 Iustin Pop
    target_node = secondary_nodes[0]
3441 53c776b5 Iustin Pop
    # check memory requirements on the secondary node
3442 53c776b5 Iustin Pop
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
3443 53c776b5 Iustin Pop
                         instance.name, i_be[constants.BE_MEMORY],
3444 53c776b5 Iustin Pop
                         instance.hypervisor)
3445 53c776b5 Iustin Pop
3446 53c776b5 Iustin Pop
    # check bridge existance
3447 53c776b5 Iustin Pop
    brlist = [nic.bridge for nic in instance.nics]
3448 53c776b5 Iustin Pop
    result = self.rpc.call_bridges_exist(target_node, brlist)
3449 53c776b5 Iustin Pop
    if result.failed or not result.data:
3450 53c776b5 Iustin Pop
      raise errors.OpPrereqError("One or more target bridges %s does not"
3451 53c776b5 Iustin Pop
                                 " exist on destination node '%s'" %
3452 53c776b5 Iustin Pop
                                 (brlist, target_node))
3453 53c776b5 Iustin Pop
3454 53c776b5 Iustin Pop
    if not self.op.cleanup:
3455 53c776b5 Iustin Pop
      result = self.rpc.call_instance_migratable(instance.primary_node,
3456 53c776b5 Iustin Pop
                                                 instance)
3457 53c776b5 Iustin Pop
      msg = result.RemoteFailMsg()
3458 53c776b5 Iustin Pop
      if msg:
3459 53c776b5 Iustin Pop
        raise errors.OpPrereqError("Can't migrate: %s - please use failover" %
3460 53c776b5 Iustin Pop
                                   msg)
3461 53c776b5 Iustin Pop
3462 53c776b5 Iustin Pop
    self.instance = instance
3463 53c776b5 Iustin Pop
3464 53c776b5 Iustin Pop
  def _WaitUntilSync(self):
3465 53c776b5 Iustin Pop
    """Poll with custom rpc for disk sync.
3466 53c776b5 Iustin Pop

3467 53c776b5 Iustin Pop
    This uses our own step-based rpc call.
3468 53c776b5 Iustin Pop

3469 53c776b5 Iustin Pop
    """
3470 53c776b5 Iustin Pop
    self.feedback_fn("* wait until resync is done")
3471 53c776b5 Iustin Pop
    all_done = False
3472 53c776b5 Iustin Pop
    while not all_done:
3473 53c776b5 Iustin Pop
      all_done = True
3474 53c776b5 Iustin Pop
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
3475 53c776b5 Iustin Pop
                                            self.nodes_ip,
3476 53c776b5 Iustin Pop
                                            self.instance.disks)
3477 53c776b5 Iustin Pop
      min_percent = 100
3478 53c776b5 Iustin Pop
      for node, nres in result.items():
3479 53c776b5 Iustin Pop
        msg = nres.RemoteFailMsg()
3480 53c776b5 Iustin Pop
        if msg:
3481 53c776b5 Iustin Pop
          raise errors.OpExecError("Cannot resync disks on node %s: %s" %
3482 53c776b5 Iustin Pop
                                   (node, msg))
3483 53c776b5 Iustin Pop
        node_done, node_percent = nres.data[1]
3484 53c776b5 Iustin Pop
        all_done = all_done and node_done
3485 53c776b5 Iustin Pop
        if node_percent is not None:
3486 53c776b5 Iustin Pop
          min_percent = min(min_percent, node_percent)
3487 53c776b5 Iustin Pop
      if not all_done:
3488 53c776b5 Iustin Pop
        if min_percent < 100:
3489 53c776b5 Iustin Pop
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
3490 53c776b5 Iustin Pop
        time.sleep(2)
3491 53c776b5 Iustin Pop
3492 53c776b5 Iustin Pop
  def _EnsureSecondary(self, node):
3493 53c776b5 Iustin Pop
    """Demote a node to secondary.
3494 53c776b5 Iustin Pop

3495 53c776b5 Iustin Pop
    """
3496 53c776b5 Iustin Pop
    self.feedback_fn("* switching node %s to secondary mode" % node)
3497 53c776b5 Iustin Pop
3498 53c776b5 Iustin Pop
    for dev in self.instance.disks:
3499 53c776b5 Iustin Pop
      self.cfg.SetDiskID(dev, node)
3500 53c776b5 Iustin Pop
3501 53c776b5 Iustin Pop
    result = self.rpc.call_blockdev_close(node, self.instance.name,
3502 53c776b5 Iustin Pop
                                          self.instance.disks)
3503 53c776b5 Iustin Pop
    msg = result.RemoteFailMsg()
3504 53c776b5 Iustin Pop
    if msg:
3505 53c776b5 Iustin Pop
      raise errors.OpExecError("Cannot change disk to secondary on node %s,"
3506 53c776b5 Iustin Pop
                               " error %s" % (node, msg))
3507 53c776b5 Iustin Pop
3508 53c776b5 Iustin Pop
  def _GoStandalone(self):
3509 53c776b5 Iustin Pop
    """Disconnect from the network.
3510 53c776b5 Iustin Pop

3511 53c776b5 Iustin Pop
    """
3512 53c776b5 Iustin Pop
    self.feedback_fn("* changing into standalone mode")
3513 53c776b5 Iustin Pop
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
3514 53c776b5 Iustin Pop
                                               self.instance.disks)
3515 53c776b5 Iustin Pop
    for node, nres in result.items():
3516 53c776b5 Iustin Pop
      msg = nres.RemoteFailMsg()
3517 53c776b5 Iustin Pop
      if msg:
3518 53c776b5 Iustin Pop
        raise errors.OpExecError("Cannot disconnect disks node %s,"
3519 53c776b5 Iustin Pop
                                 " error %s" % (node, msg))
3520 53c776b5 Iustin Pop
3521 53c776b5 Iustin Pop
  def _GoReconnect(self, multimaster):
3522 53c776b5 Iustin Pop
    """Reconnect to the network.
3523 53c776b5 Iustin Pop

3524 53c776b5 Iustin Pop
    """
3525 53c776b5 Iustin Pop
    if multimaster:
3526 53c776b5 Iustin Pop
      msg = "dual-master"
3527 53c776b5 Iustin Pop
    else:
3528 53c776b5 Iustin Pop
      msg = "single-master"
3529 53c776b5 Iustin Pop
    self.feedback_fn("* changing disks into %s mode" % msg)
3530 53c776b5 Iustin Pop
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
3531 53c776b5 Iustin Pop
                                           self.instance.disks,
3532 53c776b5 Iustin Pop
                                           self.instance.name, multimaster)
3533 53c776b5 Iustin Pop
    for node, nres in result.items():
3534 53c776b5 Iustin Pop
      msg = nres.RemoteFailMsg()
3535 53c776b5 Iustin Pop
      if msg:
3536 53c776b5 Iustin Pop
        raise errors.OpExecError("Cannot change disks config on node %s,"
3537 53c776b5 Iustin Pop
                                 " error: %s" % (node, msg))
3538 53c776b5 Iustin Pop
3539 53c776b5 Iustin Pop
  def _ExecCleanup(self):
3540 53c776b5 Iustin Pop
    """Try to cleanup after a failed migration.
3541 53c776b5 Iustin Pop

3542 53c776b5 Iustin Pop
    The cleanup is done by:
3543 53c776b5 Iustin Pop
      - check that the instance is running only on one node
3544 53c776b5 Iustin Pop
        (and update the config if needed)
3545 53c776b5 Iustin Pop
      - change disks on its secondary node to secondary
3546 53c776b5 Iustin Pop
      - wait until disks are fully synchronized
3547 53c776b5 Iustin Pop
      - disconnect from the network
3548 53c776b5 Iustin Pop
      - change disks into single-master mode
3549 53c776b5 Iustin Pop
      - wait again until disks are fully synchronized
3550 53c776b5 Iustin Pop

3551 53c776b5 Iustin Pop
    """
3552 53c776b5 Iustin Pop
    instance = self.instance
3553 53c776b5 Iustin Pop
    target_node = self.target_node
3554 53c776b5 Iustin Pop
    source_node = self.source_node
3555 53c776b5 Iustin Pop
3556 53c776b5 Iustin Pop
    # check running on only one node
3557 53c776b5 Iustin Pop
    self.feedback_fn("* checking where the instance actually runs"
3558 53c776b5 Iustin Pop
                     " (if this hangs, the hypervisor might be in"
3559 53c776b5 Iustin Pop
                     " a bad state)")
3560 53c776b5 Iustin Pop
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
3561 53c776b5 Iustin Pop
    for node, result in ins_l.items():
3562 53c776b5 Iustin Pop
      result.Raise()
3563 53c776b5 Iustin Pop
      if not isinstance(result.data, list):
3564 53c776b5 Iustin Pop
        raise errors.OpExecError("Can't contact node '%s'" % node)
3565 53c776b5 Iustin Pop
3566 53c776b5 Iustin Pop
    runningon_source = instance.name in ins_l[source_node].data
3567 53c776b5 Iustin Pop
    runningon_target = instance.name in ins_l[target_node].data
3568 53c776b5 Iustin Pop
3569 53c776b5 Iustin Pop
    if runningon_source and runningon_target:
3570 53c776b5 Iustin Pop
      raise errors.OpExecError("Instance seems to be running on two nodes,"
3571 53c776b5 Iustin Pop
                               " or the hypervisor is confused. You will have"
3572 53c776b5 Iustin Pop
                               " to ensure manually that it runs only on one"
3573 53c776b5 Iustin Pop
                               " and restart this operation.")
3574 53c776b5 Iustin Pop
3575 53c776b5 Iustin Pop
    if not (runningon_source or runningon_target):
3576 53c776b5 Iustin Pop
      raise errors.OpExecError("Instance does not seem to be running at all."
3577 53c776b5 Iustin Pop
                               " In this case, it's safer to repair by"
3578 53c776b5 Iustin Pop
                               " running 'gnt-instance stop' to ensure disk"
3579 53c776b5 Iustin Pop
                               " shutdown, and then restarting it.")
3580 53c776b5 Iustin Pop
3581 53c776b5 Iustin Pop
    if runningon_target:
3582 53c776b5 Iustin Pop
      # the migration has actually succeeded, we need to update the config
3583 53c776b5 Iustin Pop
      self.feedback_fn("* instance running on secondary node (%s),"
3584 53c776b5 Iustin Pop
                       " updating config" % target_node)
3585 53c776b5 Iustin Pop
      instance.primary_node = target_node
3586 53c776b5 Iustin Pop
      self.cfg.Update(instance)
3587 53c776b5 Iustin Pop
      demoted_node = source_node
3588 53c776b5 Iustin Pop
    else:
3589 53c776b5 Iustin Pop
      self.feedback_fn("* instance confirmed to be running on its"
3590 53c776b5 Iustin Pop
                       " primary node (%s)" % source_node)
3591 53c776b5 Iustin Pop
      demoted_node = target_node
3592 53c776b5 Iustin Pop
3593 53c776b5 Iustin Pop
    self._EnsureSecondary(demoted_node)
3594 53c776b5 Iustin Pop
    try:
3595 53c776b5 Iustin Pop
      self._WaitUntilSync()
3596 53c776b5 Iustin Pop
    except errors.OpExecError:
3597 53c776b5 Iustin Pop
      # we ignore here errors, since if the device is standalone, it
3598 53c776b5 Iustin Pop
      # won't be able to sync
3599 53c776b5 Iustin Pop
      pass
3600 53c776b5 Iustin Pop
    self._GoStandalone()
3601 53c776b5 Iustin Pop
    self._GoReconnect(False)
3602 53c776b5 Iustin Pop
    self._WaitUntilSync()
3603 53c776b5 Iustin Pop
3604 53c776b5 Iustin Pop
    self.feedback_fn("* done")
3605 53c776b5 Iustin Pop
3606 53c776b5 Iustin Pop
  def _ExecMigration(self):
3607 53c776b5 Iustin Pop
    """Migrate an instance.
3608 53c776b5 Iustin Pop

3609 53c776b5 Iustin Pop
    The migrate is done by:
3610 53c776b5 Iustin Pop
      - change the disks into dual-master mode
3611 53c776b5 Iustin Pop
      - wait until disks are fully synchronized again
3612 53c776b5 Iustin Pop
      - migrate the instance
3613 53c776b5 Iustin Pop
      - change disks on the new secondary node (the old primary) to secondary
3614 53c776b5 Iustin Pop
      - wait until disks are fully synchronized
3615 53c776b5 Iustin Pop
      - change disks into single-master mode
3616 53c776b5 Iustin Pop

3617 53c776b5 Iustin Pop
    """
3618 53c776b5 Iustin Pop
    instance = self.instance
3619 53c776b5 Iustin Pop
    target_node = self.target_node
3620 53c776b5 Iustin Pop
    source_node = self.source_node
3621 53c776b5 Iustin Pop
3622 53c776b5 Iustin Pop
    self.feedback_fn("* checking disk consistency between source and target")
3623 53c776b5 Iustin Pop
    for dev in instance.disks:
3624 53c776b5 Iustin Pop
      if not _CheckDiskConsistency(self, dev, target_node, False):
3625 53c776b5 Iustin Pop
        raise errors.OpExecError("Disk %s is degraded or not fully"
3626 53c776b5 Iustin Pop
                                 " synchronized on target node,"
3627 53c776b5 Iustin Pop
                                 " aborting migrate." % dev.iv_name)
3628 53c776b5 Iustin Pop
3629 53c776b5 Iustin Pop
    self._EnsureSecondary(target_node)
3630 53c776b5 Iustin Pop
    self._GoStandalone()
3631 53c776b5 Iustin Pop
    self._GoReconnect(True)
3632 53c776b5 Iustin Pop
    self._WaitUntilSync()
3633 53c776b5 Iustin Pop
3634 53c776b5 Iustin Pop
    self.feedback_fn("* migrating instance to %s" % target_node)
3635 53c776b5 Iustin Pop
    time.sleep(10)
3636 53c776b5 Iustin Pop
    result = self.rpc.call_instance_migrate(source_node, instance,
3637 53c776b5 Iustin Pop
                                            self.nodes_ip[target_node],
3638 53c776b5 Iustin Pop
                                            self.op.live)
3639 53c776b5 Iustin Pop
    msg = result.RemoteFailMsg()
3640 53c776b5 Iustin Pop
    if msg:
3641 53c776b5 Iustin Pop
      logging.error("Instance migration failed, trying to revert"
3642 53c776b5 Iustin Pop
                    " disk status: %s", msg)
3643 53c776b5 Iustin Pop
      try:
3644 53c776b5 Iustin Pop
        self._EnsureSecondary(target_node)
3645 53c776b5 Iustin Pop
        self._GoStandalone()
3646 53c776b5 Iustin Pop
        self._GoReconnect(False)
3647 53c776b5 Iustin Pop
        self._WaitUntilSync()
3648 53c776b5 Iustin Pop
      except errors.OpExecError, err:
3649 53c776b5 Iustin Pop
        self.LogWarning("Migration failed and I can't reconnect the"
3650 53c776b5 Iustin Pop
                        " drives: error '%s'\n"
3651 53c776b5 Iustin Pop
                        "Please look and recover the instance status" %
3652 53c776b5 Iustin Pop
                        str(err))
3653 53c776b5 Iustin Pop
3654 53c776b5 Iustin Pop
      raise errors.OpExecError("Could not migrate instance %s: %s" %
3655 53c776b5 Iustin Pop
                               (instance.name, msg))
3656 53c776b5 Iustin Pop
    time.sleep(10)
3657 53c776b5 Iustin Pop
3658 53c776b5 Iustin Pop
    instance.primary_node = target_node
3659 53c776b5 Iustin Pop
    # distribute new instance config to the other nodes
3660 53c776b5 Iustin Pop
    self.cfg.Update(instance)
3661 53c776b5 Iustin Pop
3662 53c776b5 Iustin Pop
    self._EnsureSecondary(source_node)
3663 53c776b5 Iustin Pop
    self._WaitUntilSync()
3664 53c776b5 Iustin Pop
    self._GoStandalone()
3665 53c776b5 Iustin Pop
    self._GoReconnect(False)
3666 53c776b5 Iustin Pop
    self._WaitUntilSync()
3667 53c776b5 Iustin Pop
3668 53c776b5 Iustin Pop
    self.feedback_fn("* done")
3669 53c776b5 Iustin Pop
3670 53c776b5 Iustin Pop
  def Exec(self, feedback_fn):
3671 53c776b5 Iustin Pop
    """Perform the migration.
3672 53c776b5 Iustin Pop

3673 53c776b5 Iustin Pop
    """
3674 53c776b5 Iustin Pop
    self.feedback_fn = feedback_fn
3675 53c776b5 Iustin Pop
3676 53c776b5 Iustin Pop
    self.source_node = self.instance.primary_node
3677 53c776b5 Iustin Pop
    self.target_node = self.instance.secondary_nodes[0]
3678 53c776b5 Iustin Pop
    self.all_nodes = [self.source_node, self.target_node]
3679 53c776b5 Iustin Pop
    self.nodes_ip = {
3680 53c776b5 Iustin Pop
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
3681 53c776b5 Iustin Pop
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
3682 53c776b5 Iustin Pop
      }
3683 53c776b5 Iustin Pop
    if self.op.cleanup:
3684 53c776b5 Iustin Pop
      return self._ExecCleanup()
3685 53c776b5 Iustin Pop
    else:
3686 53c776b5 Iustin Pop
      return self._ExecMigration()
3687 53c776b5 Iustin Pop
3688 53c776b5 Iustin Pop
3689 428958aa Iustin Pop
def _CreateBlockDev(lu, node, instance, device, force_create,
3690 428958aa Iustin Pop
                    info, force_open):
3691 428958aa Iustin Pop
  """Create a tree of block devices on a given node.
3692 a8083063 Iustin Pop

3693 a8083063 Iustin Pop
  If this device type has to be created on secondaries, create it and
3694 a8083063 Iustin Pop
  all its children.
3695 a8083063 Iustin Pop

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

3698 428958aa Iustin Pop
  @param lu: the lu on whose behalf we execute
3699 428958aa Iustin Pop
  @param node: the node on which to create the device
3700 428958aa Iustin Pop
  @type instance: L{objects.Instance}
3701 428958aa Iustin Pop
  @param instance: the instance which owns the device
3702 428958aa Iustin Pop
  @type device: L{objects.Disk}
3703 428958aa Iustin Pop
  @param device: the device to create
3704 428958aa Iustin Pop
  @type force_create: boolean
3705 428958aa Iustin Pop
  @param force_create: whether to force creation of this device; this
3706 428958aa Iustin Pop
      will be change to True whenever we find a device which has
3707 428958aa Iustin Pop
      CreateOnSecondary() attribute
3708 428958aa Iustin Pop
  @param info: the extra 'metadata' we should attach to the device
3709 428958aa Iustin Pop
      (this will be represented as a LVM tag)
3710 428958aa Iustin Pop
  @type force_open: boolean
3711 428958aa Iustin Pop
  @param force_open: this parameter will be passes to the
3712 428958aa Iustin Pop
      L{backend.CreateBlockDevice} function where it specifies
3713 428958aa Iustin Pop
      whether we run on primary or not, and it affects both
3714 428958aa Iustin Pop
      the child assembly and the device own Open() execution
3715 428958aa Iustin Pop

3716 a8083063 Iustin Pop
  """
3717 a8083063 Iustin Pop
  if device.CreateOnSecondary():
3718 428958aa Iustin Pop
    force_create = True
3719 796cab27 Iustin Pop
3720 a8083063 Iustin Pop
  if device.children:
3721 a8083063 Iustin Pop
    for child in device.children:
3722 428958aa Iustin Pop
      _CreateBlockDev(lu, node, instance, child, force_create,
3723 428958aa Iustin Pop
                      info, force_open)
3724 a8083063 Iustin Pop
3725 428958aa Iustin Pop
  if not force_create:
3726 796cab27 Iustin Pop
    return
3727 796cab27 Iustin Pop
3728 de12473a Iustin Pop
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
3729 de12473a Iustin Pop
3730 de12473a Iustin Pop
3731 de12473a Iustin Pop
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
3732 de12473a Iustin Pop
  """Create a single block device on a given node.
3733 de12473a Iustin Pop

3734 de12473a Iustin Pop
  This will not recurse over children of the device, so they must be
3735 de12473a Iustin Pop
  created in advance.
3736 de12473a Iustin Pop

3737 de12473a Iustin Pop
  @param lu: the lu on whose behalf we execute
3738 de12473a Iustin Pop
  @param node: the node on which to create the device
3739 de12473a Iustin Pop
  @type instance: L{objects.Instance}
3740 de12473a Iustin Pop
  @param instance: the instance which owns the device
3741 de12473a Iustin Pop
  @type device: L{objects.Disk}
3742 de12473a Iustin Pop
  @param device: the device to create
3743 de12473a Iustin Pop
  @param info: the extra 'metadata' we should attach to the device
3744 de12473a Iustin Pop
      (this will be represented as a LVM tag)
3745 de12473a Iustin Pop
  @type force_open: boolean
3746 de12473a Iustin Pop
  @param force_open: this parameter will be passes to the
3747 de12473a Iustin Pop
      L{backend.CreateBlockDevice} function where it specifies
3748 de12473a Iustin Pop
      whether we run on primary or not, and it affects both
3749 de12473a Iustin Pop
      the child assembly and the device own Open() execution
3750 de12473a Iustin Pop

3751 de12473a Iustin Pop
  """
3752 b9bddb6b Iustin Pop
  lu.cfg.SetDiskID(device, node)
3753 7d81697f Iustin Pop
  result = lu.rpc.call_blockdev_create(node, device, device.size,
3754 428958aa Iustin Pop
                                       instance.name, force_open, info)
3755 7d81697f Iustin Pop
  msg = result.RemoteFailMsg()
3756 7d81697f Iustin Pop
  if msg:
3757 428958aa Iustin Pop
    raise errors.OpExecError("Can't create block device %s on"
3758 7d81697f Iustin Pop
                             " node %s for instance %s: %s" %
3759 7d81697f Iustin Pop
                             (device, node, instance.name, msg))
3760 a8083063 Iustin Pop
  if device.physical_id is None:
3761 7d81697f Iustin Pop
    device.physical_id = result.data[1]
3762 a8083063 Iustin Pop
3763 a8083063 Iustin Pop
3764 b9bddb6b Iustin Pop
def _GenerateUniqueNames(lu, exts):
3765 923b1523 Iustin Pop
  """Generate a suitable LV name.
3766 923b1523 Iustin Pop

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

3769 923b1523 Iustin Pop
  """
3770 923b1523 Iustin Pop
  results = []
3771 923b1523 Iustin Pop
  for val in exts:
3772 b9bddb6b Iustin Pop
    new_id = lu.cfg.GenerateUniqueID()
3773 923b1523 Iustin Pop
    results.append("%s%s" % (new_id, val))
3774 923b1523 Iustin Pop
  return results
3775 923b1523 Iustin Pop
3776 923b1523 Iustin Pop
3777 b9bddb6b Iustin Pop
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
3778 ffa1c0dc Iustin Pop
                         p_minor, s_minor):
3779 a1f445d3 Iustin Pop
  """Generate a drbd8 device complete with its children.
3780 a1f445d3 Iustin Pop

3781 a1f445d3 Iustin Pop
  """
3782 b9bddb6b Iustin Pop
  port = lu.cfg.AllocatePort()
3783 b9bddb6b Iustin Pop
  vgname = lu.cfg.GetVGName()
3784 b9bddb6b Iustin Pop
  shared_secret = lu.cfg.GenerateDRBDSecret()
3785 a1f445d3 Iustin Pop
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3786 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[0]))
3787 a1f445d3 Iustin Pop
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3788 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[1]))
3789 a1f445d3 Iustin Pop
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
3790 ffa1c0dc Iustin Pop
                          logical_id=(primary, secondary, port,
3791 f9518d38 Iustin Pop
                                      p_minor, s_minor,
3792 f9518d38 Iustin Pop
                                      shared_secret),
3793 ffa1c0dc Iustin Pop
                          children=[dev_data, dev_meta],
3794 a1f445d3 Iustin Pop
                          iv_name=iv_name)
3795 a1f445d3 Iustin Pop
  return drbd_dev
3796 a1f445d3 Iustin Pop
3797 7c0d6283 Michael Hanselmann
3798 b9bddb6b Iustin Pop
def _GenerateDiskTemplate(lu, template_name,
3799 a8083063 Iustin Pop
                          instance_name, primary_node,
3800 08db7c5c Iustin Pop
                          secondary_nodes, disk_info,
3801 e2a65344 Iustin Pop
                          file_storage_dir, file_driver,
3802 e2a65344 Iustin Pop
                          base_index):
3803 a8083063 Iustin Pop
  """Generate the entire disk layout for a given template type.
3804 a8083063 Iustin Pop

3805 a8083063 Iustin Pop
  """
3806 a8083063 Iustin Pop
  #TODO: compute space requirements
3807 a8083063 Iustin Pop
3808 b9bddb6b Iustin Pop
  vgname = lu.cfg.GetVGName()
3809 08db7c5c Iustin Pop
  disk_count = len(disk_info)
3810 08db7c5c Iustin Pop
  disks = []
3811 3517d9b9 Manuel Franceschini
  if template_name == constants.DT_DISKLESS:
3812 08db7c5c Iustin Pop
    pass
3813 3517d9b9 Manuel Franceschini
  elif template_name == constants.DT_PLAIN:
3814 a8083063 Iustin Pop
    if len(secondary_nodes) != 0:
3815 a8083063 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
3816 923b1523 Iustin Pop
3817 08db7c5c Iustin Pop
    names = _GenerateUniqueNames(lu, [".disk%d" % i
3818 08db7c5c Iustin Pop
                                      for i in range(disk_count)])
3819 08db7c5c Iustin Pop
    for idx, disk in enumerate(disk_info):
3820 e2a65344 Iustin Pop
      disk_index = idx + base_index
3821 08db7c5c Iustin Pop
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
3822 08db7c5c Iustin Pop
                              logical_id=(vgname, names[idx]),
3823 e2a65344 Iustin Pop
                              iv_name="disk/%d" % disk_index)
3824 08db7c5c Iustin Pop
      disks.append(disk_dev)
3825 a1f445d3 Iustin Pop
  elif template_name == constants.DT_DRBD8:
3826 a1f445d3 Iustin Pop
    if len(secondary_nodes) != 1:
3827 a1f445d3 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
3828 a1f445d3 Iustin Pop
    remote_node = secondary_nodes[0]
3829 08db7c5c Iustin Pop
    minors = lu.cfg.AllocateDRBDMinor(
3830 08db7c5c Iustin Pop
      [primary_node, remote_node] * len(disk_info), instance_name)
3831 08db7c5c Iustin Pop
3832 e6c1ff2f Iustin Pop
    names = []
3833 e6c1ff2f Iustin Pop
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % i
3834 e6c1ff2f Iustin Pop
                                               for i in range(disk_count)]):
3835 e6c1ff2f Iustin Pop
      names.append(lv_prefix + "_data")
3836 e6c1ff2f Iustin Pop
      names.append(lv_prefix + "_meta")
3837 08db7c5c Iustin Pop
    for idx, disk in enumerate(disk_info):
3838 112050d9 Iustin Pop
      disk_index = idx + base_index
3839 08db7c5c Iustin Pop
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3840 08db7c5c Iustin Pop
                                      disk["size"], names[idx*2:idx*2+2],
3841 e2a65344 Iustin Pop
                                      "disk/%d" % disk_index,
3842 08db7c5c Iustin Pop
                                      minors[idx*2], minors[idx*2+1])
3843 08db7c5c Iustin Pop
      disks.append(disk_dev)
3844 0f1a06e3 Manuel Franceschini
  elif template_name == constants.DT_FILE:
3845 0f1a06e3 Manuel Franceschini
    if len(secondary_nodes) != 0:
3846 0f1a06e3 Manuel Franceschini
      raise errors.ProgrammerError("Wrong template configuration")
3847 0f1a06e3 Manuel Franceschini
3848 08db7c5c Iustin Pop
    for idx, disk in enumerate(disk_info):
3849 112050d9 Iustin Pop
      disk_index = idx + base_index
3850 08db7c5c Iustin Pop
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
3851 e2a65344 Iustin Pop
                              iv_name="disk/%d" % disk_index,
3852 08db7c5c Iustin Pop
                              logical_id=(file_driver,
3853 08db7c5c Iustin Pop
                                          "%s/disk%d" % (file_storage_dir,
3854 08db7c5c Iustin Pop
                                                         idx)))
3855 08db7c5c Iustin Pop
      disks.append(disk_dev)
3856 a8083063 Iustin Pop
  else:
3857 a8083063 Iustin Pop
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3858 a8083063 Iustin Pop
  return disks
3859 a8083063 Iustin Pop
3860 a8083063 Iustin Pop
3861 a0c3fea1 Michael Hanselmann
def _GetInstanceInfoText(instance):
3862 3ecf6786 Iustin Pop
  """Compute that text that should be added to the disk's metadata.
3863 3ecf6786 Iustin Pop

3864 3ecf6786 Iustin Pop
  """
3865 a0c3fea1 Michael Hanselmann
  return "originstname+%s" % instance.name
3866 a0c3fea1 Michael Hanselmann
3867 a0c3fea1 Michael Hanselmann
3868 b9bddb6b Iustin Pop
def _CreateDisks(lu, instance):
3869 a8083063 Iustin Pop
  """Create all disks for an instance.
3870 a8083063 Iustin Pop

3871 a8083063 Iustin Pop
  This abstracts away some work from AddInstance.
3872 a8083063 Iustin Pop

3873 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
3874 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
3875 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
3876 e4376078 Iustin Pop
  @param instance: the instance whose disks we should create
3877 e4376078 Iustin Pop
  @rtype: boolean
3878 e4376078 Iustin Pop
  @return: the success of the creation
3879 a8083063 Iustin Pop

3880 a8083063 Iustin Pop
  """
3881 a0c3fea1 Michael Hanselmann
  info = _GetInstanceInfoText(instance)
3882 428958aa Iustin Pop
  pnode = instance.primary_node
3883 a0c3fea1 Michael Hanselmann
3884 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3885 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3886 428958aa Iustin Pop
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
3887 0f1a06e3 Manuel Franceschini
3888 781de953 Iustin Pop
    if result.failed or not result.data:
3889 428958aa Iustin Pop
      raise errors.OpExecError("Could not connect to node '%s'" % pnode)
3890 0f1a06e3 Manuel Franceschini
3891 781de953 Iustin Pop
    if not result.data[0]:
3892 796cab27 Iustin Pop
      raise errors.OpExecError("Failed to create directory '%s'" %
3893 796cab27 Iustin Pop
                               file_storage_dir)
3894 0f1a06e3 Manuel Franceschini
3895 24991749 Iustin Pop
  # Note: this needs to be kept in sync with adding of disks in
3896 24991749 Iustin Pop
  # LUSetInstanceParams
3897 a8083063 Iustin Pop
  for device in instance.disks:
3898 9a4f63d1 Iustin Pop
    logging.info("Creating volume %s for instance %s",
3899 9a4f63d1 Iustin Pop
                 device.iv_name, instance.name)
3900 a8083063 Iustin Pop
    #HARDCODE
3901 428958aa Iustin Pop
    for node in instance.all_nodes:
3902 428958aa Iustin Pop
      f_create = node == pnode
3903 428958aa Iustin Pop
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
3904 a8083063 Iustin Pop
3905 a8083063 Iustin Pop
3906 b9bddb6b Iustin Pop
def _RemoveDisks(lu, instance):
3907 a8083063 Iustin Pop
  """Remove all disks for an instance.
3908 a8083063 Iustin Pop

3909 a8083063 Iustin Pop
  This abstracts away some work from `AddInstance()` and
3910 a8083063 Iustin Pop
  `RemoveInstance()`. Note that in case some of the devices couldn't
3911 1d67656e Iustin Pop
  be removed, the removal will continue with the other ones (compare
3912 a8083063 Iustin Pop
  with `_CreateDisks()`).
3913 a8083063 Iustin Pop

3914 e4376078 Iustin Pop
  @type lu: L{LogicalUnit}
3915 e4376078 Iustin Pop
  @param lu: the logical unit on whose behalf we execute
3916 e4376078 Iustin Pop
  @type instance: L{objects.Instance}
3917 e4376078 Iustin Pop
  @param instance: the instance whose disks we should remove
3918 e4376078 Iustin Pop
  @rtype: boolean
3919 e4376078 Iustin Pop
  @return: the success of the removal
3920 a8083063 Iustin Pop

3921 a8083063 Iustin Pop
  """
3922 9a4f63d1 Iustin Pop
  logging.info("Removing block devices for instance %s", instance.name)
3923 a8083063 Iustin Pop
3924 a8083063 Iustin Pop
  result = True
3925 a8083063 Iustin Pop
  for device in instance.disks:
3926 a8083063 Iustin Pop
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3927 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(disk, node)
3928 781de953 Iustin Pop
      result = lu.rpc.call_blockdev_remove(node, disk)
3929 781de953 Iustin Pop
      if result.failed or not result.data:
3930 86d9d3bb Iustin Pop
        lu.proc.LogWarning("Could not remove block device %s on node %s,"
3931 86d9d3bb Iustin Pop
                           " continuing anyway", device.iv_name, node)
3932 a8083063 Iustin Pop
        result = False
3933 0f1a06e3 Manuel Franceschini
3934 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3935 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3936 781de953 Iustin Pop
    result = lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3937 781de953 Iustin Pop
                                                 file_storage_dir)
3938 781de953 Iustin Pop
    if result.failed or not result.data:
3939 9a4f63d1 Iustin Pop
      logging.error("Could not remove directory '%s'", file_storage_dir)
3940 0f1a06e3 Manuel Franceschini
      result = False
3941 0f1a06e3 Manuel Franceschini
3942 a8083063 Iustin Pop
  return result
3943 a8083063 Iustin Pop
3944 a8083063 Iustin Pop
3945 08db7c5c Iustin Pop
def _ComputeDiskSize(disk_template, disks):
3946 e2fe6369 Iustin Pop
  """Compute disk size requirements in the volume group
3947 e2fe6369 Iustin Pop

3948 e2fe6369 Iustin Pop
  """
3949 e2fe6369 Iustin Pop
  # Required free disk space as a function of disk and swap space
3950 e2fe6369 Iustin Pop
  req_size_dict = {
3951 e2fe6369 Iustin Pop
    constants.DT_DISKLESS: None,
3952 08db7c5c Iustin Pop
    constants.DT_PLAIN: sum(d["size"] for d in disks),
3953 08db7c5c Iustin Pop
    # 128 MB are added for drbd metadata for each disk
3954 08db7c5c Iustin Pop
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
3955 e2fe6369 Iustin Pop
    constants.DT_FILE: None,
3956 e2fe6369 Iustin Pop
  }
3957 e2fe6369 Iustin Pop
3958 e2fe6369 Iustin Pop
  if disk_template not in req_size_dict:
3959 e2fe6369 Iustin Pop
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3960 e2fe6369 Iustin Pop
                                 " is unknown" %  disk_template)
3961 e2fe6369 Iustin Pop
3962 e2fe6369 Iustin Pop
  return req_size_dict[disk_template]
3963 e2fe6369 Iustin Pop
3964 e2fe6369 Iustin Pop
3965 74409b12 Iustin Pop
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3966 74409b12 Iustin Pop
  """Hypervisor parameter validation.
3967 74409b12 Iustin Pop

3968 74409b12 Iustin Pop
  This function abstract the hypervisor parameter validation to be
3969 74409b12 Iustin Pop
  used in both instance create and instance modify.
3970 74409b12 Iustin Pop

3971 74409b12 Iustin Pop
  @type lu: L{LogicalUnit}
3972 74409b12 Iustin Pop
  @param lu: the logical unit for which we check
3973 74409b12 Iustin Pop
  @type nodenames: list
3974 74409b12 Iustin Pop
  @param nodenames: the list of nodes on which we should check
3975 74409b12 Iustin Pop
  @type hvname: string
3976 74409b12 Iustin Pop
  @param hvname: the name of the hypervisor we should use
3977 74409b12 Iustin Pop
  @type hvparams: dict
3978 74409b12 Iustin Pop
  @param hvparams: the parameters which we need to check
3979 74409b12 Iustin Pop
  @raise errors.OpPrereqError: if the parameters are not valid
3980 74409b12 Iustin Pop

3981 74409b12 Iustin Pop
  """
3982 74409b12 Iustin Pop
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
3983 74409b12 Iustin Pop
                                                  hvname,
3984 74409b12 Iustin Pop
                                                  hvparams)
3985 74409b12 Iustin Pop
  for node in nodenames:
3986 781de953 Iustin Pop
    info = hvinfo[node]
3987 781de953 Iustin Pop
    info.Raise()
3988 781de953 Iustin Pop
    if not info.data or not isinstance(info.data, (tuple, list)):
3989 74409b12 Iustin Pop
      raise errors.OpPrereqError("Cannot get current information"
3990 781de953 Iustin Pop
                                 " from node '%s' (%s)" % (node, info.data))
3991 781de953 Iustin Pop
    if not info.data[0]:
3992 74409b12 Iustin Pop
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
3993 781de953 Iustin Pop
                                 " %s" % info.data[1])
3994 74409b12 Iustin Pop
3995 74409b12 Iustin Pop
3996 a8083063 Iustin Pop
class LUCreateInstance(LogicalUnit):
3997 a8083063 Iustin Pop
  """Create an instance.
3998 a8083063 Iustin Pop

3999 a8083063 Iustin Pop
  """
4000 a8083063 Iustin Pop
  HPATH = "instance-add"
4001 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4002 08db7c5c Iustin Pop
  _OP_REQP = ["instance_name", "disks", "disk_template",
4003 08db7c5c Iustin Pop
              "mode", "start",
4004 08db7c5c Iustin Pop
              "wait_for_sync", "ip_check", "nics",
4005 338e51e8 Iustin Pop
              "hvparams", "beparams"]
4006 7baf741d Guido Trotter
  REQ_BGL = False
4007 7baf741d Guido Trotter
4008 7baf741d Guido Trotter
  def _ExpandNode(self, node):
4009 7baf741d Guido Trotter
    """Expands and checks one node name.
4010 7baf741d Guido Trotter

4011 7baf741d Guido Trotter
    """
4012 7baf741d Guido Trotter
    node_full = self.cfg.ExpandNodeName(node)
4013 7baf741d Guido Trotter
    if node_full is None:
4014 7baf741d Guido Trotter
      raise errors.OpPrereqError("Unknown node %s" % node)
4015 7baf741d Guido Trotter
    return node_full
4016 7baf741d Guido Trotter
4017 7baf741d Guido Trotter
  def ExpandNames(self):
4018 7baf741d Guido Trotter
    """ExpandNames for CreateInstance.
4019 7baf741d Guido Trotter

4020 7baf741d Guido Trotter
    Figure out the right locks for instance creation.
4021 7baf741d Guido Trotter

4022 7baf741d Guido Trotter
    """
4023 7baf741d Guido Trotter
    self.needed_locks = {}
4024 7baf741d Guido Trotter
4025 7baf741d Guido Trotter
    # set optional parameters to none if they don't exist
4026 6785674e Iustin Pop
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
4027 7baf741d Guido Trotter
      if not hasattr(self.op, attr):
4028 7baf741d Guido Trotter
        setattr(self.op, attr, None)
4029 7baf741d Guido Trotter
4030 4b2f38dd Iustin Pop
    # cheap checks, mostly valid constants given
4031 4b2f38dd Iustin Pop
4032 7baf741d Guido Trotter
    # verify creation mode
4033 7baf741d Guido Trotter
    if self.op.mode not in (constants.INSTANCE_CREATE,
4034 7baf741d Guido Trotter
                            constants.INSTANCE_IMPORT):
4035 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
4036 7baf741d Guido Trotter
                                 self.op.mode)
4037 4b2f38dd Iustin Pop
4038 7baf741d Guido Trotter
    # disk template and mirror node verification
4039 7baf741d Guido Trotter
    if self.op.disk_template not in constants.DISK_TEMPLATES:
4040 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid disk template name")
4041 7baf741d Guido Trotter
4042 4b2f38dd Iustin Pop
    if self.op.hypervisor is None:
4043 4b2f38dd Iustin Pop
      self.op.hypervisor = self.cfg.GetHypervisorType()
4044 4b2f38dd Iustin Pop
4045 8705eb96 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
4046 8705eb96 Iustin Pop
    enabled_hvs = cluster.enabled_hypervisors
4047 4b2f38dd Iustin Pop
    if self.op.hypervisor not in enabled_hvs:
4048 4b2f38dd Iustin Pop
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
4049 4b2f38dd Iustin Pop
                                 " cluster (%s)" % (self.op.hypervisor,
4050 4b2f38dd Iustin Pop
                                  ",".join(enabled_hvs)))
4051 4b2f38dd Iustin Pop
4052 6785674e Iustin Pop
    # check hypervisor parameter syntax (locally)
4053 6785674e Iustin Pop
4054 8705eb96 Iustin Pop
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
4055 8705eb96 Iustin Pop
                                  self.op.hvparams)
4056 6785674e Iustin Pop
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
4057 8705eb96 Iustin Pop
    hv_type.CheckParameterSyntax(filled_hvp)
4058 6785674e Iustin Pop
4059 338e51e8 Iustin Pop
    # fill and remember the beparams dict
4060 d4b72030 Guido Trotter
    utils.CheckBEParams(self.op.beparams)
4061 338e51e8 Iustin Pop
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4062 338e51e8 Iustin Pop
                                    self.op.beparams)
4063 338e51e8 Iustin Pop
4064 7baf741d Guido Trotter
    #### instance parameters check
4065 7baf741d Guido Trotter
4066 7baf741d Guido Trotter
    # instance name verification
4067 7baf741d Guido Trotter
    hostname1 = utils.HostInfo(self.op.instance_name)
4068 7baf741d Guido Trotter
    self.op.instance_name = instance_name = hostname1.name
4069 7baf741d Guido Trotter
4070 7baf741d Guido Trotter
    # this is just a preventive check, but someone might still add this
4071 7baf741d Guido Trotter
    # instance in the meantime, and creation will fail at lock-add time
4072 7baf741d Guido Trotter
    if instance_name in self.cfg.GetInstanceList():
4073 7baf741d Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4074 7baf741d Guido Trotter
                                 instance_name)
4075 7baf741d Guido Trotter
4076 7baf741d Guido Trotter
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
4077 7baf741d Guido Trotter
4078 08db7c5c Iustin Pop
    # NIC buildup
4079 08db7c5c Iustin Pop
    self.nics = []
4080 08db7c5c Iustin Pop
    for nic in self.op.nics:
4081 08db7c5c Iustin Pop
      # ip validity checks
4082 08db7c5c Iustin Pop
      ip = nic.get("ip", None)
4083 08db7c5c Iustin Pop
      if ip is None or ip.lower() == "none":
4084 08db7c5c Iustin Pop
        nic_ip = None
4085 08db7c5c Iustin Pop
      elif ip.lower() == constants.VALUE_AUTO:
4086 08db7c5c Iustin Pop
        nic_ip = hostname1.ip
4087 08db7c5c Iustin Pop
      else:
4088 08db7c5c Iustin Pop
        if not utils.IsValidIP(ip):
4089 08db7c5c Iustin Pop
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
4090 08db7c5c Iustin Pop
                                     " like a valid IP" % ip)
4091 08db7c5c Iustin Pop
        nic_ip = ip
4092 08db7c5c Iustin Pop
4093 08db7c5c Iustin Pop
      # MAC address verification
4094 08db7c5c Iustin Pop
      mac = nic.get("mac", constants.VALUE_AUTO)
4095 08db7c5c Iustin Pop
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4096 08db7c5c Iustin Pop
        if not utils.IsValidMac(mac.lower()):
4097 08db7c5c Iustin Pop
          raise errors.OpPrereqError("Invalid MAC address specified: %s" %
4098 08db7c5c Iustin Pop
                                     mac)
4099 08db7c5c Iustin Pop
      # bridge verification
4100 08db7c5c Iustin Pop
      bridge = nic.get("bridge", self.cfg.GetDefBridge())
4101 08db7c5c Iustin Pop
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
4102 08db7c5c Iustin Pop
4103 08db7c5c Iustin Pop
    # disk checks/pre-build
4104 08db7c5c Iustin Pop
    self.disks = []
4105 08db7c5c Iustin Pop
    for disk in self.op.disks:
4106 08db7c5c Iustin Pop
      mode = disk.get("mode", constants.DISK_RDWR)
4107 08db7c5c Iustin Pop
      if mode not in constants.DISK_ACCESS_SET:
4108 08db7c5c Iustin Pop
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
4109 08db7c5c Iustin Pop
                                   mode)
4110 08db7c5c Iustin Pop
      size = disk.get("size", None)
4111 08db7c5c Iustin Pop
      if size is None:
4112 08db7c5c Iustin Pop
        raise errors.OpPrereqError("Missing disk size")
4113 08db7c5c Iustin Pop
      try:
4114 08db7c5c Iustin Pop
        size = int(size)
4115 08db7c5c Iustin Pop
      except ValueError:
4116 08db7c5c Iustin Pop
        raise errors.OpPrereqError("Invalid disk size '%s'" % size)
4117 08db7c5c Iustin Pop
      self.disks.append({"size": size, "mode": mode})
4118 08db7c5c Iustin Pop
4119 7baf741d Guido Trotter
    # used in CheckPrereq for ip ping check
4120 7baf741d Guido Trotter
    self.check_ip = hostname1.ip
4121 7baf741d Guido Trotter
4122 7baf741d Guido Trotter
    # file storage checks
4123 7baf741d Guido Trotter
    if (self.op.file_driver and
4124 7baf741d Guido Trotter
        not self.op.file_driver in constants.FILE_DRIVER):
4125 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
4126 7baf741d Guido Trotter
                                 self.op.file_driver)
4127 7baf741d Guido Trotter
4128 7baf741d Guido Trotter
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
4129 7baf741d Guido Trotter
      raise errors.OpPrereqError("File storage directory path not absolute")
4130 7baf741d Guido Trotter
4131 7baf741d Guido Trotter
    ### Node/iallocator related checks
4132 7baf741d Guido Trotter
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
4133 7baf741d Guido Trotter
      raise errors.OpPrereqError("One and only one of iallocator and primary"
4134 7baf741d Guido Trotter
                                 " node must be given")
4135 7baf741d Guido Trotter
4136 7baf741d Guido Trotter
    if self.op.iallocator:
4137 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4138 7baf741d Guido Trotter
    else:
4139 7baf741d Guido Trotter
      self.op.pnode = self._ExpandNode(self.op.pnode)
4140 7baf741d Guido Trotter
      nodelist = [self.op.pnode]
4141 7baf741d Guido Trotter
      if self.op.snode is not None:
4142 7baf741d Guido Trotter
        self.op.snode = self._ExpandNode(self.op.snode)
4143 7baf741d Guido Trotter
        nodelist.append(self.op.snode)
4144 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = nodelist
4145 7baf741d Guido Trotter
4146 7baf741d Guido Trotter
    # in case of import lock the source node too
4147 7baf741d Guido Trotter
    if self.op.mode == constants.INSTANCE_IMPORT:
4148 7baf741d Guido Trotter
      src_node = getattr(self.op, "src_node", None)
4149 7baf741d Guido Trotter
      src_path = getattr(self.op, "src_path", None)
4150 7baf741d Guido Trotter
4151 b9322a9f Guido Trotter
      if src_path is None:
4152 b9322a9f Guido Trotter
        self.op.src_path = src_path = self.op.instance_name
4153 b9322a9f Guido Trotter
4154 b9322a9f Guido Trotter
      if src_node is None:
4155 b9322a9f Guido Trotter
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4156 b9322a9f Guido Trotter
        self.op.src_node = None
4157 b9322a9f Guido Trotter
        if os.path.isabs(src_path):
4158 b9322a9f Guido Trotter
          raise errors.OpPrereqError("Importing an instance from an absolute"
4159 b9322a9f Guido Trotter
                                     " path requires a source node option.")
4160 b9322a9f Guido Trotter
      else:
4161 b9322a9f Guido Trotter
        self.op.src_node = src_node = self._ExpandNode(src_node)
4162 b9322a9f Guido Trotter
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4163 b9322a9f Guido Trotter
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
4164 b9322a9f Guido Trotter
        if not os.path.isabs(src_path):
4165 b9322a9f Guido Trotter
          self.op.src_path = src_path = \
4166 b9322a9f Guido Trotter
            os.path.join(constants.EXPORT_DIR, src_path)
4167 7baf741d Guido Trotter
4168 7baf741d Guido Trotter
    else: # INSTANCE_CREATE
4169 7baf741d Guido Trotter
      if getattr(self.op, "os_type", None) is None:
4170 7baf741d Guido Trotter
        raise errors.OpPrereqError("No guest OS specified")
4171 a8083063 Iustin Pop
4172 538475ca Iustin Pop
  def _RunAllocator(self):
4173 538475ca Iustin Pop
    """Run the allocator based on input opcode.
4174 538475ca Iustin Pop

4175 538475ca Iustin Pop
    """
4176 08db7c5c Iustin Pop
    nics = [n.ToDict() for n in self.nics]
4177 72737a7f Iustin Pop
    ial = IAllocator(self,
4178 29859cb7 Iustin Pop
                     mode=constants.IALLOCATOR_MODE_ALLOC,
4179 d1c2dd75 Iustin Pop
                     name=self.op.instance_name,
4180 d1c2dd75 Iustin Pop
                     disk_template=self.op.disk_template,
4181 d1c2dd75 Iustin Pop
                     tags=[],
4182 d1c2dd75 Iustin Pop
                     os=self.op.os_type,
4183 338e51e8 Iustin Pop
                     vcpus=self.be_full[constants.BE_VCPUS],
4184 338e51e8 Iustin Pop
                     mem_size=self.be_full[constants.BE_MEMORY],
4185 08db7c5c Iustin Pop
                     disks=self.disks,
4186 d1c2dd75 Iustin Pop
                     nics=nics,
4187 8cc7e742 Guido Trotter
                     hypervisor=self.op.hypervisor,
4188 29859cb7 Iustin Pop
                     )
4189 d1c2dd75 Iustin Pop
4190 d1c2dd75 Iustin Pop
    ial.Run(self.op.iallocator)
4191 d1c2dd75 Iustin Pop
4192 d1c2dd75 Iustin Pop
    if not ial.success:
4193 538475ca Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
4194 538475ca Iustin Pop
                                 " iallocator '%s': %s" % (self.op.iallocator,
4195 d1c2dd75 Iustin Pop
                                                           ial.info))
4196 27579978 Iustin Pop
    if len(ial.nodes) != ial.required_nodes:
4197 538475ca Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4198 538475ca Iustin Pop
                                 " of nodes (%s), required %s" %
4199 97abc79f Iustin Pop
                                 (self.op.iallocator, len(ial.nodes),
4200 1ce4bbe3 René Nussbaumer
                                  ial.required_nodes))
4201 d1c2dd75 Iustin Pop
    self.op.pnode = ial.nodes[0]
4202 86d9d3bb Iustin Pop
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
4203 86d9d3bb Iustin Pop
                 self.op.instance_name, self.op.iallocator,
4204 86d9d3bb Iustin Pop
                 ", ".join(ial.nodes))
4205 27579978 Iustin Pop
    if ial.required_nodes == 2:
4206 d1c2dd75 Iustin Pop
      self.op.snode = ial.nodes[1]
4207 538475ca Iustin Pop
4208 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4209 a8083063 Iustin Pop
    """Build hooks env.
4210 a8083063 Iustin Pop

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

4213 a8083063 Iustin Pop
    """
4214 a8083063 Iustin Pop
    env = {
4215 396e1b78 Michael Hanselmann
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
4216 08db7c5c Iustin Pop
      "INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks),
4217 a8083063 Iustin Pop
      "INSTANCE_ADD_MODE": self.op.mode,
4218 a8083063 Iustin Pop
      }
4219 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
4220 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_NODE"] = self.op.src_node
4221 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_PATH"] = self.op.src_path
4222 09acf207 Guido Trotter
      env["INSTANCE_SRC_IMAGES"] = self.src_images
4223 396e1b78 Michael Hanselmann
4224 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
4225 396e1b78 Michael Hanselmann
      primary_node=self.op.pnode,
4226 396e1b78 Michael Hanselmann
      secondary_nodes=self.secondaries,
4227 396e1b78 Michael Hanselmann
      status=self.instance_status,
4228 ecb215b5 Michael Hanselmann
      os_type=self.op.os_type,
4229 338e51e8 Iustin Pop
      memory=self.be_full[constants.BE_MEMORY],
4230 338e51e8 Iustin Pop
      vcpus=self.be_full[constants.BE_VCPUS],
4231 08db7c5c Iustin Pop
      nics=[(n.ip, n.bridge, n.mac) for n in self.nics],
4232 396e1b78 Michael Hanselmann
    ))
4233 a8083063 Iustin Pop
4234 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
4235 a8083063 Iustin Pop
          self.secondaries)
4236 a8083063 Iustin Pop
    return env, nl, nl
4237 a8083063 Iustin Pop
4238 a8083063 Iustin Pop
4239 a8083063 Iustin Pop
  def CheckPrereq(self):
4240 a8083063 Iustin Pop
    """Check prerequisites.
4241 a8083063 Iustin Pop

4242 a8083063 Iustin Pop
    """
4243 eedc99de Manuel Franceschini
    if (not self.cfg.GetVGName() and
4244 eedc99de Manuel Franceschini
        self.op.disk_template not in constants.DTS_NOT_LVM):
4245 eedc99de Manuel Franceschini
      raise errors.OpPrereqError("Cluster does not support lvm-based"
4246 eedc99de Manuel Franceschini
                                 " instances")
4247 eedc99de Manuel Franceschini
4248 e69d05fd Iustin Pop
4249 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
4250 7baf741d Guido Trotter
      src_node = self.op.src_node
4251 7baf741d Guido Trotter
      src_path = self.op.src_path
4252 a8083063 Iustin Pop
4253 c0cbdc67 Guido Trotter
      if src_node is None:
4254 c0cbdc67 Guido Trotter
        exp_list = self.rpc.call_export_list(
4255 781de953 Iustin Pop
          self.acquired_locks[locking.LEVEL_NODE])
4256 c0cbdc67 Guido Trotter
        found = False
4257 c0cbdc67 Guido Trotter
        for node in exp_list:
4258 781de953 Iustin Pop
          if not exp_list[node].failed and src_path in exp_list[node].data:
4259 c0cbdc67 Guido Trotter
            found = True
4260 c0cbdc67 Guido Trotter
            self.op.src_node = src_node = node
4261 c0cbdc67 Guido Trotter
            self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
4262 c0cbdc67 Guido Trotter
                                                       src_path)
4263 c0cbdc67 Guido Trotter
            break
4264 c0cbdc67 Guido Trotter
        if not found:
4265 c0cbdc67 Guido Trotter
          raise errors.OpPrereqError("No export found for relative path %s" %
4266 c0cbdc67 Guido Trotter
                                      src_path)
4267 c0cbdc67 Guido Trotter
4268 7527a8a4 Iustin Pop
      _CheckNodeOnline(self, src_node)
4269 781de953 Iustin Pop
      result = self.rpc.call_export_info(src_node, src_path)
4270 781de953 Iustin Pop
      result.Raise()
4271 781de953 Iustin Pop
      if not result.data:
4272 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
4273 a8083063 Iustin Pop
4274 781de953 Iustin Pop
      export_info = result.data
4275 a8083063 Iustin Pop
      if not export_info.has_section(constants.INISECT_EXP):
4276 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Corrupted export config")
4277 a8083063 Iustin Pop
4278 a8083063 Iustin Pop
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
4279 a8083063 Iustin Pop
      if (int(ei_version) != constants.EXPORT_VERSION):
4280 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
4281 3ecf6786 Iustin Pop
                                   (ei_version, constants.EXPORT_VERSION))
4282 a8083063 Iustin Pop
4283 09acf207 Guido Trotter
      # Check that the new instance doesn't have less disks than the export
4284 08db7c5c Iustin Pop
      instance_disks = len(self.disks)
4285 09acf207 Guido Trotter
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
4286 09acf207 Guido Trotter
      if instance_disks < export_disks:
4287 09acf207 Guido Trotter
        raise errors.OpPrereqError("Not enough disks to import."
4288 09acf207 Guido Trotter
                                   " (instance: %d, export: %d)" %
4289 726d7d68 Iustin Pop
                                   (instance_disks, export_disks))
4290 a8083063 Iustin Pop
4291 a8083063 Iustin Pop
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
4292 09acf207 Guido Trotter
      disk_images = []
4293 09acf207 Guido Trotter
      for idx in range(export_disks):
4294 09acf207 Guido Trotter
        option = 'disk%d_dump' % idx
4295 09acf207 Guido Trotter
        if export_info.has_option(constants.INISECT_INS, option):
4296 09acf207 Guido Trotter
          # FIXME: are the old os-es, disk sizes, etc. useful?
4297 09acf207 Guido Trotter
          export_name = export_info.get(constants.INISECT_INS, option)
4298 09acf207 Guido Trotter
          image = os.path.join(src_path, export_name)
4299 09acf207 Guido Trotter
          disk_images.append(image)
4300 09acf207 Guido Trotter
        else:
4301 09acf207 Guido Trotter
          disk_images.append(False)
4302 09acf207 Guido Trotter
4303 09acf207 Guido Trotter
      self.src_images = disk_images
4304 901a65c1 Iustin Pop
4305 b4364a6b Guido Trotter
      old_name = export_info.get(constants.INISECT_INS, 'name')
4306 b4364a6b Guido Trotter
      # FIXME: int() here could throw a ValueError on broken exports
4307 b4364a6b Guido Trotter
      exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count'))
4308 b4364a6b Guido Trotter
      if self.op.instance_name == old_name:
4309 b4364a6b Guido Trotter
        for idx, nic in enumerate(self.nics):
4310 b4364a6b Guido Trotter
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
4311 b4364a6b Guido Trotter
            nic_mac_ini = 'nic%d_mac' % idx
4312 b4364a6b Guido Trotter
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
4313 bc89efc3 Guido Trotter
4314 7baf741d Guido Trotter
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
4315 901a65c1 Iustin Pop
    if self.op.start and not self.op.ip_check:
4316 901a65c1 Iustin Pop
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
4317 901a65c1 Iustin Pop
                                 " adding an instance in start mode")
4318 901a65c1 Iustin Pop
4319 901a65c1 Iustin Pop
    if self.op.ip_check:
4320 7baf741d Guido Trotter
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
4321 901a65c1 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4322 7b3a8fb5 Iustin Pop
                                   (self.check_ip, self.op.instance_name))
4323 901a65c1 Iustin Pop
4324 538475ca Iustin Pop
    #### allocator run
4325 538475ca Iustin Pop
4326 538475ca Iustin Pop
    if self.op.iallocator is not None:
4327 538475ca Iustin Pop
      self._RunAllocator()
4328 0f1a06e3 Manuel Franceschini
4329 901a65c1 Iustin Pop
    #### node related checks
4330 901a65c1 Iustin Pop
4331 901a65c1 Iustin Pop
    # check primary node
4332 7baf741d Guido Trotter
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
4333 7baf741d Guido Trotter
    assert self.pnode is not None, \
4334 7baf741d Guido Trotter
      "Cannot retrieve locked node %s" % self.op.pnode
4335 7527a8a4 Iustin Pop
    if pnode.offline:
4336 7527a8a4 Iustin Pop
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
4337 7527a8a4 Iustin Pop
                                 pnode.name)
4338 7527a8a4 Iustin Pop
4339 901a65c1 Iustin Pop
    self.secondaries = []
4340 901a65c1 Iustin Pop
4341 901a65c1 Iustin Pop
    # mirror node verification
4342 a1f445d3 Iustin Pop
    if self.op.disk_template in constants.DTS_NET_MIRROR:
4343 7baf741d Guido Trotter
      if self.op.snode is None:
4344 a1f445d3 Iustin Pop
        raise errors.OpPrereqError("The networked disk templates need"
4345 3ecf6786 Iustin Pop
                                   " a mirror node")
4346 7baf741d Guido Trotter
      if self.op.snode == pnode.name:
4347 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The secondary node cannot be"
4348 3ecf6786 Iustin Pop
                                   " the primary node.")
4349 7baf741d Guido Trotter
      self.secondaries.append(self.op.snode)
4350 7527a8a4 Iustin Pop
      _CheckNodeOnline(self, self.op.snode)
4351 a8083063 Iustin Pop
4352 6785674e Iustin Pop
    nodenames = [pnode.name] + self.secondaries
4353 6785674e Iustin Pop
4354 e2fe6369 Iustin Pop
    req_size = _ComputeDiskSize(self.op.disk_template,
4355 08db7c5c Iustin Pop
                                self.disks)
4356 ed1ebc60 Guido Trotter
4357 8d75db10 Iustin Pop
    # Check lv size requirements
4358 8d75db10 Iustin Pop
    if req_size is not None:
4359 72737a7f Iustin Pop
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4360 72737a7f Iustin Pop
                                         self.op.hypervisor)
4361 8d75db10 Iustin Pop
      for node in nodenames:
4362 781de953 Iustin Pop
        info = nodeinfo[node]
4363 781de953 Iustin Pop
        info.Raise()
4364 781de953 Iustin Pop
        info = info.data
4365 8d75db10 Iustin Pop
        if not info:
4366 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Cannot get current information"
4367 3e91897b Iustin Pop
                                     " from node '%s'" % node)
4368 8d75db10 Iustin Pop
        vg_free = info.get('vg_free', None)
4369 8d75db10 Iustin Pop
        if not isinstance(vg_free, int):
4370 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Can't compute free disk space on"
4371 8d75db10 Iustin Pop
                                     " node %s" % node)
4372 8d75db10 Iustin Pop
        if req_size > info['vg_free']:
4373 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Not enough disk space on target node %s."
4374 8d75db10 Iustin Pop
                                     " %d MB available, %d MB required" %
4375 8d75db10 Iustin Pop
                                     (node, info['vg_free'], req_size))
4376 ed1ebc60 Guido Trotter
4377 74409b12 Iustin Pop
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
4378 6785674e Iustin Pop
4379 a8083063 Iustin Pop
    # os verification
4380 781de953 Iustin Pop
    result = self.rpc.call_os_get(pnode.name, self.op.os_type)
4381 781de953 Iustin Pop
    result.Raise()
4382 781de953 Iustin Pop
    if not isinstance(result.data, objects.OS):
4383 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
4384 3ecf6786 Iustin Pop
                                 " primary node"  % self.op.os_type)
4385 a8083063 Iustin Pop
4386 901a65c1 Iustin Pop
    # bridge check on primary node
4387 08db7c5c Iustin Pop
    bridges = [n.bridge for n in self.nics]
4388 781de953 Iustin Pop
    result = self.rpc.call_bridges_exist(self.pnode.name, bridges)
4389 781de953 Iustin Pop
    result.Raise()
4390 781de953 Iustin Pop
    if not result.data:
4391 781de953 Iustin Pop
      raise errors.OpPrereqError("One of the target bridges '%s' does not"
4392 781de953 Iustin Pop
                                 " exist on destination node '%s'" %
4393 08db7c5c Iustin Pop
                                 (",".join(bridges), pnode.name))
4394 a8083063 Iustin Pop
4395 49ce1563 Iustin Pop
    # memory check on primary node
4396 49ce1563 Iustin Pop
    if self.op.start:
4397 b9bddb6b Iustin Pop
      _CheckNodeFreeMemory(self, self.pnode.name,
4398 49ce1563 Iustin Pop
                           "creating instance %s" % self.op.instance_name,
4399 338e51e8 Iustin Pop
                           self.be_full[constants.BE_MEMORY],
4400 338e51e8 Iustin Pop
                           self.op.hypervisor)
4401 49ce1563 Iustin Pop
4402 a8083063 Iustin Pop
    if self.op.start:
4403 a8083063 Iustin Pop
      self.instance_status = 'up'
4404 a8083063 Iustin Pop
    else:
4405 a8083063 Iustin Pop
      self.instance_status = 'down'
4406 a8083063 Iustin Pop
4407 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4408 a8083063 Iustin Pop
    """Create and add the instance to the cluster.
4409 a8083063 Iustin Pop

4410 a8083063 Iustin Pop
    """
4411 a8083063 Iustin Pop
    instance = self.op.instance_name
4412 a8083063 Iustin Pop
    pnode_name = self.pnode.name
4413 a8083063 Iustin Pop
4414 08db7c5c Iustin Pop
    for nic in self.nics:
4415 08db7c5c Iustin Pop
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
4416 08db7c5c Iustin Pop
        nic.mac = self.cfg.GenerateMAC()
4417 a8083063 Iustin Pop
4418 e69d05fd Iustin Pop
    ht_kind = self.op.hypervisor
4419 2a6469d5 Alexander Schreiber
    if ht_kind in constants.HTS_REQ_PORT:
4420 2a6469d5 Alexander Schreiber
      network_port = self.cfg.AllocatePort()
4421 2a6469d5 Alexander Schreiber
    else:
4422 2a6469d5 Alexander Schreiber
      network_port = None
4423 58acb49d Alexander Schreiber
4424 6785674e Iustin Pop
    ##if self.op.vnc_bind_address is None:
4425 6785674e Iustin Pop
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
4426 31a853d2 Iustin Pop
4427 2c313123 Manuel Franceschini
    # this is needed because os.path.join does not accept None arguments
4428 2c313123 Manuel Franceschini
    if self.op.file_storage_dir is None:
4429 2c313123 Manuel Franceschini
      string_file_storage_dir = ""
4430 2c313123 Manuel Franceschini
    else:
4431 2c313123 Manuel Franceschini
      string_file_storage_dir = self.op.file_storage_dir
4432 2c313123 Manuel Franceschini
4433 0f1a06e3 Manuel Franceschini
    # build the full file storage dir path
4434 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.normpath(os.path.join(
4435 d6a02168 Michael Hanselmann
                                        self.cfg.GetFileStorageDir(),
4436 2c313123 Manuel Franceschini
                                        string_file_storage_dir, instance))
4437 0f1a06e3 Manuel Franceschini
4438 0f1a06e3 Manuel Franceschini
4439 b9bddb6b Iustin Pop
    disks = _GenerateDiskTemplate(self,
4440 a8083063 Iustin Pop
                                  self.op.disk_template,
4441 a8083063 Iustin Pop
                                  instance, pnode_name,
4442 08db7c5c Iustin Pop
                                  self.secondaries,
4443 08db7c5c Iustin Pop
                                  self.disks,
4444 0f1a06e3 Manuel Franceschini
                                  file_storage_dir,
4445 e2a65344 Iustin Pop
                                  self.op.file_driver,
4446 e2a65344 Iustin Pop
                                  0)
4447 a8083063 Iustin Pop
4448 a8083063 Iustin Pop
    iobj = objects.Instance(name=instance, os=self.op.os_type,
4449 a8083063 Iustin Pop
                            primary_node=pnode_name,
4450 08db7c5c Iustin Pop
                            nics=self.nics, disks=disks,
4451 a8083063 Iustin Pop
                            disk_template=self.op.disk_template,
4452 a8083063 Iustin Pop
                            status=self.instance_status,
4453 58acb49d Alexander Schreiber
                            network_port=network_port,
4454 338e51e8 Iustin Pop
                            beparams=self.op.beparams,
4455 6785674e Iustin Pop
                            hvparams=self.op.hvparams,
4456 e69d05fd Iustin Pop
                            hypervisor=self.op.hypervisor,
4457 a8083063 Iustin Pop
                            )
4458 a8083063 Iustin Pop
4459 a8083063 Iustin Pop
    feedback_fn("* creating instance disks...")
4460 796cab27 Iustin Pop
    try:
4461 796cab27 Iustin Pop
      _CreateDisks(self, iobj)
4462 796cab27 Iustin Pop
    except errors.OpExecError:
4463 796cab27 Iustin Pop
      self.LogWarning("Device creation failed, reverting...")
4464 796cab27 Iustin Pop
      try:
4465 796cab27 Iustin Pop
        _RemoveDisks(self, iobj)
4466 796cab27 Iustin Pop
      finally:
4467 796cab27 Iustin Pop
        self.cfg.ReleaseDRBDMinors(instance)
4468 796cab27 Iustin Pop
        raise
4469 a8083063 Iustin Pop
4470 a8083063 Iustin Pop
    feedback_fn("adding instance %s to cluster config" % instance)
4471 a8083063 Iustin Pop
4472 a8083063 Iustin Pop
    self.cfg.AddInstance(iobj)
4473 7baf741d Guido Trotter
    # Declare that we don't want to remove the instance lock anymore, as we've
4474 7baf741d Guido Trotter
    # added the instance to the config
4475 7baf741d Guido Trotter
    del self.remove_locks[locking.LEVEL_INSTANCE]
4476 a1578d63 Iustin Pop
    # Remove the temp. assignements for the instance's drbds
4477 a1578d63 Iustin Pop
    self.cfg.ReleaseDRBDMinors(instance)
4478 e36e96b4 Guido Trotter
    # Unlock all the nodes
4479 9c8971d7 Guido Trotter
    if self.op.mode == constants.INSTANCE_IMPORT:
4480 9c8971d7 Guido Trotter
      nodes_keep = [self.op.src_node]
4481 9c8971d7 Guido Trotter
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
4482 9c8971d7 Guido Trotter
                       if node != self.op.src_node]
4483 9c8971d7 Guido Trotter
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
4484 9c8971d7 Guido Trotter
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
4485 9c8971d7 Guido Trotter
    else:
4486 9c8971d7 Guido Trotter
      self.context.glm.release(locking.LEVEL_NODE)
4487 9c8971d7 Guido Trotter
      del self.acquired_locks[locking.LEVEL_NODE]
4488 a8083063 Iustin Pop
4489 a8083063 Iustin Pop
    if self.op.wait_for_sync:
4490 b9bddb6b Iustin Pop
      disk_abort = not _WaitForSync(self, iobj)
4491 a1f445d3 Iustin Pop
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
4492 a8083063 Iustin Pop
      # make sure the disks are not degraded (still sync-ing is ok)
4493 a8083063 Iustin Pop
      time.sleep(15)
4494 a8083063 Iustin Pop
      feedback_fn("* checking mirrors status")
4495 b9bddb6b Iustin Pop
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
4496 a8083063 Iustin Pop
    else:
4497 a8083063 Iustin Pop
      disk_abort = False
4498 a8083063 Iustin Pop
4499 a8083063 Iustin Pop
    if disk_abort:
4500 b9bddb6b Iustin Pop
      _RemoveDisks(self, iobj)
4501 a8083063 Iustin Pop
      self.cfg.RemoveInstance(iobj.name)
4502 7baf741d Guido Trotter
      # Make sure the instance lock gets removed
4503 7baf741d Guido Trotter
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
4504 3ecf6786 Iustin Pop
      raise errors.OpExecError("There are some degraded disks for"
4505 3ecf6786 Iustin Pop
                               " this instance")
4506 a8083063 Iustin Pop
4507 a8083063 Iustin Pop
    feedback_fn("creating os for instance %s on node %s" %
4508 a8083063 Iustin Pop
                (instance, pnode_name))
4509 a8083063 Iustin Pop
4510 a8083063 Iustin Pop
    if iobj.disk_template != constants.DT_DISKLESS:
4511 a8083063 Iustin Pop
      if self.op.mode == constants.INSTANCE_CREATE:
4512 a8083063 Iustin Pop
        feedback_fn("* running the instance OS create scripts...")
4513 781de953 Iustin Pop
        result = self.rpc.call_instance_os_add(pnode_name, iobj)
4514 20e01edd Iustin Pop
        msg = result.RemoteFailMsg()
4515 20e01edd Iustin Pop
        if msg:
4516 781de953 Iustin Pop
          raise errors.OpExecError("Could not add os for instance %s"
4517 20e01edd Iustin Pop
                                   " on node %s: %s" %
4518 20e01edd Iustin Pop
                                   (instance, pnode_name, msg))
4519 a8083063 Iustin Pop
4520 a8083063 Iustin Pop
      elif self.op.mode == constants.INSTANCE_IMPORT:
4521 a8083063 Iustin Pop
        feedback_fn("* running the instance OS import scripts...")
4522 a8083063 Iustin Pop
        src_node = self.op.src_node
4523 09acf207 Guido Trotter
        src_images = self.src_images
4524 62c9ec92 Iustin Pop
        cluster_name = self.cfg.GetClusterName()
4525 6c0af70e Guido Trotter
        import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
4526 09acf207 Guido Trotter
                                                         src_node, src_images,
4527 6c0af70e Guido Trotter
                                                         cluster_name)
4528 781de953 Iustin Pop
        import_result.Raise()
4529 781de953 Iustin Pop
        for idx, result in enumerate(import_result.data):
4530 09acf207 Guido Trotter
          if not result:
4531 726d7d68 Iustin Pop
            self.LogWarning("Could not import the image %s for instance"
4532 726d7d68 Iustin Pop
                            " %s, disk %d, on node %s" %
4533 726d7d68 Iustin Pop
                            (src_images[idx], instance, idx, pnode_name))
4534 a8083063 Iustin Pop
      else:
4535 a8083063 Iustin Pop
        # also checked in the prereq part
4536 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
4537 3ecf6786 Iustin Pop
                                     % self.op.mode)
4538 a8083063 Iustin Pop
4539 a8083063 Iustin Pop
    if self.op.start:
4540 9a4f63d1 Iustin Pop
      logging.info("Starting instance %s on node %s", instance, pnode_name)
4541 a8083063 Iustin Pop
      feedback_fn("* starting instance...")
4542 781de953 Iustin Pop
      result = self.rpc.call_instance_start(pnode_name, iobj, None)
4543 dd279568 Iustin Pop
      msg = result.RemoteFailMsg()
4544 dd279568 Iustin Pop
      if msg:
4545 dd279568 Iustin Pop
        raise errors.OpExecError("Could not start instance: %s" % msg)
4546 a8083063 Iustin Pop
4547 a8083063 Iustin Pop
4548 a8083063 Iustin Pop
class LUConnectConsole(NoHooksLU):
4549 a8083063 Iustin Pop
  """Connect to an instance's console.
4550 a8083063 Iustin Pop

4551 a8083063 Iustin Pop
  This is somewhat special in that it returns the command line that
4552 a8083063 Iustin Pop
  you need to run on the master node in order to connect to the
4553 a8083063 Iustin Pop
  console.
4554 a8083063 Iustin Pop

4555 a8083063 Iustin Pop
  """
4556 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
4557 8659b73e Guido Trotter
  REQ_BGL = False
4558 8659b73e Guido Trotter
4559 8659b73e Guido Trotter
  def ExpandNames(self):
4560 8659b73e Guido Trotter
    self._ExpandAndLockInstance()
4561 a8083063 Iustin Pop
4562 a8083063 Iustin Pop
  def CheckPrereq(self):
4563 a8083063 Iustin Pop
    """Check prerequisites.
4564 a8083063 Iustin Pop

4565 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
4566 a8083063 Iustin Pop

4567 a8083063 Iustin Pop
    """
4568 8659b73e Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4569 8659b73e Guido Trotter
    assert self.instance is not None, \
4570 8659b73e Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4571 513e896d Guido Trotter
    _CheckNodeOnline(self, self.instance.primary_node)
4572 a8083063 Iustin Pop
4573 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4574 a8083063 Iustin Pop
    """Connect to the console of an instance
4575 a8083063 Iustin Pop

4576 a8083063 Iustin Pop
    """
4577 a8083063 Iustin Pop
    instance = self.instance
4578 a8083063 Iustin Pop
    node = instance.primary_node
4579 a8083063 Iustin Pop
4580 72737a7f Iustin Pop
    node_insts = self.rpc.call_instance_list([node],
4581 72737a7f Iustin Pop
                                             [instance.hypervisor])[node]
4582 781de953 Iustin Pop
    node_insts.Raise()
4583 a8083063 Iustin Pop
4584 781de953 Iustin Pop
    if instance.name not in node_insts.data:
4585 3ecf6786 Iustin Pop
      raise errors.OpExecError("Instance %s is not running." % instance.name)
4586 a8083063 Iustin Pop
4587 9a4f63d1 Iustin Pop
    logging.debug("Connecting to console of %s on %s", instance.name, node)
4588 a8083063 Iustin Pop
4589 e69d05fd Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
4590 30989e69 Alexander Schreiber
    console_cmd = hyper.GetShellCommandForConsole(instance)
4591 b047857b Michael Hanselmann
4592 82122173 Iustin Pop
    # build ssh cmdline
4593 0a80a26f Michael Hanselmann
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
4594 a8083063 Iustin Pop
4595 a8083063 Iustin Pop
4596 a8083063 Iustin Pop
class LUReplaceDisks(LogicalUnit):
4597 a8083063 Iustin Pop
  """Replace the disks of an instance.
4598 a8083063 Iustin Pop

4599 a8083063 Iustin Pop
  """
4600 a8083063 Iustin Pop
  HPATH = "mirrors-replace"
4601 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4602 a9e0c397 Iustin Pop
  _OP_REQP = ["instance_name", "mode", "disks"]
4603 efd990e4 Guido Trotter
  REQ_BGL = False
4604 efd990e4 Guido Trotter
4605 7e9366f7 Iustin Pop
  def CheckArguments(self):
4606 efd990e4 Guido Trotter
    if not hasattr(self.op, "remote_node"):
4607 efd990e4 Guido Trotter
      self.op.remote_node = None
4608 7e9366f7 Iustin Pop
    if not hasattr(self.op, "iallocator"):
4609 7e9366f7 Iustin Pop
      self.op.iallocator = None
4610 7e9366f7 Iustin Pop
4611 7e9366f7 Iustin Pop
    # check for valid parameter combination
4612 7e9366f7 Iustin Pop
    cnt = [self.op.remote_node, self.op.iallocator].count(None)
4613 7e9366f7 Iustin Pop
    if self.op.mode == constants.REPLACE_DISK_CHG:
4614 7e9366f7 Iustin Pop
      if cnt == 2:
4615 7e9366f7 Iustin Pop
        raise errors.OpPrereqError("When changing the secondary either an"
4616 7e9366f7 Iustin Pop
                                   " iallocator script must be used or the"
4617 7e9366f7 Iustin Pop
                                   " new node given")
4618 7e9366f7 Iustin Pop
      elif cnt == 0:
4619 efd990e4 Guido Trotter
        raise errors.OpPrereqError("Give either the iallocator or the new"
4620 efd990e4 Guido Trotter
                                   " secondary, not both")
4621 7e9366f7 Iustin Pop
    else: # not replacing the secondary
4622 7e9366f7 Iustin Pop
      if cnt != 2:
4623 7e9366f7 Iustin Pop
        raise errors.OpPrereqError("The iallocator and new node options can"
4624 7e9366f7 Iustin Pop
                                   " be used only when changing the"
4625 7e9366f7 Iustin Pop
                                   " secondary node")
4626 7e9366f7 Iustin Pop
4627 7e9366f7 Iustin Pop
  def ExpandNames(self):
4628 7e9366f7 Iustin Pop
    self._ExpandAndLockInstance()
4629 7e9366f7 Iustin Pop
4630 7e9366f7 Iustin Pop
    if self.op.iallocator is not None:
4631 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4632 efd990e4 Guido Trotter
    elif self.op.remote_node is not None:
4633 efd990e4 Guido Trotter
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
4634 efd990e4 Guido Trotter
      if remote_node is None:
4635 efd990e4 Guido Trotter
        raise errors.OpPrereqError("Node '%s' not known" %
4636 efd990e4 Guido Trotter
                                   self.op.remote_node)
4637 efd990e4 Guido Trotter
      self.op.remote_node = remote_node
4638 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
4639 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
4640 efd990e4 Guido Trotter
    else:
4641 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = []
4642 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4643 efd990e4 Guido Trotter
4644 efd990e4 Guido Trotter
  def DeclareLocks(self, level):
4645 efd990e4 Guido Trotter
    # If we're not already locking all nodes in the set we have to declare the
4646 efd990e4 Guido Trotter
    # instance's primary/secondary nodes.
4647 efd990e4 Guido Trotter
    if (level == locking.LEVEL_NODE and
4648 efd990e4 Guido Trotter
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
4649 efd990e4 Guido Trotter
      self._LockInstancesNodes()
4650 a8083063 Iustin Pop
4651 b6e82a65 Iustin Pop
  def _RunAllocator(self):
4652 b6e82a65 Iustin Pop
    """Compute a new secondary node using an IAllocator.
4653 b6e82a65 Iustin Pop

4654 b6e82a65 Iustin Pop
    """
4655 72737a7f Iustin Pop
    ial = IAllocator(self,
4656 b6e82a65 Iustin Pop
                     mode=constants.IALLOCATOR_MODE_RELOC,
4657 b6e82a65 Iustin Pop
                     name=self.op.instance_name,
4658 b6e82a65 Iustin Pop
                     relocate_from=[self.sec_node])
4659 b6e82a65 Iustin Pop
4660 b6e82a65 Iustin Pop
    ial.Run(self.op.iallocator)
4661 b6e82a65 Iustin Pop
4662 b6e82a65 Iustin Pop
    if not ial.success:
4663 b6e82a65 Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
4664 b6e82a65 Iustin Pop
                                 " iallocator '%s': %s" % (self.op.iallocator,
4665 b6e82a65 Iustin Pop
                                                           ial.info))
4666 b6e82a65 Iustin Pop
    if len(ial.nodes) != ial.required_nodes:
4667 b6e82a65 Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
4668 b6e82a65 Iustin Pop
                                 " of nodes (%s), required %s" %
4669 b6e82a65 Iustin Pop
                                 (len(ial.nodes), ial.required_nodes))
4670 b6e82a65 Iustin Pop
    self.op.remote_node = ial.nodes[0]
4671 86d9d3bb Iustin Pop
    self.LogInfo("Selected new secondary for the instance: %s",
4672 86d9d3bb Iustin Pop
                 self.op.remote_node)
4673 b6e82a65 Iustin Pop
4674 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4675 a8083063 Iustin Pop
    """Build hooks env.
4676 a8083063 Iustin Pop

4677 a8083063 Iustin Pop
    This runs on the master, the primary and all the secondaries.
4678 a8083063 Iustin Pop

4679 a8083063 Iustin Pop
    """
4680 a8083063 Iustin Pop
    env = {
4681 a9e0c397 Iustin Pop
      "MODE": self.op.mode,
4682 a8083063 Iustin Pop
      "NEW_SECONDARY": self.op.remote_node,
4683 a8083063 Iustin Pop
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
4684 a8083063 Iustin Pop
      }
4685 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4686 0834c866 Iustin Pop
    nl = [
4687 d6a02168 Michael Hanselmann
      self.cfg.GetMasterNode(),
4688 0834c866 Iustin Pop
      self.instance.primary_node,
4689 0834c866 Iustin Pop
      ]
4690 0834c866 Iustin Pop
    if self.op.remote_node is not None:
4691 0834c866 Iustin Pop
      nl.append(self.op.remote_node)
4692 a8083063 Iustin Pop
    return env, nl, nl
4693 a8083063 Iustin Pop
4694 a8083063 Iustin Pop
  def CheckPrereq(self):
4695 a8083063 Iustin Pop
    """Check prerequisites.
4696 a8083063 Iustin Pop

4697 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
4698 a8083063 Iustin Pop

4699 a8083063 Iustin Pop
    """
4700 efd990e4 Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4701 efd990e4 Guido Trotter
    assert instance is not None, \
4702 efd990e4 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4703 a8083063 Iustin Pop
    self.instance = instance
4704 a8083063 Iustin Pop
4705 7e9366f7 Iustin Pop
    if instance.disk_template != constants.DT_DRBD8:
4706 7e9366f7 Iustin Pop
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
4707 7e9366f7 Iustin Pop
                                 " instances")
4708 a8083063 Iustin Pop
4709 a8083063 Iustin Pop
    if len(instance.secondary_nodes) != 1:
4710 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The instance has a strange layout,"
4711 3ecf6786 Iustin Pop
                                 " expected one secondary but found %d" %
4712 3ecf6786 Iustin Pop
                                 len(instance.secondary_nodes))
4713 a8083063 Iustin Pop
4714 a9e0c397 Iustin Pop
    self.sec_node = instance.secondary_nodes[0]
4715 a9e0c397 Iustin Pop
4716 7e9366f7 Iustin Pop
    if self.op.iallocator is not None:
4717 de8c7666 Guido Trotter
      self._RunAllocator()
4718 b6e82a65 Iustin Pop
4719 b6e82a65 Iustin Pop
    remote_node = self.op.remote_node
4720 a9e0c397 Iustin Pop
    if remote_node is not None:
4721 a9e0c397 Iustin Pop
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
4722 efd990e4 Guido Trotter
      assert self.remote_node_info is not None, \
4723 efd990e4 Guido Trotter
        "Cannot retrieve locked node %s" % remote_node
4724 a9e0c397 Iustin Pop
    else:
4725 a9e0c397 Iustin Pop
      self.remote_node_info = None
4726 a8083063 Iustin Pop
    if remote_node == instance.primary_node:
4727 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The specified node is the primary node of"
4728 3ecf6786 Iustin Pop
                                 " the instance.")
4729 a9e0c397 Iustin Pop
    elif remote_node == self.sec_node:
4730 7e9366f7 Iustin Pop
      raise errors.OpPrereqError("The specified node is already the"
4731 7e9366f7 Iustin Pop
                                 " secondary node of the instance.")
4732 7e9366f7 Iustin Pop
4733 7e9366f7 Iustin Pop
    if self.op.mode == constants.REPLACE_DISK_PRI:
4734 7e9366f7 Iustin Pop
      n1 = self.tgt_node = instance.primary_node
4735 7e9366f7 Iustin Pop
      n2 = self.oth_node = self.sec_node
4736 7e9366f7 Iustin Pop
    elif self.op.mode == constants.REPLACE_DISK_SEC:
4737 7e9366f7 Iustin Pop
      n1 = self.tgt_node = self.sec_node
4738 7e9366f7 Iustin Pop
      n2 = self.oth_node = instance.primary_node
4739 7e9366f7 Iustin Pop
    elif self.op.mode == constants.REPLACE_DISK_CHG:
4740 7e9366f7 Iustin Pop
      n1 = self.new_node = remote_node
4741 7e9366f7 Iustin Pop
      n2 = self.oth_node = instance.primary_node
4742 7e9366f7 Iustin Pop
      self.tgt_node = self.sec_node
4743 7e9366f7 Iustin Pop
    else:
4744 7e9366f7 Iustin Pop
      raise errors.ProgrammerError("Unhandled disk replace mode")
4745 7e9366f7 Iustin Pop
4746 7e9366f7 Iustin Pop
    _CheckNodeOnline(self, n1)
4747 7e9366f7 Iustin Pop
    _CheckNodeOnline(self, n2)
4748 a9e0c397 Iustin Pop
4749 54155f52 Iustin Pop
    if not self.op.disks:
4750 54155f52 Iustin Pop
      self.op.disks = range(len(instance.disks))
4751 54155f52 Iustin Pop
4752 54155f52 Iustin Pop
    for disk_idx in self.op.disks:
4753 3e0cea06 Iustin Pop
      instance.FindDisk(disk_idx)
4754 a8083063 Iustin Pop
4755 a9e0c397 Iustin Pop
  def _ExecD8DiskOnly(self, feedback_fn):
4756 a9e0c397 Iustin Pop
    """Replace a disk on the primary or secondary for dbrd8.
4757 a9e0c397 Iustin Pop

4758 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
4759 e4376078 Iustin Pop

4760 e4376078 Iustin Pop
      1. for each disk to be replaced:
4761 e4376078 Iustin Pop

4762 e4376078 Iustin Pop
        1. create new LVs on the target node with unique names
4763 e4376078 Iustin Pop
        1. detach old LVs from the drbd device
4764 e4376078 Iustin Pop
        1. rename old LVs to name_replaced.<time_t>
4765 e4376078 Iustin Pop
        1. rename new LVs to old LVs
4766 e4376078 Iustin Pop
        1. attach the new LVs (with the old names now) to the drbd device
4767 e4376078 Iustin Pop

4768 e4376078 Iustin Pop
      1. wait for sync across all devices
4769 e4376078 Iustin Pop

4770 e4376078 Iustin Pop
      1. for each modified disk:
4771 e4376078 Iustin Pop

4772 e4376078 Iustin Pop
        1. remove old LVs (which have the name name_replaces.<time_t>)
4773 a9e0c397 Iustin Pop

4774 a9e0c397 Iustin Pop
    Failures are not very well handled.
4775 cff90b79 Iustin Pop

4776 a9e0c397 Iustin Pop
    """
4777 cff90b79 Iustin Pop
    steps_total = 6
4778 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4779 a9e0c397 Iustin Pop
    instance = self.instance
4780 a9e0c397 Iustin Pop
    iv_names = {}
4781 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
4782 a9e0c397 Iustin Pop
    # start of work
4783 a9e0c397 Iustin Pop
    cfg = self.cfg
4784 a9e0c397 Iustin Pop
    tgt_node = self.tgt_node
4785 cff90b79 Iustin Pop
    oth_node = self.oth_node
4786 cff90b79 Iustin Pop
4787 cff90b79 Iustin Pop
    # Step: check device activation
4788 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
4789 cff90b79 Iustin Pop
    info("checking volume groups")
4790 cff90b79 Iustin Pop
    my_vg = cfg.GetVGName()
4791 72737a7f Iustin Pop
    results = self.rpc.call_vg_list([oth_node, tgt_node])
4792 cff90b79 Iustin Pop
    if not results:
4793 cff90b79 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
4794 cff90b79 Iustin Pop
    for node in oth_node, tgt_node:
4795 781de953 Iustin Pop
      res = results[node]
4796 781de953 Iustin Pop
      if res.failed or not res.data or my_vg not in res.data:
4797 cff90b79 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4798 cff90b79 Iustin Pop
                                 (my_vg, node))
4799 54155f52 Iustin Pop
    for idx, dev in enumerate(instance.disks):
4800 54155f52 Iustin Pop
      if idx not in self.op.disks:
4801 cff90b79 Iustin Pop
        continue
4802 cff90b79 Iustin Pop
      for node in tgt_node, oth_node:
4803 54155f52 Iustin Pop
        info("checking disk/%d on %s" % (idx, node))
4804 cff90b79 Iustin Pop
        cfg.SetDiskID(dev, node)
4805 72737a7f Iustin Pop
        if not self.rpc.call_blockdev_find(node, dev):
4806 54155f52 Iustin Pop
          raise errors.OpExecError("Can't find disk/%d on node %s" %
4807 54155f52 Iustin Pop
                                   (idx, node))
4808 cff90b79 Iustin Pop
4809 cff90b79 Iustin Pop
    # Step: check other node consistency
4810 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
4811 54155f52 Iustin Pop
    for idx, dev in enumerate(instance.disks):
4812 54155f52 Iustin Pop
      if idx not in self.op.disks:
4813 cff90b79 Iustin Pop
        continue
4814 54155f52 Iustin Pop
      info("checking disk/%d consistency on %s" % (idx, oth_node))
4815 b9bddb6b Iustin Pop
      if not _CheckDiskConsistency(self, dev, oth_node,
4816 cff90b79 Iustin Pop
                                   oth_node==instance.primary_node):
4817 cff90b79 Iustin Pop
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
4818 cff90b79 Iustin Pop
                                 " to replace disks on this node (%s)" %
4819 cff90b79 Iustin Pop
                                 (oth_node, tgt_node))
4820 cff90b79 Iustin Pop
4821 cff90b79 Iustin Pop
    # Step: create new storage
4822 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
4823 54155f52 Iustin Pop
    for idx, dev in enumerate(instance.disks):
4824 54155f52 Iustin Pop
      if idx not in self.op.disks:
4825 a9e0c397 Iustin Pop
        continue
4826 a9e0c397 Iustin Pop
      size = dev.size
4827 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, tgt_node)
4828 54155f52 Iustin Pop
      lv_names = [".disk%d_%s" % (idx, suf)
4829 54155f52 Iustin Pop
                  for suf in ["data", "meta"]]
4830 b9bddb6b Iustin Pop
      names = _GenerateUniqueNames(self, lv_names)
4831 a9e0c397 Iustin Pop
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
4832 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[0]))
4833 a9e0c397 Iustin Pop
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
4834 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[1]))
4835 a9e0c397 Iustin Pop
      new_lvs = [lv_data, lv_meta]
4836 a9e0c397 Iustin Pop
      old_lvs = dev.children
4837 a9e0c397 Iustin Pop
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
4838 cff90b79 Iustin Pop
      info("creating new local storage on %s for %s" %
4839 cff90b79 Iustin Pop
           (tgt_node, dev.iv_name))
4840 428958aa Iustin Pop
      # we pass force_create=True to force the LVM creation
4841 a9e0c397 Iustin Pop
      for new_lv in new_lvs:
4842 428958aa Iustin Pop
        _CreateBlockDev(self, tgt_node, instance, new_lv, True,
4843 428958aa Iustin Pop
                        _GetInstanceInfoText(instance), False)
4844 a9e0c397 Iustin Pop
4845 cff90b79 Iustin Pop
    # Step: for each lv, detach+rename*2+attach
4846 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "change drbd configuration")
4847 cff90b79 Iustin Pop
    for dev, old_lvs, new_lvs in iv_names.itervalues():
4848 cff90b79 Iustin Pop
      info("detaching %s drbd from local storage" % dev.iv_name)
4849 781de953 Iustin Pop
      result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
4850 781de953 Iustin Pop
      result.Raise()
4851 781de953 Iustin Pop
      if not result.data:
4852 a9e0c397 Iustin Pop
        raise errors.OpExecError("Can't detach drbd from local storage on node"
4853 a9e0c397 Iustin Pop
                                 " %s for device %s" % (tgt_node, dev.iv_name))
4854 cff90b79 Iustin Pop
      #dev.children = []
4855 cff90b79 Iustin Pop
      #cfg.Update(instance)
4856 a9e0c397 Iustin Pop
4857 a9e0c397 Iustin Pop
      # ok, we created the new LVs, so now we know we have the needed
4858 a9e0c397 Iustin Pop
      # storage; as such, we proceed on the target node to rename
4859 a9e0c397 Iustin Pop
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
4860 c99a3cc0 Manuel Franceschini
      # using the assumption that logical_id == physical_id (which in
4861 a9e0c397 Iustin Pop
      # turn is the unique_id on that node)
4862 cff90b79 Iustin Pop
4863 cff90b79 Iustin Pop
      # FIXME(iustin): use a better name for the replaced LVs
4864 a9e0c397 Iustin Pop
      temp_suffix = int(time.time())
4865 a9e0c397 Iustin Pop
      ren_fn = lambda d, suff: (d.physical_id[0],
4866 a9e0c397 Iustin Pop
                                d.physical_id[1] + "_replaced-%s" % suff)
4867 cff90b79 Iustin Pop
      # build the rename list based on what LVs exist on the node
4868 cff90b79 Iustin Pop
      rlist = []
4869 cff90b79 Iustin Pop
      for to_ren in old_lvs:
4870 72737a7f Iustin Pop
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
4871 781de953 Iustin Pop
        if not find_res.failed and find_res.data is not None: # device exists
4872 cff90b79 Iustin Pop
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
4873 cff90b79 Iustin Pop
4874 cff90b79 Iustin Pop
      info("renaming the old LVs on the target node")
4875 781de953 Iustin Pop
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4876 781de953 Iustin Pop
      result.Raise()
4877 781de953 Iustin Pop
      if not result.data:
4878 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
4879 a9e0c397 Iustin Pop
      # now we rename the new LVs to the old LVs
4880 cff90b79 Iustin Pop
      info("renaming the new LVs on the target node")
4881 a9e0c397 Iustin Pop
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
4882 781de953 Iustin Pop
      result = self.rpc.call_blockdev_rename(tgt_node, rlist)
4883 781de953 Iustin Pop
      result.Raise()
4884 781de953 Iustin Pop
      if not result.data:
4885 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
4886 cff90b79 Iustin Pop
4887 cff90b79 Iustin Pop
      for old, new in zip(old_lvs, new_lvs):
4888 cff90b79 Iustin Pop
        new.logical_id = old.logical_id
4889 cff90b79 Iustin Pop
        cfg.SetDiskID(new, tgt_node)
4890 a9e0c397 Iustin Pop
4891 cff90b79 Iustin Pop
      for disk in old_lvs:
4892 cff90b79 Iustin Pop
        disk.logical_id = ren_fn(disk, temp_suffix)
4893 cff90b79 Iustin Pop
        cfg.SetDiskID(disk, tgt_node)
4894 a9e0c397 Iustin Pop
4895 a9e0c397 Iustin Pop
      # now that the new lvs have the old name, we can add them to the device
4896 cff90b79 Iustin Pop
      info("adding new mirror component on %s" % tgt_node)
4897 4504c3d6 Iustin Pop
      result = self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
4898 781de953 Iustin Pop
      if result.failed or not result.data:
4899 a9e0c397 Iustin Pop
        for new_lv in new_lvs:
4900 781de953 Iustin Pop
          result = self.rpc.call_blockdev_remove(tgt_node, new_lv)
4901 781de953 Iustin Pop
          if result.failed or not result.data:
4902 79caa9ed Guido Trotter
            warning("Can't rollback device %s", hint="manually cleanup unused"
4903 cff90b79 Iustin Pop
                    " logical volumes")
4904 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't add local storage to drbd")
4905 a9e0c397 Iustin Pop
4906 a9e0c397 Iustin Pop
      dev.children = new_lvs
4907 a9e0c397 Iustin Pop
      cfg.Update(instance)
4908 a9e0c397 Iustin Pop
4909 cff90b79 Iustin Pop
    # Step: wait for sync
4910 a9e0c397 Iustin Pop
4911 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
4912 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
4913 a9e0c397 Iustin Pop
    # return value
4914 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
4915 b9bddb6b Iustin Pop
    _WaitForSync(self, instance, unlock=True)
4916 a9e0c397 Iustin Pop
4917 a9e0c397 Iustin Pop
    # so check manually all the devices
4918 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4919 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, instance.primary_node)
4920 781de953 Iustin Pop
      result = self.rpc.call_blockdev_find(instance.primary_node, dev)
4921 781de953 Iustin Pop
      if result.failed or result.data[5]:
4922 a9e0c397 Iustin Pop
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4923 a9e0c397 Iustin Pop
4924 cff90b79 Iustin Pop
    # Step: remove old storage
4925 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
4926 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4927 cff90b79 Iustin Pop
      info("remove logical volumes for %s" % name)
4928 a9e0c397 Iustin Pop
      for lv in old_lvs:
4929 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, tgt_node)
4930 781de953 Iustin Pop
        result = self.rpc.call_blockdev_remove(tgt_node, lv)
4931 781de953 Iustin Pop
        if result.failed or not result.data:
4932 79caa9ed Guido Trotter
          warning("Can't remove old LV", hint="manually remove unused LVs")
4933 a9e0c397 Iustin Pop
          continue
4934 a9e0c397 Iustin Pop
4935 a9e0c397 Iustin Pop
  def _ExecD8Secondary(self, feedback_fn):
4936 a9e0c397 Iustin Pop
    """Replace the secondary node for drbd8.
4937 a9e0c397 Iustin Pop

4938 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
4939 a9e0c397 Iustin Pop
      - for all disks of the instance:
4940 a9e0c397 Iustin Pop
        - create new LVs on the new node with same names
4941 a9e0c397 Iustin Pop
        - shutdown the drbd device on the old secondary
4942 a9e0c397 Iustin Pop
        - disconnect the drbd network on the primary
4943 a9e0c397 Iustin Pop
        - create the drbd device on the new secondary
4944 a9e0c397 Iustin Pop
        - network attach the drbd on the primary, using an artifice:
4945 a9e0c397 Iustin Pop
          the drbd code for Attach() will connect to the network if it
4946 a9e0c397 Iustin Pop
          finds a device which is connected to the good local disks but
4947 a9e0c397 Iustin Pop
          not network enabled
4948 a9e0c397 Iustin Pop
      - wait for sync across all devices
4949 a9e0c397 Iustin Pop
      - remove all disks from the old secondary
4950 a9e0c397 Iustin Pop

4951 a9e0c397 Iustin Pop
    Failures are not very well handled.
4952 0834c866 Iustin Pop

4953 a9e0c397 Iustin Pop
    """
4954 0834c866 Iustin Pop
    steps_total = 6
4955 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4956 a9e0c397 Iustin Pop
    instance = self.instance
4957 a9e0c397 Iustin Pop
    iv_names = {}
4958 a9e0c397 Iustin Pop
    # start of work
4959 a9e0c397 Iustin Pop
    cfg = self.cfg
4960 a9e0c397 Iustin Pop
    old_node = self.tgt_node
4961 a9e0c397 Iustin Pop
    new_node = self.new_node
4962 a9e0c397 Iustin Pop
    pri_node = instance.primary_node
4963 a2d59d8b Iustin Pop
    nodes_ip = {
4964 a2d59d8b Iustin Pop
      old_node: self.cfg.GetNodeInfo(old_node).secondary_ip,
4965 a2d59d8b Iustin Pop
      new_node: self.cfg.GetNodeInfo(new_node).secondary_ip,
4966 a2d59d8b Iustin Pop
      pri_node: self.cfg.GetNodeInfo(pri_node).secondary_ip,
4967 a2d59d8b Iustin Pop
      }
4968 0834c866 Iustin Pop
4969 0834c866 Iustin Pop
    # Step: check device activation
4970 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
4971 0834c866 Iustin Pop
    info("checking volume groups")
4972 0834c866 Iustin Pop
    my_vg = cfg.GetVGName()
4973 72737a7f Iustin Pop
    results = self.rpc.call_vg_list([pri_node, new_node])
4974 0834c866 Iustin Pop
    for node in pri_node, new_node:
4975 781de953 Iustin Pop
      res = results[node]
4976 781de953 Iustin Pop
      if res.failed or not res.data or my_vg not in res.data:
4977 0834c866 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4978 0834c866 Iustin Pop
                                 (my_vg, node))
4979 d418ebfb Iustin Pop
    for idx, dev in enumerate(instance.disks):
4980 d418ebfb Iustin Pop
      if idx not in self.op.disks:
4981 0834c866 Iustin Pop
        continue
4982 d418ebfb Iustin Pop
      info("checking disk/%d on %s" % (idx, pri_node))
4983 0834c866 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4984 781de953 Iustin Pop
      result = self.rpc.call_blockdev_find(pri_node, dev)
4985 781de953 Iustin Pop
      result.Raise()
4986 781de953 Iustin Pop
      if not result.data:
4987 d418ebfb Iustin Pop
        raise errors.OpExecError("Can't find disk/%d on node %s" %
4988 d418ebfb Iustin Pop
                                 (idx, pri_node))
4989 0834c866 Iustin Pop
4990 0834c866 Iustin Pop
    # Step: check other node consistency
4991 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
4992 d418ebfb Iustin Pop
    for idx, dev in enumerate(instance.disks):
4993 d418ebfb Iustin Pop
      if idx not in self.op.disks:
4994 0834c866 Iustin Pop
        continue
4995 d418ebfb Iustin Pop
      info("checking disk/%d consistency on %s" % (idx, pri_node))
4996 b9bddb6b Iustin Pop
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
4997 0834c866 Iustin Pop
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4998 0834c866 Iustin Pop
                                 " unsafe to replace the secondary" %
4999 0834c866 Iustin Pop
                                 pri_node)
5000 0834c866 Iustin Pop
5001 0834c866 Iustin Pop
    # Step: create new storage
5002 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
5003 d418ebfb Iustin Pop
    for idx, dev in enumerate(instance.disks):
5004 d418ebfb Iustin Pop
      info("adding new local storage on %s for disk/%d" %
5005 d418ebfb Iustin Pop
           (new_node, idx))
5006 428958aa Iustin Pop
      # we pass force_create=True to force LVM creation
5007 a9e0c397 Iustin Pop
      for new_lv in dev.children:
5008 428958aa Iustin Pop
        _CreateBlockDev(self, new_node, instance, new_lv, True,
5009 428958aa Iustin Pop
                        _GetInstanceInfoText(instance), False)
5010 a9e0c397 Iustin Pop
5011 468b46f9 Iustin Pop
    # Step 4: dbrd minors and drbd setups changes
5012 a1578d63 Iustin Pop
    # after this, we must manually remove the drbd minors on both the
5013 a1578d63 Iustin Pop
    # error and the success paths
5014 a1578d63 Iustin Pop
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
5015 a1578d63 Iustin Pop
                                   instance.name)
5016 468b46f9 Iustin Pop
    logging.debug("Allocated minors %s" % (minors,))
5017 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
5018 d418ebfb Iustin Pop
    for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)):
5019 0834c866 Iustin Pop
      size = dev.size
5020 d418ebfb Iustin Pop
      info("activating a new drbd on %s for disk/%d" % (new_node, idx))
5021 a2d59d8b Iustin Pop
      # create new devices on new_node; note that we create two IDs:
5022 a2d59d8b Iustin Pop
      # one without port, so the drbd will be activated without
5023 a2d59d8b Iustin Pop
      # networking information on the new node at this stage, and one
5024 a2d59d8b Iustin Pop
      # with network, for the latter activation in step 4
5025 a2d59d8b Iustin Pop
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
5026 a2d59d8b Iustin Pop
      if pri_node == o_node1:
5027 a2d59d8b Iustin Pop
        p_minor = o_minor1
5028 ffa1c0dc Iustin Pop
      else:
5029 a2d59d8b Iustin Pop
        p_minor = o_minor2
5030 a2d59d8b Iustin Pop
5031 a2d59d8b Iustin Pop
      new_alone_id = (pri_node, new_node, None, p_minor, new_minor, o_secret)
5032 a2d59d8b Iustin Pop
      new_net_id = (pri_node, new_node, o_port, p_minor, new_minor, o_secret)
5033 a2d59d8b Iustin Pop
5034 a2d59d8b Iustin Pop
      iv_names[idx] = (dev, dev.children, new_net_id)
5035 a1578d63 Iustin Pop
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
5036 a2d59d8b Iustin Pop
                    new_net_id)
5037 a9e0c397 Iustin Pop
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
5038 a2d59d8b Iustin Pop
                              logical_id=new_alone_id,
5039 a9e0c397 Iustin Pop
                              children=dev.children)
5040 796cab27 Iustin Pop
      try:
5041 de12473a Iustin Pop
        _CreateSingleBlockDev(self, new_node, instance, new_drbd,
5042 de12473a Iustin Pop
                              _GetInstanceInfoText(instance), False)
5043 1492cca7 Iustin Pop
      except errors.BlockDeviceError:
5044 a1578d63 Iustin Pop
        self.cfg.ReleaseDRBDMinors(instance.name)
5045 796cab27 Iustin Pop
        raise
5046 a9e0c397 Iustin Pop
5047 d418ebfb Iustin Pop
    for idx, dev in enumerate(instance.disks):
5048 a9e0c397 Iustin Pop
      # we have new devices, shutdown the drbd on the old secondary
5049 d418ebfb Iustin Pop
      info("shutting down drbd for disk/%d on old node" % idx)
5050 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, old_node)
5051 781de953 Iustin Pop
      result = self.rpc.call_blockdev_shutdown(old_node, dev)
5052 781de953 Iustin Pop
      if result.failed or not result.data:
5053 d418ebfb Iustin Pop
        warning("Failed to shutdown drbd for disk/%d on old node" % idx,
5054 79caa9ed Guido Trotter
                hint="Please cleanup this device manually as soon as possible")
5055 a9e0c397 Iustin Pop
5056 642445d9 Iustin Pop
    info("detaching primary drbds from the network (=> standalone)")
5057 a2d59d8b Iustin Pop
    result = self.rpc.call_drbd_disconnect_net([pri_node], nodes_ip,
5058 a2d59d8b Iustin Pop
                                               instance.disks)[pri_node]
5059 642445d9 Iustin Pop
5060 a2d59d8b Iustin Pop
    msg = result.RemoteFailMsg()
5061 a2d59d8b Iustin Pop
    if msg:
5062 a2d59d8b Iustin Pop
      # detaches didn't succeed (unlikely)
5063 a1578d63 Iustin Pop
      self.cfg.ReleaseDRBDMinors(instance.name)
5064 a2d59d8b Iustin Pop
      raise errors.OpExecError("Can't detach the disks from the network on"
5065 a2d59d8b Iustin Pop
                               " old node: %s" % (msg,))
5066 642445d9 Iustin Pop
5067 642445d9 Iustin Pop
    # if we managed to detach at least one, we update all the disks of
5068 642445d9 Iustin Pop
    # the instance to point to the new secondary
5069 642445d9 Iustin Pop
    info("updating instance configuration")
5070 468b46f9 Iustin Pop
    for dev, _, new_logical_id in iv_names.itervalues():
5071 468b46f9 Iustin Pop
      dev.logical_id = new_logical_id
5072 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
5073 642445d9 Iustin Pop
    cfg.Update(instance)
5074 a1578d63 Iustin Pop
    # we can remove now the temp minors as now the new values are
5075 a1578d63 Iustin Pop
    # written to the config file (and therefore stable)
5076 a1578d63 Iustin Pop
    self.cfg.ReleaseDRBDMinors(instance.name)
5077 a9e0c397 Iustin Pop
5078 642445d9 Iustin Pop
    # and now perform the drbd attach
5079 642445d9 Iustin Pop
    info("attaching primary drbds to new secondary (standalone => connected)")
5080 a2d59d8b Iustin Pop
    result = self.rpc.call_drbd_attach_net([pri_node, new_node], nodes_ip,
5081 a2d59d8b Iustin Pop
                                           instance.disks, instance.name,
5082 a2d59d8b Iustin Pop
                                           False)
5083 a2d59d8b Iustin Pop
    for to_node, to_result in result.items():
5084 a2d59d8b Iustin Pop
      msg = to_result.RemoteFailMsg()
5085 a2d59d8b Iustin Pop
      if msg:
5086 a2d59d8b Iustin Pop
        warning("can't attach drbd disks on node %s: %s", to_node, msg,
5087 a2d59d8b Iustin Pop
                hint="please do a gnt-instance info to see the"
5088 a2d59d8b Iustin Pop
                " status of disks")
5089 a9e0c397 Iustin Pop
5090 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
5091 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
5092 a9e0c397 Iustin Pop
    # return value
5093 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
5094 b9bddb6b Iustin Pop
    _WaitForSync(self, instance, unlock=True)
5095 a9e0c397 Iustin Pop
5096 a9e0c397 Iustin Pop
    # so check manually all the devices
5097 d418ebfb Iustin Pop
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5098 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
5099 781de953 Iustin Pop
      result = self.rpc.call_blockdev_find(pri_node, dev)
5100 781de953 Iustin Pop
      result.Raise()
5101 781de953 Iustin Pop
      if result.data[5]:
5102 d418ebfb Iustin Pop
        raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx)
5103 a9e0c397 Iustin Pop
5104 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
5105 d418ebfb Iustin Pop
    for idx, (dev, old_lvs, _) in iv_names.iteritems():
5106 d418ebfb Iustin Pop
      info("remove logical volumes for disk/%d" % idx)
5107 a9e0c397 Iustin Pop
      for lv in old_lvs:
5108 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, old_node)
5109 781de953 Iustin Pop
        result = self.rpc.call_blockdev_remove(old_node, lv)
5110 781de953 Iustin Pop
        if result.failed or not result.data:
5111 0834c866 Iustin Pop
          warning("Can't remove LV on old secondary",
5112 79caa9ed Guido Trotter
                  hint="Cleanup stale volumes by hand")
5113 a9e0c397 Iustin Pop
5114 a9e0c397 Iustin Pop
  def Exec(self, feedback_fn):
5115 a9e0c397 Iustin Pop
    """Execute disk replacement.
5116 a9e0c397 Iustin Pop

5117 a9e0c397 Iustin Pop
    This dispatches the disk replacement to the appropriate handler.
5118 a9e0c397 Iustin Pop

5119 a9e0c397 Iustin Pop
    """
5120 a9e0c397 Iustin Pop
    instance = self.instance
5121 22985314 Guido Trotter
5122 22985314 Guido Trotter
    # Activate the instance disks if we're replacing them on a down instance
5123 22985314 Guido Trotter
    if instance.status == "down":
5124 b9bddb6b Iustin Pop
      _StartInstanceDisks(self, instance, True)
5125 22985314 Guido Trotter
5126 7e9366f7 Iustin Pop
    if self.op.mode == constants.REPLACE_DISK_CHG:
5127 7e9366f7 Iustin Pop
      fn = self._ExecD8Secondary
5128 a9e0c397 Iustin Pop
    else:
5129 7e9366f7 Iustin Pop
      fn = self._ExecD8DiskOnly
5130 22985314 Guido Trotter
5131 22985314 Guido Trotter
    ret = fn(feedback_fn)
5132 22985314 Guido Trotter
5133 22985314 Guido Trotter
    # Deactivate the instance disks if we're replacing them on a down instance
5134 22985314 Guido Trotter
    if instance.status == "down":
5135 b9bddb6b Iustin Pop
      _SafeShutdownInstanceDisks(self, instance)
5136 22985314 Guido Trotter
5137 22985314 Guido Trotter
    return ret
5138 a9e0c397 Iustin Pop
5139 a8083063 Iustin Pop
5140 8729e0d7 Iustin Pop
class LUGrowDisk(LogicalUnit):
5141 8729e0d7 Iustin Pop
  """Grow a disk of an instance.
5142 8729e0d7 Iustin Pop

5143 8729e0d7 Iustin Pop
  """
5144 8729e0d7 Iustin Pop
  HPATH = "disk-grow"
5145 8729e0d7 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
5146 6605411d Iustin Pop
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
5147 31e63dbf Guido Trotter
  REQ_BGL = False
5148 31e63dbf Guido Trotter
5149 31e63dbf Guido Trotter
  def ExpandNames(self):
5150 31e63dbf Guido Trotter
    self._ExpandAndLockInstance()
5151 31e63dbf Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
5152 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5153 31e63dbf Guido Trotter
5154 31e63dbf Guido Trotter
  def DeclareLocks(self, level):
5155 31e63dbf Guido Trotter
    if level == locking.LEVEL_NODE:
5156 31e63dbf Guido Trotter
      self._LockInstancesNodes()
5157 8729e0d7 Iustin Pop
5158 8729e0d7 Iustin Pop
  def BuildHooksEnv(self):
5159 8729e0d7 Iustin Pop
    """Build hooks env.
5160 8729e0d7 Iustin Pop

5161 8729e0d7 Iustin Pop
    This runs on the master, the primary and all the secondaries.
5162 8729e0d7 Iustin Pop

5163 8729e0d7 Iustin Pop
    """
5164 8729e0d7 Iustin Pop
    env = {
5165 8729e0d7 Iustin Pop
      "DISK": self.op.disk,
5166 8729e0d7 Iustin Pop
      "AMOUNT": self.op.amount,
5167 8729e0d7 Iustin Pop
      }
5168 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5169 8729e0d7 Iustin Pop
    nl = [
5170 d6a02168 Michael Hanselmann
      self.cfg.GetMasterNode(),
5171 8729e0d7 Iustin Pop
      self.instance.primary_node,
5172 8729e0d7 Iustin Pop
      ]
5173 8729e0d7 Iustin Pop
    return env, nl, nl
5174 8729e0d7 Iustin Pop
5175 8729e0d7 Iustin Pop
  def CheckPrereq(self):
5176 8729e0d7 Iustin Pop
    """Check prerequisites.
5177 8729e0d7 Iustin Pop

5178 8729e0d7 Iustin Pop
    This checks that the instance is in the cluster.
5179 8729e0d7 Iustin Pop

5180 8729e0d7 Iustin Pop
    """
5181 31e63dbf Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5182 31e63dbf Guido Trotter
    assert instance is not None, \
5183 31e63dbf Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
5184 6b12959c Iustin Pop
    nodenames = list(instance.all_nodes)
5185 6b12959c Iustin Pop
    for node in nodenames:
5186 7527a8a4 Iustin Pop
      _CheckNodeOnline(self, node)
5187 7527a8a4 Iustin Pop
5188 31e63dbf Guido Trotter
5189 8729e0d7 Iustin Pop
    self.instance = instance
5190 8729e0d7 Iustin Pop
5191 8729e0d7 Iustin Pop
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
5192 8729e0d7 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout does not support"
5193 8729e0d7 Iustin Pop
                                 " growing.")
5194 8729e0d7 Iustin Pop
5195 ad24e046 Iustin Pop
    self.disk = instance.FindDisk(self.op.disk)
5196 8729e0d7 Iustin Pop
5197 72737a7f Iustin Pop
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
5198 72737a7f Iustin Pop
                                       instance.hypervisor)
5199 8729e0d7 Iustin Pop
    for node in nodenames:
5200 781de953 Iustin Pop
      info = nodeinfo[node]
5201 781de953 Iustin Pop
      if info.failed or not info.data:
5202 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Cannot get current information"
5203 8729e0d7 Iustin Pop
                                   " from node '%s'" % node)
5204 781de953 Iustin Pop
      vg_free = info.data.get('vg_free', None)
5205 8729e0d7 Iustin Pop
      if not isinstance(vg_free, int):
5206 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Can't compute free disk space on"
5207 8729e0d7 Iustin Pop
                                   " node %s" % node)
5208 781de953 Iustin Pop
      if self.op.amount > vg_free:
5209 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
5210 8729e0d7 Iustin Pop
                                   " %d MiB available, %d MiB required" %
5211 781de953 Iustin Pop
                                   (node, vg_free, self.op.amount))
5212 8729e0d7 Iustin Pop
5213 8729e0d7 Iustin Pop
  def Exec(self, feedback_fn):
5214 8729e0d7 Iustin Pop
    """Execute disk grow.
5215 8729e0d7 Iustin Pop

5216 8729e0d7 Iustin Pop
    """
5217 8729e0d7 Iustin Pop
    instance = self.instance
5218 ad24e046 Iustin Pop
    disk = self.disk
5219 6b12959c Iustin Pop
    for node in instance.all_nodes:
5220 8729e0d7 Iustin Pop
      self.cfg.SetDiskID(disk, node)
5221 72737a7f Iustin Pop
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
5222 781de953 Iustin Pop
      result.Raise()
5223 781de953 Iustin Pop
      if (not result.data or not isinstance(result.data, (list, tuple)) or
5224 781de953 Iustin Pop
          len(result.data) != 2):
5225 781de953 Iustin Pop
        raise errors.OpExecError("Grow request failed to node %s" % node)
5226 781de953 Iustin Pop
      elif not result.data[0]:
5227 781de953 Iustin Pop
        raise errors.OpExecError("Grow request failed to node %s: %s" %
5228 781de953 Iustin Pop
                                 (node, result.data[1]))
5229 8729e0d7 Iustin Pop
    disk.RecordGrow(self.op.amount)
5230 8729e0d7 Iustin Pop
    self.cfg.Update(instance)
5231 6605411d Iustin Pop
    if self.op.wait_for_sync:
5232 cd4d138f Guido Trotter
      disk_abort = not _WaitForSync(self, instance)
5233 6605411d Iustin Pop
      if disk_abort:
5234 86d9d3bb Iustin Pop
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
5235 86d9d3bb Iustin Pop
                             " status.\nPlease check the instance.")
5236 8729e0d7 Iustin Pop
5237 8729e0d7 Iustin Pop
5238 a8083063 Iustin Pop
class LUQueryInstanceData(NoHooksLU):
5239 a8083063 Iustin Pop
  """Query runtime instance data.
5240 a8083063 Iustin Pop

5241 a8083063 Iustin Pop
  """
5242 57821cac Iustin Pop
  _OP_REQP = ["instances", "static"]
5243 a987fa48 Guido Trotter
  REQ_BGL = False
5244 ae5849b5 Michael Hanselmann
5245 a987fa48 Guido Trotter
  def ExpandNames(self):
5246 a987fa48 Guido Trotter
    self.needed_locks = {}
5247 a987fa48 Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
5248 a987fa48 Guido Trotter
5249 a987fa48 Guido Trotter
    if not isinstance(self.op.instances, list):
5250 a987fa48 Guido Trotter
      raise errors.OpPrereqError("Invalid argument type 'instances'")
5251 a987fa48 Guido Trotter
5252 a987fa48 Guido Trotter
    if self.op.instances:
5253 a987fa48 Guido Trotter
      self.wanted_names = []
5254 a987fa48 Guido Trotter
      for name in self.op.instances:
5255 a987fa48 Guido Trotter
        full_name = self.cfg.ExpandInstanceName(name)
5256 a987fa48 Guido Trotter
        if full_name is None:
5257 f57c76e4 Iustin Pop
          raise errors.OpPrereqError("Instance '%s' not known" % name)
5258 a987fa48 Guido Trotter
        self.wanted_names.append(full_name)
5259 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
5260 a987fa48 Guido Trotter
    else:
5261 a987fa48 Guido Trotter
      self.wanted_names = None
5262 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5263 a987fa48 Guido Trotter
5264 a987fa48 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
5265 a987fa48 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5266 a987fa48 Guido Trotter
5267 a987fa48 Guido Trotter
  def DeclareLocks(self, level):
5268 a987fa48 Guido Trotter
    if level == locking.LEVEL_NODE:
5269 a987fa48 Guido Trotter
      self._LockInstancesNodes()
5270 a8083063 Iustin Pop
5271 a8083063 Iustin Pop
  def CheckPrereq(self):
5272 a8083063 Iustin Pop
    """Check prerequisites.
5273 a8083063 Iustin Pop

5274 a8083063 Iustin Pop
    This only checks the optional instance list against the existing names.
5275 a8083063 Iustin Pop

5276 a8083063 Iustin Pop
    """
5277 a987fa48 Guido Trotter
    if self.wanted_names is None:
5278 a987fa48 Guido Trotter
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5279 a8083063 Iustin Pop
5280 a987fa48 Guido Trotter
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
5281 a987fa48 Guido Trotter
                             in self.wanted_names]
5282 a987fa48 Guido Trotter
    return
5283 a8083063 Iustin Pop
5284 a8083063 Iustin Pop
  def _ComputeDiskStatus(self, instance, snode, dev):
5285 a8083063 Iustin Pop
    """Compute block device status.
5286 a8083063 Iustin Pop

5287 a8083063 Iustin Pop
    """
5288 57821cac Iustin Pop
    static = self.op.static
5289 57821cac Iustin Pop
    if not static:
5290 57821cac Iustin Pop
      self.cfg.SetDiskID(dev, instance.primary_node)
5291 57821cac Iustin Pop
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
5292 781de953 Iustin Pop
      dev_pstatus.Raise()
5293 781de953 Iustin Pop
      dev_pstatus = dev_pstatus.data
5294 57821cac Iustin Pop
    else:
5295 57821cac Iustin Pop
      dev_pstatus = None
5296 57821cac Iustin Pop
5297 a1f445d3 Iustin Pop
    if dev.dev_type in constants.LDS_DRBD:
5298 a8083063 Iustin Pop
      # we change the snode then (otherwise we use the one passed in)
5299 a8083063 Iustin Pop
      if dev.logical_id[0] == instance.primary_node:
5300 a8083063 Iustin Pop
        snode = dev.logical_id[1]
5301 a8083063 Iustin Pop
      else:
5302 a8083063 Iustin Pop
        snode = dev.logical_id[0]
5303 a8083063 Iustin Pop
5304 57821cac Iustin Pop
    if snode and not static:
5305 a8083063 Iustin Pop
      self.cfg.SetDiskID(dev, snode)
5306 72737a7f Iustin Pop
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
5307 781de953 Iustin Pop
      dev_sstatus.Raise()
5308 781de953 Iustin Pop
      dev_sstatus = dev_sstatus.data
5309 a8083063 Iustin Pop
    else:
5310 a8083063 Iustin Pop
      dev_sstatus = None
5311 a8083063 Iustin Pop
5312 a8083063 Iustin Pop
    if dev.children:
5313 a8083063 Iustin Pop
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
5314 a8083063 Iustin Pop
                      for child in dev.children]
5315 a8083063 Iustin Pop
    else:
5316 a8083063 Iustin Pop
      dev_children = []
5317 a8083063 Iustin Pop
5318 a8083063 Iustin Pop
    data = {
5319 a8083063 Iustin Pop
      "iv_name": dev.iv_name,
5320 a8083063 Iustin Pop
      "dev_type": dev.dev_type,
5321 a8083063 Iustin Pop
      "logical_id": dev.logical_id,
5322 a8083063 Iustin Pop
      "physical_id": dev.physical_id,
5323 a8083063 Iustin Pop
      "pstatus": dev_pstatus,
5324 a8083063 Iustin Pop
      "sstatus": dev_sstatus,
5325 a8083063 Iustin Pop
      "children": dev_children,
5326 b6fdf8b8 Iustin Pop
      "mode": dev.mode,
5327 a8083063 Iustin Pop
      }
5328 a8083063 Iustin Pop
5329 a8083063 Iustin Pop
    return data
5330 a8083063 Iustin Pop
5331 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
5332 a8083063 Iustin Pop
    """Gather and return data"""
5333 a8083063 Iustin Pop
    result = {}
5334 338e51e8 Iustin Pop
5335 338e51e8 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
5336 338e51e8 Iustin Pop
5337 a8083063 Iustin Pop
    for instance in self.wanted_instances:
5338 57821cac Iustin Pop
      if not self.op.static:
5339 57821cac Iustin Pop
        remote_info = self.rpc.call_instance_info(instance.primary_node,
5340 57821cac Iustin Pop
                                                  instance.name,
5341 57821cac Iustin Pop
                                                  instance.hypervisor)
5342 781de953 Iustin Pop
        remote_info.Raise()
5343 781de953 Iustin Pop
        remote_info = remote_info.data
5344 57821cac Iustin Pop
        if remote_info and "state" in remote_info:
5345 57821cac Iustin Pop
          remote_state = "up"
5346 57821cac Iustin Pop
        else:
5347 57821cac Iustin Pop
          remote_state = "down"
5348 a8083063 Iustin Pop
      else:
5349 57821cac Iustin Pop
        remote_state = None
5350 a8083063 Iustin Pop
      if instance.status == "down":
5351 a8083063 Iustin Pop
        config_state = "down"
5352 a8083063 Iustin Pop
      else:
5353 a8083063 Iustin Pop
        config_state = "up"
5354 a8083063 Iustin Pop
5355 a8083063 Iustin Pop
      disks = [self._ComputeDiskStatus(instance, None, device)
5356 a8083063 Iustin Pop
               for device in instance.disks]
5357 a8083063 Iustin Pop
5358 a8083063 Iustin Pop
      idict = {
5359 a8083063 Iustin Pop
        "name": instance.name,
5360 a8083063 Iustin Pop
        "config_state": config_state,
5361 a8083063 Iustin Pop
        "run_state": remote_state,
5362 a8083063 Iustin Pop
        "pnode": instance.primary_node,
5363 a8083063 Iustin Pop
        "snodes": instance.secondary_nodes,
5364 a8083063 Iustin Pop
        "os": instance.os,
5365 a8083063 Iustin Pop
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
5366 a8083063 Iustin Pop
        "disks": disks,
5367 e69d05fd Iustin Pop
        "hypervisor": instance.hypervisor,
5368 24838135 Iustin Pop
        "network_port": instance.network_port,
5369 24838135 Iustin Pop
        "hv_instance": instance.hvparams,
5370 338e51e8 Iustin Pop
        "hv_actual": cluster.FillHV(instance),
5371 338e51e8 Iustin Pop
        "be_instance": instance.beparams,
5372 338e51e8 Iustin Pop
        "be_actual": cluster.FillBE(instance),
5373 a8083063 Iustin Pop
        }
5374 a8083063 Iustin Pop
5375 a8083063 Iustin Pop
      result[instance.name] = idict
5376 a8083063 Iustin Pop
5377 a8083063 Iustin Pop
    return result
5378 a8083063 Iustin Pop
5379 a8083063 Iustin Pop
5380 7767bbf5 Manuel Franceschini
class LUSetInstanceParams(LogicalUnit):
5381 a8083063 Iustin Pop
  """Modifies an instances's parameters.
5382 a8083063 Iustin Pop

5383 a8083063 Iustin Pop
  """
5384 a8083063 Iustin Pop
  HPATH = "instance-modify"
5385 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
5386 24991749 Iustin Pop
  _OP_REQP = ["instance_name"]
5387 1a5c7281 Guido Trotter
  REQ_BGL = False
5388 1a5c7281 Guido Trotter
5389 24991749 Iustin Pop
  def CheckArguments(self):
5390 24991749 Iustin Pop
    if not hasattr(self.op, 'nics'):
5391 24991749 Iustin Pop
      self.op.nics = []
5392 24991749 Iustin Pop
    if not hasattr(self.op, 'disks'):
5393 24991749 Iustin Pop
      self.op.disks = []
5394 24991749 Iustin Pop
    if not hasattr(self.op, 'beparams'):
5395 24991749 Iustin Pop
      self.op.beparams = {}
5396 24991749 Iustin Pop
    if not hasattr(self.op, 'hvparams'):
5397 24991749 Iustin Pop
      self.op.hvparams = {}
5398 24991749 Iustin Pop
    self.op.force = getattr(self.op, "force", False)
5399 24991749 Iustin Pop
    if not (self.op.nics or self.op.disks or
5400 24991749 Iustin Pop
            self.op.hvparams or self.op.beparams):
5401 24991749 Iustin Pop
      raise errors.OpPrereqError("No changes submitted")
5402 24991749 Iustin Pop
5403 d4b72030 Guido Trotter
    utils.CheckBEParams(self.op.beparams)
5404 d4b72030 Guido Trotter
5405 24991749 Iustin Pop
    # Disk validation
5406 24991749 Iustin Pop
    disk_addremove = 0
5407 24991749 Iustin Pop
    for disk_op, disk_dict in self.op.disks:
5408 24991749 Iustin Pop
      if disk_op == constants.DDM_REMOVE:
5409 24991749 Iustin Pop
        disk_addremove += 1
5410 24991749 Iustin Pop
        continue
5411 24991749 Iustin Pop
      elif disk_op == constants.DDM_ADD:
5412 24991749 Iustin Pop
        disk_addremove += 1
5413 24991749 Iustin Pop
      else:
5414 24991749 Iustin Pop
        if not isinstance(disk_op, int):
5415 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid disk index")
5416 24991749 Iustin Pop
      if disk_op == constants.DDM_ADD:
5417 24991749 Iustin Pop
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
5418 24991749 Iustin Pop
        if mode not in (constants.DISK_RDONLY, constants.DISK_RDWR):
5419 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode)
5420 24991749 Iustin Pop
        size = disk_dict.get('size', None)
5421 24991749 Iustin Pop
        if size is None:
5422 24991749 Iustin Pop
          raise errors.OpPrereqError("Required disk parameter size missing")
5423 24991749 Iustin Pop
        try:
5424 24991749 Iustin Pop
          size = int(size)
5425 24991749 Iustin Pop
        except ValueError, err:
5426 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
5427 24991749 Iustin Pop
                                     str(err))
5428 24991749 Iustin Pop
        disk_dict['size'] = size
5429 24991749 Iustin Pop
      else:
5430 24991749 Iustin Pop
        # modification of disk
5431 24991749 Iustin Pop
        if 'size' in disk_dict:
5432 24991749 Iustin Pop
          raise errors.OpPrereqError("Disk size change not possible, use"
5433 24991749 Iustin Pop
                                     " grow-disk")
5434 24991749 Iustin Pop
5435 24991749 Iustin Pop
    if disk_addremove > 1:
5436 24991749 Iustin Pop
      raise errors.OpPrereqError("Only one disk add or remove operation"
5437 24991749 Iustin Pop
                                 " supported at a time")
5438 24991749 Iustin Pop
5439 24991749 Iustin Pop
    # NIC validation
5440 24991749 Iustin Pop
    nic_addremove = 0
5441 24991749 Iustin Pop
    for nic_op, nic_dict in self.op.nics:
5442 24991749 Iustin Pop
      if nic_op == constants.DDM_REMOVE:
5443 24991749 Iustin Pop
        nic_addremove += 1
5444 24991749 Iustin Pop
        continue
5445 24991749 Iustin Pop
      elif nic_op == constants.DDM_ADD:
5446 24991749 Iustin Pop
        nic_addremove += 1
5447 24991749 Iustin Pop
      else:
5448 24991749 Iustin Pop
        if not isinstance(nic_op, int):
5449 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid nic index")
5450 24991749 Iustin Pop
5451 24991749 Iustin Pop
      # nic_dict should be a dict
5452 24991749 Iustin Pop
      nic_ip = nic_dict.get('ip', None)
5453 24991749 Iustin Pop
      if nic_ip is not None:
5454 24991749 Iustin Pop
        if nic_ip.lower() == "none":
5455 24991749 Iustin Pop
          nic_dict['ip'] = None
5456 24991749 Iustin Pop
        else:
5457 24991749 Iustin Pop
          if not utils.IsValidIP(nic_ip):
5458 24991749 Iustin Pop
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip)
5459 24991749 Iustin Pop
      # we can only check None bridges and assign the default one
5460 24991749 Iustin Pop
      nic_bridge = nic_dict.get('bridge', None)
5461 24991749 Iustin Pop
      if nic_bridge is None:
5462 24991749 Iustin Pop
        nic_dict['bridge'] = self.cfg.GetDefBridge()
5463 24991749 Iustin Pop
      # but we can validate MACs
5464 24991749 Iustin Pop
      nic_mac = nic_dict.get('mac', None)
5465 24991749 Iustin Pop
      if nic_mac is not None:
5466 24991749 Iustin Pop
        if self.cfg.IsMacInUse(nic_mac):
5467 24991749 Iustin Pop
          raise errors.OpPrereqError("MAC address %s already in use"
5468 24991749 Iustin Pop
                                     " in cluster" % nic_mac)
5469 24991749 Iustin Pop
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5470 24991749 Iustin Pop
          if not utils.IsValidMac(nic_mac):
5471 24991749 Iustin Pop
            raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac)
5472 24991749 Iustin Pop
    if nic_addremove > 1:
5473 24991749 Iustin Pop
      raise errors.OpPrereqError("Only one NIC add or remove operation"
5474 24991749 Iustin Pop
                                 " supported at a time")
5475 24991749 Iustin Pop
5476 1a5c7281 Guido Trotter
  def ExpandNames(self):
5477 1a5c7281 Guido Trotter
    self._ExpandAndLockInstance()
5478 74409b12 Iustin Pop
    self.needed_locks[locking.LEVEL_NODE] = []
5479 74409b12 Iustin Pop
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5480 74409b12 Iustin Pop
5481 74409b12 Iustin Pop
  def DeclareLocks(self, level):
5482 74409b12 Iustin Pop
    if level == locking.LEVEL_NODE:
5483 74409b12 Iustin Pop
      self._LockInstancesNodes()
5484 a8083063 Iustin Pop
5485 a8083063 Iustin Pop
  def BuildHooksEnv(self):
5486 a8083063 Iustin Pop
    """Build hooks env.
5487 a8083063 Iustin Pop

5488 a8083063 Iustin Pop
    This runs on the master, primary and secondaries.
5489 a8083063 Iustin Pop

5490 a8083063 Iustin Pop
    """
5491 396e1b78 Michael Hanselmann
    args = dict()
5492 338e51e8 Iustin Pop
    if constants.BE_MEMORY in self.be_new:
5493 338e51e8 Iustin Pop
      args['memory'] = self.be_new[constants.BE_MEMORY]
5494 338e51e8 Iustin Pop
    if constants.BE_VCPUS in self.be_new:
5495 61be6ba4 Iustin Pop
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
5496 24991749 Iustin Pop
    # FIXME: readd disk/nic changes
5497 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
5498 6b12959c Iustin Pop
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5499 a8083063 Iustin Pop
    return env, nl, nl
5500 a8083063 Iustin Pop
5501 a8083063 Iustin Pop
  def CheckPrereq(self):
5502 a8083063 Iustin Pop
    """Check prerequisites.
5503 a8083063 Iustin Pop

5504 a8083063 Iustin Pop
    This only checks the instance list against the existing names.
5505 a8083063 Iustin Pop

5506 a8083063 Iustin Pop
    """
5507 24991749 Iustin Pop
    force = self.force = self.op.force
5508 a8083063 Iustin Pop
5509 74409b12 Iustin Pop
    # checking the new params on the primary/secondary nodes
5510 31a853d2 Iustin Pop
5511 cfefe007 Guido Trotter
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5512 1a5c7281 Guido Trotter
    assert self.instance is not None, \
5513 1a5c7281 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
5514 6b12959c Iustin Pop
    pnode = instance.primary_node
5515 6b12959c Iustin Pop
    nodelist = list(instance.all_nodes)
5516 74409b12 Iustin Pop
5517 338e51e8 Iustin Pop
    # hvparams processing
5518 74409b12 Iustin Pop
    if self.op.hvparams:
5519 74409b12 Iustin Pop
      i_hvdict = copy.deepcopy(instance.hvparams)
5520 74409b12 Iustin Pop
      for key, val in self.op.hvparams.iteritems():
5521 8edcd611 Guido Trotter
        if val == constants.VALUE_DEFAULT:
5522 74409b12 Iustin Pop
          try:
5523 74409b12 Iustin Pop
            del i_hvdict[key]
5524 74409b12 Iustin Pop
          except KeyError:
5525 74409b12 Iustin Pop
            pass
5526 8edcd611 Guido Trotter
        elif val == constants.VALUE_NONE:
5527 8edcd611 Guido Trotter
          i_hvdict[key] = None
5528 74409b12 Iustin Pop
        else:
5529 74409b12 Iustin Pop
          i_hvdict[key] = val
5530 74409b12 Iustin Pop
      cluster = self.cfg.GetClusterInfo()
5531 74409b12 Iustin Pop
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
5532 74409b12 Iustin Pop
                                i_hvdict)
5533 74409b12 Iustin Pop
      # local check
5534 74409b12 Iustin Pop
      hypervisor.GetHypervisor(
5535 74409b12 Iustin Pop
        instance.hypervisor).CheckParameterSyntax(hv_new)
5536 74409b12 Iustin Pop
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
5537 338e51e8 Iustin Pop
      self.hv_new = hv_new # the new actual values
5538 338e51e8 Iustin Pop
      self.hv_inst = i_hvdict # the new dict (without defaults)
5539 338e51e8 Iustin Pop
    else:
5540 338e51e8 Iustin Pop
      self.hv_new = self.hv_inst = {}
5541 338e51e8 Iustin Pop
5542 338e51e8 Iustin Pop
    # beparams processing
5543 338e51e8 Iustin Pop
    if self.op.beparams:
5544 338e51e8 Iustin Pop
      i_bedict = copy.deepcopy(instance.beparams)
5545 338e51e8 Iustin Pop
      for key, val in self.op.beparams.iteritems():
5546 8edcd611 Guido Trotter
        if val == constants.VALUE_DEFAULT:
5547 338e51e8 Iustin Pop
          try:
5548 338e51e8 Iustin Pop
            del i_bedict[key]
5549 338e51e8 Iustin Pop
          except KeyError:
5550 338e51e8 Iustin Pop
            pass
5551 338e51e8 Iustin Pop
        else:
5552 338e51e8 Iustin Pop
          i_bedict[key] = val
5553 338e51e8 Iustin Pop
      cluster = self.cfg.GetClusterInfo()
5554 338e51e8 Iustin Pop
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
5555 338e51e8 Iustin Pop
                                i_bedict)
5556 338e51e8 Iustin Pop
      self.be_new = be_new # the new actual values
5557 338e51e8 Iustin Pop
      self.be_inst = i_bedict # the new dict (without defaults)
5558 338e51e8 Iustin Pop
    else:
5559 b637ae4d Iustin Pop
      self.be_new = self.be_inst = {}
5560 74409b12 Iustin Pop
5561 cfefe007 Guido Trotter
    self.warn = []
5562 647a5d80 Iustin Pop
5563 338e51e8 Iustin Pop
    if constants.BE_MEMORY in self.op.beparams and not self.force:
5564 647a5d80 Iustin Pop
      mem_check_list = [pnode]
5565 c0f2b229 Iustin Pop
      if be_new[constants.BE_AUTO_BALANCE]:
5566 c0f2b229 Iustin Pop
        # either we changed auto_balance to yes or it was from before
5567 647a5d80 Iustin Pop
        mem_check_list.extend(instance.secondary_nodes)
5568 72737a7f Iustin Pop
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
5569 72737a7f Iustin Pop
                                                  instance.hypervisor)
5570 647a5d80 Iustin Pop
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
5571 72737a7f Iustin Pop
                                         instance.hypervisor)
5572 781de953 Iustin Pop
      if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict):
5573 cfefe007 Guido Trotter
        # Assume the primary node is unreachable and go ahead
5574 cfefe007 Guido Trotter
        self.warn.append("Can't get info from primary node %s" % pnode)
5575 cfefe007 Guido Trotter
      else:
5576 781de953 Iustin Pop
        if not instance_info.failed and instance_info.data:
5577 781de953 Iustin Pop
          current_mem = instance_info.data['memory']
5578 cfefe007 Guido Trotter
        else:
5579 cfefe007 Guido Trotter
          # Assume instance not running
5580 cfefe007 Guido Trotter
          # (there is a slight race condition here, but it's not very probable,
5581 cfefe007 Guido Trotter
          # and we have no other way to check)
5582 cfefe007 Guido Trotter
          current_mem = 0
5583 338e51e8 Iustin Pop
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
5584 781de953 Iustin Pop
                    nodeinfo[pnode].data['memory_free'])
5585 cfefe007 Guido Trotter
        if miss_mem > 0:
5586 cfefe007 Guido Trotter
          raise errors.OpPrereqError("This change will prevent the instance"
5587 cfefe007 Guido Trotter
                                     " from starting, due to %d MB of memory"
5588 cfefe007 Guido Trotter
                                     " missing on its primary node" % miss_mem)
5589 cfefe007 Guido Trotter
5590 c0f2b229 Iustin Pop
      if be_new[constants.BE_AUTO_BALANCE]:
5591 ea33068f Iustin Pop
        for node, nres in nodeinfo.iteritems():
5592 ea33068f Iustin Pop
          if node not in instance.secondary_nodes:
5593 ea33068f Iustin Pop
            continue
5594 781de953 Iustin Pop
          if nres.failed or not isinstance(nres.data, dict):
5595 647a5d80 Iustin Pop
            self.warn.append("Can't get info from secondary node %s" % node)
5596 781de953 Iustin Pop
          elif be_new[constants.BE_MEMORY] > nres.data['memory_free']:
5597 647a5d80 Iustin Pop
            self.warn.append("Not enough memory to failover instance to"
5598 647a5d80 Iustin Pop
                             " secondary node %s" % node)
5599 5bc84f33 Alexander Schreiber
5600 24991749 Iustin Pop
    # NIC processing
5601 24991749 Iustin Pop
    for nic_op, nic_dict in self.op.nics:
5602 24991749 Iustin Pop
      if nic_op == constants.DDM_REMOVE:
5603 24991749 Iustin Pop
        if not instance.nics:
5604 24991749 Iustin Pop
          raise errors.OpPrereqError("Instance has no NICs, cannot remove")
5605 24991749 Iustin Pop
        continue
5606 24991749 Iustin Pop
      if nic_op != constants.DDM_ADD:
5607 24991749 Iustin Pop
        # an existing nic
5608 24991749 Iustin Pop
        if nic_op < 0 or nic_op >= len(instance.nics):
5609 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
5610 24991749 Iustin Pop
                                     " are 0 to %d" %
5611 24991749 Iustin Pop
                                     (nic_op, len(instance.nics)))
5612 24991749 Iustin Pop
      nic_bridge = nic_dict.get('bridge', None)
5613 24991749 Iustin Pop
      if nic_bridge is not None:
5614 24991749 Iustin Pop
        if not self.rpc.call_bridges_exist(pnode, [nic_bridge]):
5615 24991749 Iustin Pop
          msg = ("Bridge '%s' doesn't exist on one of"
5616 24991749 Iustin Pop
                 " the instance nodes" % nic_bridge)
5617 24991749 Iustin Pop
          if self.force:
5618 24991749 Iustin Pop
            self.warn.append(msg)
5619 24991749 Iustin Pop
          else:
5620 24991749 Iustin Pop
            raise errors.OpPrereqError(msg)
5621 24991749 Iustin Pop
5622 24991749 Iustin Pop
    # DISK processing
5623 24991749 Iustin Pop
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
5624 24991749 Iustin Pop
      raise errors.OpPrereqError("Disk operations not supported for"
5625 24991749 Iustin Pop
                                 " diskless instances")
5626 24991749 Iustin Pop
    for disk_op, disk_dict in self.op.disks:
5627 24991749 Iustin Pop
      if disk_op == constants.DDM_REMOVE:
5628 24991749 Iustin Pop
        if len(instance.disks) == 1:
5629 24991749 Iustin Pop
          raise errors.OpPrereqError("Cannot remove the last disk of"
5630 24991749 Iustin Pop
                                     " an instance")
5631 24991749 Iustin Pop
        ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
5632 24991749 Iustin Pop
        ins_l = ins_l[pnode]
5633 4cfb9426 Iustin Pop
        if ins_l.failed or not isinstance(ins_l.data, list):
5634 24991749 Iustin Pop
          raise errors.OpPrereqError("Can't contact node '%s'" % pnode)
5635 4cfb9426 Iustin Pop
        if instance.name in ins_l.data:
5636 24991749 Iustin Pop
          raise errors.OpPrereqError("Instance is running, can't remove"
5637 24991749 Iustin Pop
                                     " disks.")
5638 24991749 Iustin Pop
5639 24991749 Iustin Pop
      if (disk_op == constants.DDM_ADD and
5640 24991749 Iustin Pop
          len(instance.nics) >= constants.MAX_DISKS):
5641 24991749 Iustin Pop
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
5642 24991749 Iustin Pop
                                   " add more" % constants.MAX_DISKS)
5643 24991749 Iustin Pop
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
5644 24991749 Iustin Pop
        # an existing disk
5645 24991749 Iustin Pop
        if disk_op < 0 or disk_op >= len(instance.disks):
5646 24991749 Iustin Pop
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
5647 24991749 Iustin Pop
                                     " are 0 to %d" %
5648 24991749 Iustin Pop
                                     (disk_op, len(instance.disks)))
5649 24991749 Iustin Pop
5650 a8083063 Iustin Pop
    return
5651 a8083063 Iustin Pop
5652 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
5653 a8083063 Iustin Pop
    """Modifies an instance.
5654 a8083063 Iustin Pop

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

5657 a8083063 Iustin Pop
    """
5658 cfefe007 Guido Trotter
    # Process here the warnings from CheckPrereq, as we don't have a
5659 cfefe007 Guido Trotter
    # feedback_fn there.
5660 cfefe007 Guido Trotter
    for warn in self.warn:
5661 cfefe007 Guido Trotter
      feedback_fn("WARNING: %s" % warn)
5662 cfefe007 Guido Trotter
5663 a8083063 Iustin Pop
    result = []
5664 a8083063 Iustin Pop
    instance = self.instance
5665 24991749 Iustin Pop
    # disk changes
5666 24991749 Iustin Pop
    for disk_op, disk_dict in self.op.disks:
5667 24991749 Iustin Pop
      if disk_op == constants.DDM_REMOVE:
5668 24991749 Iustin Pop
        # remove the last disk
5669 24991749 Iustin Pop
        device = instance.disks.pop()
5670 24991749 Iustin Pop
        device_idx = len(instance.disks)
5671 24991749 Iustin Pop
        for node, disk in device.ComputeNodeTree(instance.primary_node):
5672 24991749 Iustin Pop
          self.cfg.SetDiskID(disk, node)
5673 4cfb9426 Iustin Pop
          rpc_result = self.rpc.call_blockdev_remove(node, disk)
5674 4cfb9426 Iustin Pop
          if rpc_result.failed or not rpc_result.data:
5675 24991749 Iustin Pop
            self.proc.LogWarning("Could not remove disk/%d on node %s,"
5676 24991749 Iustin Pop
                                 " continuing anyway", device_idx, node)
5677 24991749 Iustin Pop
        result.append(("disk/%d" % device_idx, "remove"))
5678 24991749 Iustin Pop
      elif disk_op == constants.DDM_ADD:
5679 24991749 Iustin Pop
        # add a new disk
5680 24991749 Iustin Pop
        if instance.disk_template == constants.DT_FILE:
5681 24991749 Iustin Pop
          file_driver, file_path = instance.disks[0].logical_id
5682 24991749 Iustin Pop
          file_path = os.path.dirname(file_path)
5683 24991749 Iustin Pop
        else:
5684 24991749 Iustin Pop
          file_driver = file_path = None
5685 24991749 Iustin Pop
        disk_idx_base = len(instance.disks)
5686 24991749 Iustin Pop
        new_disk = _GenerateDiskTemplate(self,
5687 24991749 Iustin Pop
                                         instance.disk_template,
5688 24991749 Iustin Pop
                                         instance, instance.primary_node,
5689 24991749 Iustin Pop
                                         instance.secondary_nodes,
5690 24991749 Iustin Pop
                                         [disk_dict],
5691 24991749 Iustin Pop
                                         file_path,
5692 24991749 Iustin Pop
                                         file_driver,
5693 24991749 Iustin Pop
                                         disk_idx_base)[0]
5694 24991749 Iustin Pop
        new_disk.mode = disk_dict['mode']
5695 24991749 Iustin Pop
        instance.disks.append(new_disk)
5696 24991749 Iustin Pop
        info = _GetInstanceInfoText(instance)
5697 24991749 Iustin Pop
5698 24991749 Iustin Pop
        logging.info("Creating volume %s for instance %s",
5699 24991749 Iustin Pop
                     new_disk.iv_name, instance.name)
5700 24991749 Iustin Pop
        # Note: this needs to be kept in sync with _CreateDisks
5701 24991749 Iustin Pop
        #HARDCODE
5702 428958aa Iustin Pop
        for node in instance.all_nodes:
5703 428958aa Iustin Pop
          f_create = node == instance.primary_node
5704 796cab27 Iustin Pop
          try:
5705 428958aa Iustin Pop
            _CreateBlockDev(self, node, instance, new_disk,
5706 428958aa Iustin Pop
                            f_create, info, f_create)
5707 1492cca7 Iustin Pop
          except errors.OpExecError, err:
5708 24991749 Iustin Pop
            self.LogWarning("Failed to create volume %s (%s) on"
5709 428958aa Iustin Pop
                            " node %s: %s",
5710 428958aa Iustin Pop
                            new_disk.iv_name, new_disk, node, err)
5711 24991749 Iustin Pop
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
5712 24991749 Iustin Pop
                       (new_disk.size, new_disk.mode)))
5713 24991749 Iustin Pop
      else:
5714 24991749 Iustin Pop
        # change a given disk
5715 24991749 Iustin Pop
        instance.disks[disk_op].mode = disk_dict['mode']
5716 24991749 Iustin Pop
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
5717 24991749 Iustin Pop
    # NIC changes
5718 24991749 Iustin Pop
    for nic_op, nic_dict in self.op.nics:
5719 24991749 Iustin Pop
      if nic_op == constants.DDM_REMOVE:
5720 24991749 Iustin Pop
        # remove the last nic
5721 24991749 Iustin Pop
        del instance.nics[-1]
5722 24991749 Iustin Pop
        result.append(("nic.%d" % len(instance.nics), "remove"))
5723 24991749 Iustin Pop
      elif nic_op == constants.DDM_ADD:
5724 24991749 Iustin Pop
        # add a new nic
5725 24991749 Iustin Pop
        if 'mac' not in nic_dict:
5726 24991749 Iustin Pop
          mac = constants.VALUE_GENERATE
5727 24991749 Iustin Pop
        else:
5728 24991749 Iustin Pop
          mac = nic_dict['mac']
5729 24991749 Iustin Pop
        if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
5730 24991749 Iustin Pop
          mac = self.cfg.GenerateMAC()
5731 24991749 Iustin Pop
        new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None),
5732 24991749 Iustin Pop
                              bridge=nic_dict.get('bridge', None))
5733 24991749 Iustin Pop
        instance.nics.append(new_nic)
5734 24991749 Iustin Pop
        result.append(("nic.%d" % (len(instance.nics) - 1),
5735 24991749 Iustin Pop
                       "add:mac=%s,ip=%s,bridge=%s" %
5736 24991749 Iustin Pop
                       (new_nic.mac, new_nic.ip, new_nic.bridge)))
5737 24991749 Iustin Pop
      else:
5738 24991749 Iustin Pop
        # change a given nic
5739 24991749 Iustin Pop
        for key in 'mac', 'ip', 'bridge':
5740 24991749 Iustin Pop
          if key in nic_dict:
5741 24991749 Iustin Pop
            setattr(instance.nics[nic_op], key, nic_dict[key])
5742 24991749 Iustin Pop
            result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
5743 24991749 Iustin Pop
5744 24991749 Iustin Pop
    # hvparams changes
5745 74409b12 Iustin Pop
    if self.op.hvparams:
5746 74409b12 Iustin Pop
      instance.hvparams = self.hv_new
5747 74409b12 Iustin Pop
      for key, val in self.op.hvparams.iteritems():
5748 74409b12 Iustin Pop
        result.append(("hv/%s" % key, val))
5749 24991749 Iustin Pop
5750 24991749 Iustin Pop
    # beparams changes
5751 338e51e8 Iustin Pop
    if self.op.beparams:
5752 338e51e8 Iustin Pop
      instance.beparams = self.be_inst
5753 338e51e8 Iustin Pop
      for key, val in self.op.beparams.iteritems():
5754 338e51e8 Iustin Pop
        result.append(("be/%s" % key, val))
5755 a8083063 Iustin Pop
5756 ea94e1cd Guido Trotter
    self.cfg.Update(instance)
5757 a8083063 Iustin Pop
5758 a8083063 Iustin Pop
    return result
5759 a8083063 Iustin Pop
5760 a8083063 Iustin Pop
5761 a8083063 Iustin Pop
class LUQueryExports(NoHooksLU):
5762 a8083063 Iustin Pop
  """Query the exports list
5763 a8083063 Iustin Pop

5764 a8083063 Iustin Pop
  """
5765 895ecd9c Guido Trotter
  _OP_REQP = ['nodes']
5766 21a15682 Guido Trotter
  REQ_BGL = False
5767 21a15682 Guido Trotter
5768 21a15682 Guido Trotter
  def ExpandNames(self):
5769 21a15682 Guido Trotter
    self.needed_locks = {}
5770 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
5771 21a15682 Guido Trotter
    if not self.op.nodes:
5772 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5773 21a15682 Guido Trotter
    else:
5774 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
5775 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
5776 a8083063 Iustin Pop
5777 a8083063 Iustin Pop
  def CheckPrereq(self):
5778 21a15682 Guido Trotter
    """Check prerequisites.
5779 a8083063 Iustin Pop

5780 a8083063 Iustin Pop
    """
5781 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
5782 a8083063 Iustin Pop
5783 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
5784 a8083063 Iustin Pop
    """Compute the list of all the exported system images.
5785 a8083063 Iustin Pop

5786 e4376078 Iustin Pop
    @rtype: dict
5787 e4376078 Iustin Pop
    @return: a dictionary with the structure node->(export-list)
5788 e4376078 Iustin Pop
        where export-list is a list of the instances exported on
5789 e4376078 Iustin Pop
        that node.
5790 a8083063 Iustin Pop

5791 a8083063 Iustin Pop
    """
5792 b04285f2 Guido Trotter
    rpcresult = self.rpc.call_export_list(self.nodes)
5793 b04285f2 Guido Trotter
    result = {}
5794 b04285f2 Guido Trotter
    for node in rpcresult:
5795 b04285f2 Guido Trotter
      if rpcresult[node].failed:
5796 b04285f2 Guido Trotter
        result[node] = False
5797 b04285f2 Guido Trotter
      else:
5798 b04285f2 Guido Trotter
        result[node] = rpcresult[node].data
5799 b04285f2 Guido Trotter
5800 b04285f2 Guido Trotter
    return result
5801 a8083063 Iustin Pop
5802 a8083063 Iustin Pop
5803 a8083063 Iustin Pop
class LUExportInstance(LogicalUnit):
5804 a8083063 Iustin Pop
  """Export an instance to an image in the cluster.
5805 a8083063 Iustin Pop

5806 a8083063 Iustin Pop
  """
5807 a8083063 Iustin Pop
  HPATH = "instance-export"
5808 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
5809 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
5810 6657590e Guido Trotter
  REQ_BGL = False
5811 6657590e Guido Trotter
5812 6657590e Guido Trotter
  def ExpandNames(self):
5813 6657590e Guido Trotter
    self._ExpandAndLockInstance()
5814 6657590e Guido Trotter
    # FIXME: lock only instance primary and destination node
5815 6657590e Guido Trotter
    #
5816 6657590e Guido Trotter
    # Sad but true, for now we have do lock all nodes, as we don't know where
5817 6657590e Guido Trotter
    # the previous export might be, and and in this LU we search for it and
5818 6657590e Guido Trotter
    # remove it from its current node. In the future we could fix this by:
5819 6657590e Guido Trotter
    #  - making a tasklet to search (share-lock all), then create the new one,
5820 6657590e Guido Trotter
    #    then one to remove, after
5821 6657590e Guido Trotter
    #  - removing the removal operation altoghether
5822 6657590e Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5823 6657590e Guido Trotter
5824 6657590e Guido Trotter
  def DeclareLocks(self, level):
5825 6657590e Guido Trotter
    """Last minute lock declaration."""
5826 6657590e Guido Trotter
    # All nodes are locked anyway, so nothing to do here.
5827 a8083063 Iustin Pop
5828 a8083063 Iustin Pop
  def BuildHooksEnv(self):
5829 a8083063 Iustin Pop
    """Build hooks env.
5830 a8083063 Iustin Pop

5831 a8083063 Iustin Pop
    This will run on the master, primary node and target node.
5832 a8083063 Iustin Pop

5833 a8083063 Iustin Pop
    """
5834 a8083063 Iustin Pop
    env = {
5835 a8083063 Iustin Pop
      "EXPORT_NODE": self.op.target_node,
5836 a8083063 Iustin Pop
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
5837 a8083063 Iustin Pop
      }
5838 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5839 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
5840 a8083063 Iustin Pop
          self.op.target_node]
5841 a8083063 Iustin Pop
    return env, nl, nl
5842 a8083063 Iustin Pop
5843 a8083063 Iustin Pop
  def CheckPrereq(self):
5844 a8083063 Iustin Pop
    """Check prerequisites.
5845 a8083063 Iustin Pop

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

5848 a8083063 Iustin Pop
    """
5849 6657590e Guido Trotter
    instance_name = self.op.instance_name
5850 a8083063 Iustin Pop
    self.instance = self.cfg.GetInstanceInfo(instance_name)
5851 6657590e Guido Trotter
    assert self.instance is not None, \
5852 6657590e Guido Trotter
          "Cannot retrieve locked instance %s" % self.op.instance_name
5853 43017d26 Iustin Pop
    _CheckNodeOnline(self, self.instance.primary_node)
5854 a8083063 Iustin Pop
5855 6657590e Guido Trotter
    self.dst_node = self.cfg.GetNodeInfo(
5856 6657590e Guido Trotter
      self.cfg.ExpandNodeName(self.op.target_node))
5857 a8083063 Iustin Pop
5858 268b8e42 Iustin Pop
    if self.dst_node is None:
5859 268b8e42 Iustin Pop
      # This is wrong node name, not a non-locked node
5860 268b8e42 Iustin Pop
      raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node)
5861 aeb83a2b Iustin Pop
    _CheckNodeOnline(self, self.dst_node.name)
5862 a8083063 Iustin Pop
5863 b6023d6c Manuel Franceschini
    # instance disk type verification
5864 b6023d6c Manuel Franceschini
    for disk in self.instance.disks:
5865 b6023d6c Manuel Franceschini
      if disk.dev_type == constants.LD_FILE:
5866 b6023d6c Manuel Franceschini
        raise errors.OpPrereqError("Export not supported for instances with"
5867 b6023d6c Manuel Franceschini
                                   " file-based disks")
5868 b6023d6c Manuel Franceschini
5869 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
5870 a8083063 Iustin Pop
    """Export an instance to an image in the cluster.
5871 a8083063 Iustin Pop

5872 a8083063 Iustin Pop
    """
5873 a8083063 Iustin Pop
    instance = self.instance
5874 a8083063 Iustin Pop
    dst_node = self.dst_node
5875 a8083063 Iustin Pop
    src_node = instance.primary_node
5876 a8083063 Iustin Pop
    if self.op.shutdown:
5877 fb300fb7 Guido Trotter
      # shutdown the instance, but not the disks
5878 781de953 Iustin Pop
      result = self.rpc.call_instance_shutdown(src_node, instance)
5879 781de953 Iustin Pop
      result.Raise()
5880 781de953 Iustin Pop
      if not result.data:
5881 38206f3c Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
5882 38206f3c Iustin Pop
                                 (instance.name, src_node))
5883 a8083063 Iustin Pop
5884 a8083063 Iustin Pop
    vgname = self.cfg.GetVGName()
5885 a8083063 Iustin Pop
5886 a8083063 Iustin Pop
    snap_disks = []
5887 a8083063 Iustin Pop
5888 998c712c Iustin Pop
    # set the disks ID correctly since call_instance_start needs the
5889 998c712c Iustin Pop
    # correct drbd minor to create the symlinks
5890 998c712c Iustin Pop
    for disk in instance.disks:
5891 998c712c Iustin Pop
      self.cfg.SetDiskID(disk, src_node)
5892 998c712c Iustin Pop
5893 a8083063 Iustin Pop
    try:
5894 a8083063 Iustin Pop
      for disk in instance.disks:
5895 19d7f90a Guido Trotter
        # new_dev_name will be a snapshot of an lvm leaf of the one we passed
5896 19d7f90a Guido Trotter
        new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
5897 781de953 Iustin Pop
        if new_dev_name.failed or not new_dev_name.data:
5898 19d7f90a Guido Trotter
          self.LogWarning("Could not snapshot block device %s on node %s",
5899 9a4f63d1 Iustin Pop
                          disk.logical_id[1], src_node)
5900 19d7f90a Guido Trotter
          snap_disks.append(False)
5901 19d7f90a Guido Trotter
        else:
5902 19d7f90a Guido Trotter
          new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
5903 781de953 Iustin Pop
                                 logical_id=(vgname, new_dev_name.data),
5904 781de953 Iustin Pop
                                 physical_id=(vgname, new_dev_name.data),
5905 19d7f90a Guido Trotter
                                 iv_name=disk.iv_name)
5906 19d7f90a Guido Trotter
          snap_disks.append(new_dev)
5907 a8083063 Iustin Pop
5908 a8083063 Iustin Pop
    finally:
5909 fb300fb7 Guido Trotter
      if self.op.shutdown and instance.status == "up":
5910 781de953 Iustin Pop
        result = self.rpc.call_instance_start(src_node, instance, None)
5911 dd279568 Iustin Pop
        msg = result.RemoteFailMsg()
5912 dd279568 Iustin Pop
        if msg:
5913 b9bddb6b Iustin Pop
          _ShutdownInstanceDisks(self, instance)
5914 dd279568 Iustin Pop
          raise errors.OpExecError("Could not start instance: %s" % msg)
5915 a8083063 Iustin Pop
5916 a8083063 Iustin Pop
    # TODO: check for size
5917 a8083063 Iustin Pop
5918 62c9ec92 Iustin Pop
    cluster_name = self.cfg.GetClusterName()
5919 74c47259 Iustin Pop
    for idx, dev in enumerate(snap_disks):
5920 19d7f90a Guido Trotter
      if dev:
5921 781de953 Iustin Pop
        result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
5922 781de953 Iustin Pop
                                               instance, cluster_name, idx)
5923 781de953 Iustin Pop
        if result.failed or not result.data:
5924 19d7f90a Guido Trotter
          self.LogWarning("Could not export block device %s from node %s to"
5925 19d7f90a Guido Trotter
                          " node %s", dev.logical_id[1], src_node,
5926 19d7f90a Guido Trotter
                          dst_node.name)
5927 781de953 Iustin Pop
        result = self.rpc.call_blockdev_remove(src_node, dev)
5928 781de953 Iustin Pop
        if result.failed or not result.data:
5929 19d7f90a Guido Trotter
          self.LogWarning("Could not remove snapshot block device %s from node"
5930 19d7f90a Guido Trotter
                          " %s", dev.logical_id[1], src_node)
5931 a8083063 Iustin Pop
5932 781de953 Iustin Pop
    result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
5933 781de953 Iustin Pop
    if result.failed or not result.data:
5934 19d7f90a Guido Trotter
      self.LogWarning("Could not finalize export for instance %s on node %s",
5935 19d7f90a Guido Trotter
                      instance.name, dst_node.name)
5936 a8083063 Iustin Pop
5937 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
5938 a8083063 Iustin Pop
    nodelist.remove(dst_node.name)
5939 a8083063 Iustin Pop
5940 a8083063 Iustin Pop
    # on one-node clusters nodelist will be empty after the removal
5941 a8083063 Iustin Pop
    # if we proceed the backup would be removed because OpQueryExports
5942 a8083063 Iustin Pop
    # substitutes an empty list with the full cluster node list.
5943 a8083063 Iustin Pop
    if nodelist:
5944 72737a7f Iustin Pop
      exportlist = self.rpc.call_export_list(nodelist)
5945 a8083063 Iustin Pop
      for node in exportlist:
5946 781de953 Iustin Pop
        if exportlist[node].failed:
5947 781de953 Iustin Pop
          continue
5948 781de953 Iustin Pop
        if instance.name in exportlist[node].data:
5949 72737a7f Iustin Pop
          if not self.rpc.call_export_remove(node, instance.name):
5950 19d7f90a Guido Trotter
            self.LogWarning("Could not remove older export for instance %s"
5951 19d7f90a Guido Trotter
                            " on node %s", instance.name, node)
5952 5c947f38 Iustin Pop
5953 5c947f38 Iustin Pop
5954 9ac99fda Guido Trotter
class LURemoveExport(NoHooksLU):
5955 9ac99fda Guido Trotter
  """Remove exports related to the named instance.
5956 9ac99fda Guido Trotter

5957 9ac99fda Guido Trotter
  """
5958 9ac99fda Guido Trotter
  _OP_REQP = ["instance_name"]
5959 3656b3af Guido Trotter
  REQ_BGL = False
5960 3656b3af Guido Trotter
5961 3656b3af Guido Trotter
  def ExpandNames(self):
5962 3656b3af Guido Trotter
    self.needed_locks = {}
5963 3656b3af Guido Trotter
    # We need all nodes to be locked in order for RemoveExport to work, but we
5964 3656b3af Guido Trotter
    # don't need to lock the instance itself, as nothing will happen to it (and
5965 3656b3af Guido Trotter
    # we can remove exports also for a removed instance)
5966 3656b3af Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5967 9ac99fda Guido Trotter
5968 9ac99fda Guido Trotter
  def CheckPrereq(self):
5969 9ac99fda Guido Trotter
    """Check prerequisites.
5970 9ac99fda Guido Trotter
    """
5971 9ac99fda Guido Trotter
    pass
5972 9ac99fda Guido Trotter
5973 9ac99fda Guido Trotter
  def Exec(self, feedback_fn):
5974 9ac99fda Guido Trotter
    """Remove any export.
5975 9ac99fda Guido Trotter

5976 9ac99fda Guido Trotter
    """
5977 9ac99fda Guido Trotter
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
5978 9ac99fda Guido Trotter
    # If the instance was not found we'll try with the name that was passed in.
5979 9ac99fda Guido Trotter
    # This will only work if it was an FQDN, though.
5980 9ac99fda Guido Trotter
    fqdn_warn = False
5981 9ac99fda Guido Trotter
    if not instance_name:
5982 9ac99fda Guido Trotter
      fqdn_warn = True
5983 9ac99fda Guido Trotter
      instance_name = self.op.instance_name
5984 9ac99fda Guido Trotter
5985 72737a7f Iustin Pop
    exportlist = self.rpc.call_export_list(self.acquired_locks[
5986 72737a7f Iustin Pop
      locking.LEVEL_NODE])
5987 9ac99fda Guido Trotter
    found = False
5988 9ac99fda Guido Trotter
    for node in exportlist:
5989 781de953 Iustin Pop
      if exportlist[node].failed:
5990 25361b9a Iustin Pop
        self.LogWarning("Failed to query node %s, continuing" % node)
5991 781de953 Iustin Pop
        continue
5992 781de953 Iustin Pop
      if instance_name in exportlist[node].data:
5993 9ac99fda Guido Trotter
        found = True
5994 781de953 Iustin Pop
        result = self.rpc.call_export_remove(node, instance_name)
5995 781de953 Iustin Pop
        if result.failed or not result.data:
5996 9a4f63d1 Iustin Pop
          logging.error("Could not remove export for instance %s"
5997 9a4f63d1 Iustin Pop
                        " on node %s", instance_name, node)
5998 9ac99fda Guido Trotter
5999 9ac99fda Guido Trotter
    if fqdn_warn and not found:
6000 9ac99fda Guido Trotter
      feedback_fn("Export not found. If trying to remove an export belonging"
6001 9ac99fda Guido Trotter
                  " to a deleted instance please use its Fully Qualified"
6002 9ac99fda Guido Trotter
                  " Domain Name.")
6003 9ac99fda Guido Trotter
6004 9ac99fda Guido Trotter
6005 5c947f38 Iustin Pop
class TagsLU(NoHooksLU):
6006 5c947f38 Iustin Pop
  """Generic tags LU.
6007 5c947f38 Iustin Pop

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

6010 5c947f38 Iustin Pop
  """
6011 5c947f38 Iustin Pop
6012 8646adce Guido Trotter
  def ExpandNames(self):
6013 8646adce Guido Trotter
    self.needed_locks = {}
6014 8646adce Guido Trotter
    if self.op.kind == constants.TAG_NODE:
6015 5c947f38 Iustin Pop
      name = self.cfg.ExpandNodeName(self.op.name)
6016 5c947f38 Iustin Pop
      if name is None:
6017 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid node name (%s)" %
6018 3ecf6786 Iustin Pop
                                   (self.op.name,))
6019 5c947f38 Iustin Pop
      self.op.name = name
6020 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = name
6021 5c947f38 Iustin Pop
    elif self.op.kind == constants.TAG_INSTANCE:
6022 8f684e16 Iustin Pop
      name = self.cfg.ExpandInstanceName(self.op.name)
6023 5c947f38 Iustin Pop
      if name is None:
6024 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid instance name (%s)" %
6025 3ecf6786 Iustin Pop
                                   (self.op.name,))
6026 5c947f38 Iustin Pop
      self.op.name = name
6027 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = name
6028 8646adce Guido Trotter
6029 8646adce Guido Trotter
  def CheckPrereq(self):
6030 8646adce Guido Trotter
    """Check prerequisites.
6031 8646adce Guido Trotter

6032 8646adce Guido Trotter
    """
6033 8646adce Guido Trotter
    if self.op.kind == constants.TAG_CLUSTER:
6034 8646adce Guido Trotter
      self.target = self.cfg.GetClusterInfo()
6035 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_NODE:
6036 8646adce Guido Trotter
      self.target = self.cfg.GetNodeInfo(self.op.name)
6037 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_INSTANCE:
6038 8646adce Guido Trotter
      self.target = self.cfg.GetInstanceInfo(self.op.name)
6039 5c947f38 Iustin Pop
    else:
6040 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
6041 3ecf6786 Iustin Pop
                                 str(self.op.kind))
6042 5c947f38 Iustin Pop
6043 5c947f38 Iustin Pop
6044 5c947f38 Iustin Pop
class LUGetTags(TagsLU):
6045 5c947f38 Iustin Pop
  """Returns the tags of a given object.
6046 5c947f38 Iustin Pop

6047 5c947f38 Iustin Pop
  """
6048 5c947f38 Iustin Pop
  _OP_REQP = ["kind", "name"]
6049 8646adce Guido Trotter
  REQ_BGL = False
6050 5c947f38 Iustin Pop
6051 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
6052 5c947f38 Iustin Pop
    """Returns the tag list.
6053 5c947f38 Iustin Pop

6054 5c947f38 Iustin Pop
    """
6055 5d414478 Oleksiy Mishchenko
    return list(self.target.GetTags())
6056 5c947f38 Iustin Pop
6057 5c947f38 Iustin Pop
6058 73415719 Iustin Pop
class LUSearchTags(NoHooksLU):
6059 73415719 Iustin Pop
  """Searches the tags for a given pattern.
6060 73415719 Iustin Pop

6061 73415719 Iustin Pop
  """
6062 73415719 Iustin Pop
  _OP_REQP = ["pattern"]
6063 8646adce Guido Trotter
  REQ_BGL = False
6064 8646adce Guido Trotter
6065 8646adce Guido Trotter
  def ExpandNames(self):
6066 8646adce Guido Trotter
    self.needed_locks = {}
6067 73415719 Iustin Pop
6068 73415719 Iustin Pop
  def CheckPrereq(self):
6069 73415719 Iustin Pop
    """Check prerequisites.
6070 73415719 Iustin Pop

6071 73415719 Iustin Pop
    This checks the pattern passed for validity by compiling it.
6072 73415719 Iustin Pop

6073 73415719 Iustin Pop
    """
6074 73415719 Iustin Pop
    try:
6075 73415719 Iustin Pop
      self.re = re.compile(self.op.pattern)
6076 73415719 Iustin Pop
    except re.error, err:
6077 73415719 Iustin Pop
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
6078 73415719 Iustin Pop
                                 (self.op.pattern, err))
6079 73415719 Iustin Pop
6080 73415719 Iustin Pop
  def Exec(self, feedback_fn):
6081 73415719 Iustin Pop
    """Returns the tag list.
6082 73415719 Iustin Pop

6083 73415719 Iustin Pop
    """
6084 73415719 Iustin Pop
    cfg = self.cfg
6085 73415719 Iustin Pop
    tgts = [("/cluster", cfg.GetClusterInfo())]
6086 8646adce Guido Trotter
    ilist = cfg.GetAllInstancesInfo().values()
6087 73415719 Iustin Pop
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
6088 8646adce Guido Trotter
    nlist = cfg.GetAllNodesInfo().values()
6089 73415719 Iustin Pop
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
6090 73415719 Iustin Pop
    results = []
6091 73415719 Iustin Pop
    for path, target in tgts:
6092 73415719 Iustin Pop
      for tag in target.GetTags():
6093 73415719 Iustin Pop
        if self.re.search(tag):
6094 73415719 Iustin Pop
          results.append((path, tag))
6095 73415719 Iustin Pop
    return results
6096 73415719 Iustin Pop
6097 73415719 Iustin Pop
6098 f27302fa Iustin Pop
class LUAddTags(TagsLU):
6099 5c947f38 Iustin Pop
  """Sets a tag on a given object.
6100 5c947f38 Iustin Pop

6101 5c947f38 Iustin Pop
  """
6102 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
6103 8646adce Guido Trotter
  REQ_BGL = False
6104 5c947f38 Iustin Pop
6105 5c947f38 Iustin Pop
  def CheckPrereq(self):
6106 5c947f38 Iustin Pop
    """Check prerequisites.
6107 5c947f38 Iustin Pop

6108 5c947f38 Iustin Pop
    This checks the type and length of the tag name and value.
6109 5c947f38 Iustin Pop

6110 5c947f38 Iustin Pop
    """
6111 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
6112 f27302fa Iustin Pop
    for tag in self.op.tags:
6113 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
6114 5c947f38 Iustin Pop
6115 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
6116 5c947f38 Iustin Pop
    """Sets the tag.
6117 5c947f38 Iustin Pop

6118 5c947f38 Iustin Pop
    """
6119 5c947f38 Iustin Pop
    try:
6120 f27302fa Iustin Pop
      for tag in self.op.tags:
6121 f27302fa Iustin Pop
        self.target.AddTag(tag)
6122 5c947f38 Iustin Pop
    except errors.TagError, err:
6123 3ecf6786 Iustin Pop
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
6124 5c947f38 Iustin Pop
    try:
6125 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
6126 5c947f38 Iustin Pop
    except errors.ConfigurationError:
6127 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
6128 3ecf6786 Iustin Pop
                                " config file and the operation has been"
6129 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
6130 5c947f38 Iustin Pop
6131 5c947f38 Iustin Pop
6132 f27302fa Iustin Pop
class LUDelTags(TagsLU):
6133 f27302fa Iustin Pop
  """Delete a list of tags from a given object.
6134 5c947f38 Iustin Pop

6135 5c947f38 Iustin Pop
  """
6136 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
6137 8646adce Guido Trotter
  REQ_BGL = False
6138 5c947f38 Iustin Pop
6139 5c947f38 Iustin Pop
  def CheckPrereq(self):
6140 5c947f38 Iustin Pop
    """Check prerequisites.
6141 5c947f38 Iustin Pop

6142 5c947f38 Iustin Pop
    This checks that we have the given tag.
6143 5c947f38 Iustin Pop

6144 5c947f38 Iustin Pop
    """
6145 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
6146 f27302fa Iustin Pop
    for tag in self.op.tags:
6147 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
6148 f27302fa Iustin Pop
    del_tags = frozenset(self.op.tags)
6149 f27302fa Iustin Pop
    cur_tags = self.target.GetTags()
6150 f27302fa Iustin Pop
    if not del_tags <= cur_tags:
6151 f27302fa Iustin Pop
      diff_tags = del_tags - cur_tags
6152 f27302fa Iustin Pop
      diff_names = ["'%s'" % tag for tag in diff_tags]
6153 f27302fa Iustin Pop
      diff_names.sort()
6154 f27302fa Iustin Pop
      raise errors.OpPrereqError("Tag(s) %s not found" %
6155 f27302fa Iustin Pop
                                 (",".join(diff_names)))
6156 5c947f38 Iustin Pop
6157 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
6158 5c947f38 Iustin Pop
    """Remove the tag from the object.
6159 5c947f38 Iustin Pop

6160 5c947f38 Iustin Pop
    """
6161 f27302fa Iustin Pop
    for tag in self.op.tags:
6162 f27302fa Iustin Pop
      self.target.RemoveTag(tag)
6163 5c947f38 Iustin Pop
    try:
6164 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
6165 5c947f38 Iustin Pop
    except errors.ConfigurationError:
6166 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
6167 3ecf6786 Iustin Pop
                                " config file and the operation has been"
6168 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
6169 06009e27 Iustin Pop
6170 0eed6e61 Guido Trotter
6171 06009e27 Iustin Pop
class LUTestDelay(NoHooksLU):
6172 06009e27 Iustin Pop
  """Sleep for a specified amount of time.
6173 06009e27 Iustin Pop

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

6177 06009e27 Iustin Pop
  """
6178 06009e27 Iustin Pop
  _OP_REQP = ["duration", "on_master", "on_nodes"]
6179 fbe9022f Guido Trotter
  REQ_BGL = False
6180 06009e27 Iustin Pop
6181 fbe9022f Guido Trotter
  def ExpandNames(self):
6182 fbe9022f Guido Trotter
    """Expand names and set required locks.
6183 06009e27 Iustin Pop

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

6186 06009e27 Iustin Pop
    """
6187 fbe9022f Guido Trotter
    self.needed_locks = {}
6188 06009e27 Iustin Pop
    if self.op.on_nodes:
6189 fbe9022f Guido Trotter
      # _GetWantedNodes can be used here, but is not always appropriate to use
6190 fbe9022f Guido Trotter
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
6191 fbe9022f Guido Trotter
      # more information.
6192 06009e27 Iustin Pop
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
6193 fbe9022f Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
6194 fbe9022f Guido Trotter
6195 fbe9022f Guido Trotter
  def CheckPrereq(self):
6196 fbe9022f Guido Trotter
    """Check prerequisites.
6197 fbe9022f Guido Trotter

6198 fbe9022f Guido Trotter
    """
6199 06009e27 Iustin Pop
6200 06009e27 Iustin Pop
  def Exec(self, feedback_fn):
6201 06009e27 Iustin Pop
    """Do the actual sleep.
6202 06009e27 Iustin Pop

6203 06009e27 Iustin Pop
    """
6204 06009e27 Iustin Pop
    if self.op.on_master:
6205 06009e27 Iustin Pop
      if not utils.TestDelay(self.op.duration):
6206 06009e27 Iustin Pop
        raise errors.OpExecError("Error during master delay test")
6207 06009e27 Iustin Pop
    if self.op.on_nodes:
6208 72737a7f Iustin Pop
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
6209 06009e27 Iustin Pop
      if not result:
6210 06009e27 Iustin Pop
        raise errors.OpExecError("Complete failure from rpc call")
6211 06009e27 Iustin Pop
      for node, node_result in result.items():
6212 781de953 Iustin Pop
        node_result.Raise()
6213 781de953 Iustin Pop
        if not node_result.data:
6214 06009e27 Iustin Pop
          raise errors.OpExecError("Failure during rpc call to node %s,"
6215 781de953 Iustin Pop
                                   " result: %s" % (node, node_result.data))
6216 d61df03e Iustin Pop
6217 d61df03e Iustin Pop
6218 d1c2dd75 Iustin Pop
class IAllocator(object):
6219 d1c2dd75 Iustin Pop
  """IAllocator framework.
6220 d61df03e Iustin Pop

6221 d1c2dd75 Iustin Pop
  An IAllocator instance has three sets of attributes:
6222 d6a02168 Michael Hanselmann
    - cfg that is needed to query the cluster
6223 d1c2dd75 Iustin Pop
    - input data (all members of the _KEYS class attribute are required)
6224 d1c2dd75 Iustin Pop
    - four buffer attributes (in|out_data|text), that represent the
6225 d1c2dd75 Iustin Pop
      input (to the external script) in text and data structure format,
6226 d1c2dd75 Iustin Pop
      and the output from it, again in two formats
6227 d1c2dd75 Iustin Pop
    - the result variables from the script (success, info, nodes) for
6228 d1c2dd75 Iustin Pop
      easy usage
6229 d61df03e Iustin Pop

6230 d61df03e Iustin Pop
  """
6231 29859cb7 Iustin Pop
  _ALLO_KEYS = [
6232 d1c2dd75 Iustin Pop
    "mem_size", "disks", "disk_template",
6233 8cc7e742 Guido Trotter
    "os", "tags", "nics", "vcpus", "hypervisor",
6234 d1c2dd75 Iustin Pop
    ]
6235 29859cb7 Iustin Pop
  _RELO_KEYS = [
6236 29859cb7 Iustin Pop
    "relocate_from",
6237 29859cb7 Iustin Pop
    ]
6238 d1c2dd75 Iustin Pop
6239 72737a7f Iustin Pop
  def __init__(self, lu, mode, name, **kwargs):
6240 72737a7f Iustin Pop
    self.lu = lu
6241 d1c2dd75 Iustin Pop
    # init buffer variables
6242 d1c2dd75 Iustin Pop
    self.in_text = self.out_text = self.in_data = self.out_data = None
6243 d1c2dd75 Iustin Pop
    # init all input fields so that pylint is happy
6244 29859cb7 Iustin Pop
    self.mode = mode
6245 29859cb7 Iustin Pop
    self.name = name
6246 d1c2dd75 Iustin Pop
    self.mem_size = self.disks = self.disk_template = None
6247 d1c2dd75 Iustin Pop
    self.os = self.tags = self.nics = self.vcpus = None
6248 a0add446 Iustin Pop
    self.hypervisor = None
6249 29859cb7 Iustin Pop
    self.relocate_from = None
6250 27579978 Iustin Pop
    # computed fields
6251 27579978 Iustin Pop
    self.required_nodes = None
6252 d1c2dd75 Iustin Pop
    # init result fields
6253 d1c2dd75 Iustin Pop
    self.success = self.info = self.nodes = None
6254 29859cb7 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6255 29859cb7 Iustin Pop
      keyset = self._ALLO_KEYS
6256 29859cb7 Iustin Pop
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6257 29859cb7 Iustin Pop
      keyset = self._RELO_KEYS
6258 29859cb7 Iustin Pop
    else:
6259 29859cb7 Iustin Pop
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
6260 29859cb7 Iustin Pop
                                   " IAllocator" % self.mode)
6261 d1c2dd75 Iustin Pop
    for key in kwargs:
6262 29859cb7 Iustin Pop
      if key not in keyset:
6263 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
6264 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
6265 d1c2dd75 Iustin Pop
      setattr(self, key, kwargs[key])
6266 29859cb7 Iustin Pop
    for key in keyset:
6267 d1c2dd75 Iustin Pop
      if key not in kwargs:
6268 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Missing input parameter '%s' to"
6269 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
6270 d1c2dd75 Iustin Pop
    self._BuildInputData()
6271 d1c2dd75 Iustin Pop
6272 d1c2dd75 Iustin Pop
  def _ComputeClusterData(self):
6273 d1c2dd75 Iustin Pop
    """Compute the generic allocator input data.
6274 d1c2dd75 Iustin Pop

6275 d1c2dd75 Iustin Pop
    This is the data that is independent of the actual operation.
6276 d1c2dd75 Iustin Pop

6277 d1c2dd75 Iustin Pop
    """
6278 72737a7f Iustin Pop
    cfg = self.lu.cfg
6279 e69d05fd Iustin Pop
    cluster_info = cfg.GetClusterInfo()
6280 d1c2dd75 Iustin Pop
    # cluster data
6281 d1c2dd75 Iustin Pop
    data = {
6282 d1c2dd75 Iustin Pop
      "version": 1,
6283 72737a7f Iustin Pop
      "cluster_name": cfg.GetClusterName(),
6284 e69d05fd Iustin Pop
      "cluster_tags": list(cluster_info.GetTags()),
6285 e69d05fd Iustin Pop
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
6286 d1c2dd75 Iustin Pop
      # we don't have job IDs
6287 d61df03e Iustin Pop
      }
6288 b57e9819 Guido Trotter
    iinfo = cfg.GetAllInstancesInfo().values()
6289 b57e9819 Guido Trotter
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
6290 6286519f Iustin Pop
6291 d1c2dd75 Iustin Pop
    # node data
6292 d1c2dd75 Iustin Pop
    node_results = {}
6293 d1c2dd75 Iustin Pop
    node_list = cfg.GetNodeList()
6294 8cc7e742 Guido Trotter
6295 8cc7e742 Guido Trotter
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6296 a0add446 Iustin Pop
      hypervisor_name = self.hypervisor
6297 8cc7e742 Guido Trotter
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
6298 a0add446 Iustin Pop
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
6299 8cc7e742 Guido Trotter
6300 72737a7f Iustin Pop
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
6301 a0add446 Iustin Pop
                                           hypervisor_name)
6302 18640d69 Guido Trotter
    node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
6303 18640d69 Guido Trotter
                       cluster_info.enabled_hypervisors)
6304 d1c2dd75 Iustin Pop
    for nname in node_list:
6305 d1c2dd75 Iustin Pop
      ninfo = cfg.GetNodeInfo(nname)
6306 781de953 Iustin Pop
      node_data[nname].Raise()
6307 781de953 Iustin Pop
      if not isinstance(node_data[nname].data, dict):
6308 d1c2dd75 Iustin Pop
        raise errors.OpExecError("Can't get data for node %s" % nname)
6309 781de953 Iustin Pop
      remote_info = node_data[nname].data
6310 b2662e7f Iustin Pop
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
6311 4337cf1b Iustin Pop
                   'vg_size', 'vg_free', 'cpu_total']:
6312 d1c2dd75 Iustin Pop
        if attr not in remote_info:
6313 d1c2dd75 Iustin Pop
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
6314 d1c2dd75 Iustin Pop
                                   (nname, attr))
6315 d1c2dd75 Iustin Pop
        try:
6316 b2662e7f Iustin Pop
          remote_info[attr] = int(remote_info[attr])
6317 d1c2dd75 Iustin Pop
        except ValueError, err:
6318 d1c2dd75 Iustin Pop
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
6319 d1c2dd75 Iustin Pop
                                   " %s" % (nname, attr, str(err)))
6320 6286519f Iustin Pop
      # compute memory used by primary instances
6321 6286519f Iustin Pop
      i_p_mem = i_p_up_mem = 0
6322 338e51e8 Iustin Pop
      for iinfo, beinfo in i_list:
6323 6286519f Iustin Pop
        if iinfo.primary_node == nname:
6324 338e51e8 Iustin Pop
          i_p_mem += beinfo[constants.BE_MEMORY]
6325 18640d69 Guido Trotter
          if iinfo.name not in node_iinfo[nname]:
6326 18640d69 Guido Trotter
            i_used_mem = 0
6327 18640d69 Guido Trotter
          else:
6328 18640d69 Guido Trotter
            i_used_mem = int(node_iinfo[nname][iinfo.name]['memory'])
6329 18640d69 Guido Trotter
          i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
6330 18640d69 Guido Trotter
          remote_info['memory_free'] -= max(0, i_mem_diff)
6331 18640d69 Guido Trotter
6332 6286519f Iustin Pop
          if iinfo.status == "up":
6333 338e51e8 Iustin Pop
            i_p_up_mem += beinfo[constants.BE_MEMORY]
6334 6286519f Iustin Pop
6335 b2662e7f Iustin Pop
      # compute memory used by instances
6336 d1c2dd75 Iustin Pop
      pnr = {
6337 d1c2dd75 Iustin Pop
        "tags": list(ninfo.GetTags()),
6338 b2662e7f Iustin Pop
        "total_memory": remote_info['memory_total'],
6339 b2662e7f Iustin Pop
        "reserved_memory": remote_info['memory_dom0'],
6340 b2662e7f Iustin Pop
        "free_memory": remote_info['memory_free'],
6341 6286519f Iustin Pop
        "i_pri_memory": i_p_mem,
6342 6286519f Iustin Pop
        "i_pri_up_memory": i_p_up_mem,
6343 b2662e7f Iustin Pop
        "total_disk": remote_info['vg_size'],
6344 b2662e7f Iustin Pop
        "free_disk": remote_info['vg_free'],
6345 d1c2dd75 Iustin Pop
        "primary_ip": ninfo.primary_ip,
6346 d1c2dd75 Iustin Pop
        "secondary_ip": ninfo.secondary_ip,
6347 4337cf1b Iustin Pop
        "total_cpus": remote_info['cpu_total'],
6348 fc0fe88c Iustin Pop
        "offline": ninfo.offline,
6349 d1c2dd75 Iustin Pop
        }
6350 d1c2dd75 Iustin Pop
      node_results[nname] = pnr
6351 d1c2dd75 Iustin Pop
    data["nodes"] = node_results
6352 d1c2dd75 Iustin Pop
6353 d1c2dd75 Iustin Pop
    # instance data
6354 d1c2dd75 Iustin Pop
    instance_data = {}
6355 338e51e8 Iustin Pop
    for iinfo, beinfo in i_list:
6356 d1c2dd75 Iustin Pop
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
6357 d1c2dd75 Iustin Pop
                  for n in iinfo.nics]
6358 d1c2dd75 Iustin Pop
      pir = {
6359 d1c2dd75 Iustin Pop
        "tags": list(iinfo.GetTags()),
6360 d1c2dd75 Iustin Pop
        "should_run": iinfo.status == "up",
6361 338e51e8 Iustin Pop
        "vcpus": beinfo[constants.BE_VCPUS],
6362 338e51e8 Iustin Pop
        "memory": beinfo[constants.BE_MEMORY],
6363 d1c2dd75 Iustin Pop
        "os": iinfo.os,
6364 6b12959c Iustin Pop
        "nodes": list(iinfo.all_nodes),
6365 d1c2dd75 Iustin Pop
        "nics": nic_data,
6366 d1c2dd75 Iustin Pop
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
6367 d1c2dd75 Iustin Pop
        "disk_template": iinfo.disk_template,
6368 e69d05fd Iustin Pop
        "hypervisor": iinfo.hypervisor,
6369 d1c2dd75 Iustin Pop
        }
6370 768f0a80 Iustin Pop
      instance_data[iinfo.name] = pir
6371 d61df03e Iustin Pop
6372 d1c2dd75 Iustin Pop
    data["instances"] = instance_data
6373 d61df03e Iustin Pop
6374 d1c2dd75 Iustin Pop
    self.in_data = data
6375 d61df03e Iustin Pop
6376 d1c2dd75 Iustin Pop
  def _AddNewInstance(self):
6377 d1c2dd75 Iustin Pop
    """Add new instance data to allocator structure.
6378 d61df03e Iustin Pop

6379 d1c2dd75 Iustin Pop
    This in combination with _AllocatorGetClusterData will create the
6380 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
6381 d61df03e Iustin Pop

6382 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
6383 d1c2dd75 Iustin Pop
    done.
6384 d61df03e Iustin Pop

6385 d1c2dd75 Iustin Pop
    """
6386 d1c2dd75 Iustin Pop
    data = self.in_data
6387 d1c2dd75 Iustin Pop
    if len(self.disks) != 2:
6388 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Only two-disk configurations supported")
6389 d1c2dd75 Iustin Pop
6390 dafc7302 Guido Trotter
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
6391 d1c2dd75 Iustin Pop
6392 27579978 Iustin Pop
    if self.disk_template in constants.DTS_NET_MIRROR:
6393 27579978 Iustin Pop
      self.required_nodes = 2
6394 27579978 Iustin Pop
    else:
6395 27579978 Iustin Pop
      self.required_nodes = 1
6396 d1c2dd75 Iustin Pop
    request = {
6397 d1c2dd75 Iustin Pop
      "type": "allocate",
6398 d1c2dd75 Iustin Pop
      "name": self.name,
6399 d1c2dd75 Iustin Pop
      "disk_template": self.disk_template,
6400 d1c2dd75 Iustin Pop
      "tags": self.tags,
6401 d1c2dd75 Iustin Pop
      "os": self.os,
6402 d1c2dd75 Iustin Pop
      "vcpus": self.vcpus,
6403 d1c2dd75 Iustin Pop
      "memory": self.mem_size,
6404 d1c2dd75 Iustin Pop
      "disks": self.disks,
6405 d1c2dd75 Iustin Pop
      "disk_space_total": disk_space,
6406 d1c2dd75 Iustin Pop
      "nics": self.nics,
6407 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
6408 d1c2dd75 Iustin Pop
      }
6409 d1c2dd75 Iustin Pop
    data["request"] = request
6410 298fe380 Iustin Pop
6411 d1c2dd75 Iustin Pop
  def _AddRelocateInstance(self):
6412 d1c2dd75 Iustin Pop
    """Add relocate instance data to allocator structure.
6413 298fe380 Iustin Pop

6414 d1c2dd75 Iustin Pop
    This in combination with _IAllocatorGetClusterData will create the
6415 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
6416 d61df03e Iustin Pop

6417 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
6418 d1c2dd75 Iustin Pop
    done.
6419 d61df03e Iustin Pop

6420 d1c2dd75 Iustin Pop
    """
6421 72737a7f Iustin Pop
    instance = self.lu.cfg.GetInstanceInfo(self.name)
6422 27579978 Iustin Pop
    if instance is None:
6423 27579978 Iustin Pop
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
6424 27579978 Iustin Pop
                                   " IAllocator" % self.name)
6425 27579978 Iustin Pop
6426 27579978 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
6427 27579978 Iustin Pop
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
6428 27579978 Iustin Pop
6429 2a139bb0 Iustin Pop
    if len(instance.secondary_nodes) != 1:
6430 2a139bb0 Iustin Pop
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
6431 2a139bb0 Iustin Pop
6432 27579978 Iustin Pop
    self.required_nodes = 1
6433 dafc7302 Guido Trotter
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
6434 dafc7302 Guido Trotter
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
6435 27579978 Iustin Pop
6436 d1c2dd75 Iustin Pop
    request = {
6437 2a139bb0 Iustin Pop
      "type": "relocate",
6438 d1c2dd75 Iustin Pop
      "name": self.name,
6439 27579978 Iustin Pop
      "disk_space_total": disk_space,
6440 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
6441 29859cb7 Iustin Pop
      "relocate_from": self.relocate_from,
6442 d1c2dd75 Iustin Pop
      }
6443 27579978 Iustin Pop
    self.in_data["request"] = request
6444 d61df03e Iustin Pop
6445 d1c2dd75 Iustin Pop
  def _BuildInputData(self):
6446 d1c2dd75 Iustin Pop
    """Build input data structures.
6447 d61df03e Iustin Pop

6448 d1c2dd75 Iustin Pop
    """
6449 d1c2dd75 Iustin Pop
    self._ComputeClusterData()
6450 d61df03e Iustin Pop
6451 d1c2dd75 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
6452 d1c2dd75 Iustin Pop
      self._AddNewInstance()
6453 d1c2dd75 Iustin Pop
    else:
6454 d1c2dd75 Iustin Pop
      self._AddRelocateInstance()
6455 d61df03e Iustin Pop
6456 d1c2dd75 Iustin Pop
    self.in_text = serializer.Dump(self.in_data)
6457 d61df03e Iustin Pop
6458 72737a7f Iustin Pop
  def Run(self, name, validate=True, call_fn=None):
6459 d1c2dd75 Iustin Pop
    """Run an instance allocator and return the results.
6460 298fe380 Iustin Pop

6461 d1c2dd75 Iustin Pop
    """
6462 72737a7f Iustin Pop
    if call_fn is None:
6463 72737a7f Iustin Pop
      call_fn = self.lu.rpc.call_iallocator_runner
6464 d1c2dd75 Iustin Pop
    data = self.in_text
6465 298fe380 Iustin Pop
6466 72737a7f Iustin Pop
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
6467 781de953 Iustin Pop
    result.Raise()
6468 298fe380 Iustin Pop
6469 781de953 Iustin Pop
    if not isinstance(result.data, (list, tuple)) or len(result.data) != 4:
6470 8d528b7c Iustin Pop
      raise errors.OpExecError("Invalid result from master iallocator runner")
6471 8d528b7c Iustin Pop
6472 781de953 Iustin Pop
    rcode, stdout, stderr, fail = result.data
6473 8d528b7c Iustin Pop
6474 8d528b7c Iustin Pop
    if rcode == constants.IARUN_NOTFOUND:
6475 8d528b7c Iustin Pop
      raise errors.OpExecError("Can't find allocator '%s'" % name)
6476 8d528b7c Iustin Pop
    elif rcode == constants.IARUN_FAILURE:
6477 38206f3c Iustin Pop
      raise errors.OpExecError("Instance allocator call failed: %s,"
6478 38206f3c Iustin Pop
                               " output: %s" % (fail, stdout+stderr))
6479 8d528b7c Iustin Pop
    self.out_text = stdout
6480 d1c2dd75 Iustin Pop
    if validate:
6481 d1c2dd75 Iustin Pop
      self._ValidateResult()
6482 298fe380 Iustin Pop
6483 d1c2dd75 Iustin Pop
  def _ValidateResult(self):
6484 d1c2dd75 Iustin Pop
    """Process the allocator results.
6485 538475ca Iustin Pop

6486 d1c2dd75 Iustin Pop
    This will process and if successful save the result in
6487 d1c2dd75 Iustin Pop
    self.out_data and the other parameters.
6488 538475ca Iustin Pop

6489 d1c2dd75 Iustin Pop
    """
6490 d1c2dd75 Iustin Pop
    try:
6491 d1c2dd75 Iustin Pop
      rdict = serializer.Load(self.out_text)
6492 d1c2dd75 Iustin Pop
    except Exception, err:
6493 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
6494 d1c2dd75 Iustin Pop
6495 d1c2dd75 Iustin Pop
    if not isinstance(rdict, dict):
6496 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
6497 538475ca Iustin Pop
6498 d1c2dd75 Iustin Pop
    for key in "success", "info", "nodes":
6499 d1c2dd75 Iustin Pop
      if key not in rdict:
6500 d1c2dd75 Iustin Pop
        raise errors.OpExecError("Can't parse iallocator results:"
6501 d1c2dd75 Iustin Pop
                                 " missing key '%s'" % key)
6502 d1c2dd75 Iustin Pop
      setattr(self, key, rdict[key])
6503 538475ca Iustin Pop
6504 d1c2dd75 Iustin Pop
    if not isinstance(rdict["nodes"], list):
6505 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
6506 d1c2dd75 Iustin Pop
                               " is not a list")
6507 d1c2dd75 Iustin Pop
    self.out_data = rdict
6508 538475ca Iustin Pop
6509 538475ca Iustin Pop
6510 d61df03e Iustin Pop
class LUTestAllocator(NoHooksLU):
6511 d61df03e Iustin Pop
  """Run allocator tests.
6512 d61df03e Iustin Pop

6513 d61df03e Iustin Pop
  This LU runs the allocator tests
6514 d61df03e Iustin Pop

6515 d61df03e Iustin Pop
  """
6516 d61df03e Iustin Pop
  _OP_REQP = ["direction", "mode", "name"]
6517 d61df03e Iustin Pop
6518 d61df03e Iustin Pop
  def CheckPrereq(self):
6519 d61df03e Iustin Pop
    """Check prerequisites.
6520 d61df03e Iustin Pop

6521 d61df03e Iustin Pop
    This checks the opcode parameters depending on the director and mode test.
6522 d61df03e Iustin Pop

6523 d61df03e Iustin Pop
    """
6524 298fe380 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6525 d61df03e Iustin Pop
      for attr in ["name", "mem_size", "disks", "disk_template",
6526 d61df03e Iustin Pop
                   "os", "tags", "nics", "vcpus"]:
6527 d61df03e Iustin Pop
        if not hasattr(self.op, attr):
6528 d61df03e Iustin Pop
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
6529 d61df03e Iustin Pop
                                     attr)
6530 d61df03e Iustin Pop
      iname = self.cfg.ExpandInstanceName(self.op.name)
6531 d61df03e Iustin Pop
      if iname is not None:
6532 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
6533 d61df03e Iustin Pop
                                   iname)
6534 d61df03e Iustin Pop
      if not isinstance(self.op.nics, list):
6535 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'nics'")
6536 d61df03e Iustin Pop
      for row in self.op.nics:
6537 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
6538 d61df03e Iustin Pop
            "mac" not in row or
6539 d61df03e Iustin Pop
            "ip" not in row or
6540 d61df03e Iustin Pop
            "bridge" not in row):
6541 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
6542 d61df03e Iustin Pop
                                     " 'nics' parameter")
6543 d61df03e Iustin Pop
      if not isinstance(self.op.disks, list):
6544 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'disks'")
6545 298fe380 Iustin Pop
      if len(self.op.disks) != 2:
6546 298fe380 Iustin Pop
        raise errors.OpPrereqError("Only two-disk configurations supported")
6547 d61df03e Iustin Pop
      for row in self.op.disks:
6548 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
6549 d61df03e Iustin Pop
            "size" not in row or
6550 d61df03e Iustin Pop
            not isinstance(row["size"], int) or
6551 d61df03e Iustin Pop
            "mode" not in row or
6552 d61df03e Iustin Pop
            row["mode"] not in ['r', 'w']):
6553 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
6554 d61df03e Iustin Pop
                                     " 'disks' parameter")
6555 8cc7e742 Guido Trotter
      if self.op.hypervisor is None:
6556 8cc7e742 Guido Trotter
        self.op.hypervisor = self.cfg.GetHypervisorType()
6557 298fe380 Iustin Pop
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
6558 d61df03e Iustin Pop
      if not hasattr(self.op, "name"):
6559 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
6560 d61df03e Iustin Pop
      fname = self.cfg.ExpandInstanceName(self.op.name)
6561 d61df03e Iustin Pop
      if fname is None:
6562 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
6563 d61df03e Iustin Pop
                                   self.op.name)
6564 d61df03e Iustin Pop
      self.op.name = fname
6565 29859cb7 Iustin Pop
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
6566 d61df03e Iustin Pop
    else:
6567 d61df03e Iustin Pop
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
6568 d61df03e Iustin Pop
                                 self.op.mode)
6569 d61df03e Iustin Pop
6570 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
6571 298fe380 Iustin Pop
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
6572 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing allocator name")
6573 298fe380 Iustin Pop
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
6574 d61df03e Iustin Pop
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
6575 d61df03e Iustin Pop
                                 self.op.direction)
6576 d61df03e Iustin Pop
6577 d61df03e Iustin Pop
  def Exec(self, feedback_fn):
6578 d61df03e Iustin Pop
    """Run the allocator test.
6579 d61df03e Iustin Pop

6580 d61df03e Iustin Pop
    """
6581 29859cb7 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
6582 72737a7f Iustin Pop
      ial = IAllocator(self,
6583 29859cb7 Iustin Pop
                       mode=self.op.mode,
6584 29859cb7 Iustin Pop
                       name=self.op.name,
6585 29859cb7 Iustin Pop
                       mem_size=self.op.mem_size,
6586 29859cb7 Iustin Pop
                       disks=self.op.disks,
6587 29859cb7 Iustin Pop
                       disk_template=self.op.disk_template,
6588 29859cb7 Iustin Pop
                       os=self.op.os,
6589 29859cb7 Iustin Pop
                       tags=self.op.tags,
6590 29859cb7 Iustin Pop
                       nics=self.op.nics,
6591 29859cb7 Iustin Pop
                       vcpus=self.op.vcpus,
6592 8cc7e742 Guido Trotter
                       hypervisor=self.op.hypervisor,
6593 29859cb7 Iustin Pop
                       )
6594 29859cb7 Iustin Pop
    else:
6595 72737a7f Iustin Pop
      ial = IAllocator(self,
6596 29859cb7 Iustin Pop
                       mode=self.op.mode,
6597 29859cb7 Iustin Pop
                       name=self.op.name,
6598 29859cb7 Iustin Pop
                       relocate_from=list(self.relocate_from),
6599 29859cb7 Iustin Pop
                       )
6600 d61df03e Iustin Pop
6601 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
6602 d1c2dd75 Iustin Pop
      result = ial.in_text
6603 298fe380 Iustin Pop
    else:
6604 d1c2dd75 Iustin Pop
      ial.Run(self.op.allocator, validate=False)
6605 d1c2dd75 Iustin Pop
      result = ial.out_text
6606 298fe380 Iustin Pop
    return result