Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 6605411d

History | View | Annotate | Download (187.7 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 a8083063 Iustin Pop
36 a8083063 Iustin Pop
from ganeti import ssh
37 a8083063 Iustin Pop
from ganeti import logger
38 a8083063 Iustin Pop
from ganeti import utils
39 a8083063 Iustin Pop
from ganeti import errors
40 a8083063 Iustin Pop
from ganeti import hypervisor
41 6048c986 Guido Trotter
from ganeti import locking
42 a8083063 Iustin Pop
from ganeti import constants
43 a8083063 Iustin Pop
from ganeti import objects
44 a8083063 Iustin Pop
from ganeti import opcodes
45 8d14b30d Iustin Pop
from ganeti import serializer
46 d61df03e Iustin Pop
47 d61df03e Iustin Pop
48 a8083063 Iustin Pop
class LogicalUnit(object):
49 396e1b78 Michael Hanselmann
  """Logical Unit base class.
50 a8083063 Iustin Pop

51 a8083063 Iustin Pop
  Subclasses must follow these rules:
52 d465bdc8 Guido Trotter
    - implement ExpandNames
53 d465bdc8 Guido Trotter
    - implement CheckPrereq
54 a8083063 Iustin Pop
    - implement Exec
55 a8083063 Iustin Pop
    - implement BuildHooksEnv
56 a8083063 Iustin Pop
    - redefine HPATH and HTYPE
57 05f86716 Guido Trotter
    - optionally redefine their run requirements:
58 05f86716 Guido Trotter
        REQ_MASTER: the LU needs to run on the master node
59 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 a8083063 Iustin Pop
  REQ_MASTER = True
68 7e55040e Guido Trotter
  REQ_BGL = True
69 a8083063 Iustin Pop
70 72737a7f Iustin Pop
  def __init__(self, processor, op, context, rpc):
71 a8083063 Iustin Pop
    """Constructor for LogicalUnit.
72 a8083063 Iustin Pop

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

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

110 c92b310a Michael Hanselmann
    """
111 c92b310a Michael Hanselmann
    if not self.__ssh:
112 6b0469d2 Iustin Pop
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
113 c92b310a Michael Hanselmann
    return self.__ssh
114 c92b310a Michael Hanselmann
115 c92b310a Michael Hanselmann
  ssh = property(fget=__GetSSH)
116 c92b310a Michael Hanselmann
117 d465bdc8 Guido Trotter
  def ExpandNames(self):
118 d465bdc8 Guido Trotter
    """Expand names for this LU.
119 d465bdc8 Guido Trotter

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

280 c4a2fee1 Guido Trotter
    If should be called in DeclareLocks in a way similar to:
281 c4a2fee1 Guido Trotter

282 c4a2fee1 Guido Trotter
    if level == locking.LEVEL_NODE:
283 c4a2fee1 Guido Trotter
      self._LockInstancesNodes()
284 c4a2fee1 Guido Trotter

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

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

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

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

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

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

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

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

374 83120a01 Michael Hanselmann
  Args:
375 83120a01 Michael Hanselmann
    static: Static fields
376 83120a01 Michael Hanselmann
    dynamic: Dynamic fields
377 83120a01 Michael Hanselmann

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

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

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

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

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

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

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

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

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

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

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

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

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

606 a8083063 Iustin Pop
    This function checks to see if the required block devices are
607 a8083063 Iustin Pop
    available on the instance's node.
608 a8083063 Iustin Pop

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

643 a8083063 Iustin Pop
    The .os, .swap and backup volumes are ignored. All other volumes are
644 a8083063 Iustin Pop
    reported as unknown.
645 a8083063 Iustin Pop

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

660 a8083063 Iustin Pop
    This checks what instances are running but unknown to the cluster.
661 a8083063 Iustin Pop

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

675 2b3b6ddd Guido Trotter
    Check that if one single node dies we can still start all the instances it
676 2b3b6ddd Guido Trotter
    was primary for.
677 2b3b6ddd Guido Trotter

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

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

708 a8083063 Iustin Pop
    """
709 e54c4c5e Guido Trotter
    self.skip_set = frozenset(self.op.skip_checks)
710 e54c4c5e Guido Trotter
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
711 e54c4c5e Guido Trotter
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
712 a8083063 Iustin Pop
713 d8fff41c Guido Trotter
  def BuildHooksEnv(self):
714 d8fff41c Guido Trotter
    """Build hooks env.
715 d8fff41c Guido Trotter

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

719 d8fff41c Guido Trotter
    """
720 d8fff41c Guido Trotter
    all_nodes = self.cfg.GetNodeList()
721 d8fff41c Guido Trotter
    # TODO: populate the environment with useful information for verify hooks
722 d8fff41c Guido Trotter
    env = {}
723 d8fff41c Guido Trotter
    return env, [], all_nodes
724 d8fff41c Guido Trotter
725 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
726 a8083063 Iustin Pop
    """Verify integrity of cluster, performing various test on nodes.
727 a8083063 Iustin Pop

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

903 d8fff41c Guido Trotter
    Args:
904 d8fff41c Guido Trotter
      phase: the hooks phase that has just been run
905 d8fff41c Guido Trotter
      hooks_results: the results of the multi-node hooks rpc call
906 d8fff41c Guido Trotter
      feedback_fn: function to send feedback back to the caller
907 d8fff41c Guido Trotter
      lu_result: previous Exec result
908 d8fff41c Guido Trotter

909 d8fff41c Guido Trotter
    """
910 38206f3c Iustin Pop
    # We only really run POST phase hooks, and are only interested in
911 38206f3c Iustin Pop
    # their results
912 d8fff41c Guido Trotter
    if phase == constants.HOOKS_PHASE_POST:
913 d8fff41c Guido Trotter
      # Used to change hooks' output to proper indentation
914 d8fff41c Guido Trotter
      indent_re = re.compile('^', re.M)
915 d8fff41c Guido Trotter
      feedback_fn("* Hooks Results")
916 d8fff41c Guido Trotter
      if not hooks_results:
917 d8fff41c Guido Trotter
        feedback_fn("  - ERROR: general communication failure")
918 d8fff41c Guido Trotter
        lu_result = 1
919 d8fff41c Guido Trotter
      else:
920 d8fff41c Guido Trotter
        for node_name in hooks_results:
921 d8fff41c Guido Trotter
          show_node_header = True
922 d8fff41c Guido Trotter
          res = hooks_results[node_name]
923 d8fff41c Guido Trotter
          if res is False or not isinstance(res, list):
924 d8fff41c Guido Trotter
            feedback_fn("    Communication failure")
925 d8fff41c Guido Trotter
            lu_result = 1
926 d8fff41c Guido Trotter
            continue
927 d8fff41c Guido Trotter
          for script, hkr, output in res:
928 d8fff41c Guido Trotter
            if hkr == constants.HKR_FAIL:
929 d8fff41c Guido Trotter
              # The node header is only shown once, if there are
930 d8fff41c Guido Trotter
              # failing hooks on that node
931 d8fff41c Guido Trotter
              if show_node_header:
932 d8fff41c Guido Trotter
                feedback_fn("  Node %s:" % node_name)
933 d8fff41c Guido Trotter
                show_node_header = False
934 d8fff41c Guido Trotter
              feedback_fn("    ERROR: Script %s failed, output:" % script)
935 d8fff41c Guido Trotter
              output = indent_re.sub('      ', output)
936 d8fff41c Guido Trotter
              feedback_fn("%s" % output)
937 d8fff41c Guido Trotter
              lu_result = 1
938 d8fff41c Guido Trotter
939 d8fff41c Guido Trotter
      return lu_result
940 d8fff41c Guido Trotter
941 a8083063 Iustin Pop
942 2c95a8d4 Iustin Pop
class LUVerifyDisks(NoHooksLU):
943 2c95a8d4 Iustin Pop
  """Verifies the cluster disks status.
944 2c95a8d4 Iustin Pop

945 2c95a8d4 Iustin Pop
  """
946 2c95a8d4 Iustin Pop
  _OP_REQP = []
947 d4b9d97f Guido Trotter
  REQ_BGL = False
948 d4b9d97f Guido Trotter
949 d4b9d97f Guido Trotter
  def ExpandNames(self):
950 d4b9d97f Guido Trotter
    self.needed_locks = {
951 d4b9d97f Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
952 d4b9d97f Guido Trotter
      locking.LEVEL_INSTANCE: locking.ALL_SET,
953 d4b9d97f Guido Trotter
    }
954 d4b9d97f Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
955 2c95a8d4 Iustin Pop
956 2c95a8d4 Iustin Pop
  def CheckPrereq(self):
957 2c95a8d4 Iustin Pop
    """Check prerequisites.
958 2c95a8d4 Iustin Pop

959 2c95a8d4 Iustin Pop
    This has no prerequisites.
960 2c95a8d4 Iustin Pop

961 2c95a8d4 Iustin Pop
    """
962 2c95a8d4 Iustin Pop
    pass
963 2c95a8d4 Iustin Pop
964 2c95a8d4 Iustin Pop
  def Exec(self, feedback_fn):
965 2c95a8d4 Iustin Pop
    """Verify integrity of cluster disks.
966 2c95a8d4 Iustin Pop

967 2c95a8d4 Iustin Pop
    """
968 b63ed789 Iustin Pop
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
969 2c95a8d4 Iustin Pop
970 2c95a8d4 Iustin Pop
    vg_name = self.cfg.GetVGName()
971 2c95a8d4 Iustin Pop
    nodes = utils.NiceSort(self.cfg.GetNodeList())
972 2c95a8d4 Iustin Pop
    instances = [self.cfg.GetInstanceInfo(name)
973 2c95a8d4 Iustin Pop
                 for name in self.cfg.GetInstanceList()]
974 2c95a8d4 Iustin Pop
975 2c95a8d4 Iustin Pop
    nv_dict = {}
976 2c95a8d4 Iustin Pop
    for inst in instances:
977 2c95a8d4 Iustin Pop
      inst_lvs = {}
978 2c95a8d4 Iustin Pop
      if (inst.status != "up" or
979 2c95a8d4 Iustin Pop
          inst.disk_template not in constants.DTS_NET_MIRROR):
980 2c95a8d4 Iustin Pop
        continue
981 2c95a8d4 Iustin Pop
      inst.MapLVsByNode(inst_lvs)
982 2c95a8d4 Iustin Pop
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
983 2c95a8d4 Iustin Pop
      for node, vol_list in inst_lvs.iteritems():
984 2c95a8d4 Iustin Pop
        for vol in vol_list:
985 2c95a8d4 Iustin Pop
          nv_dict[(node, vol)] = inst
986 2c95a8d4 Iustin Pop
987 2c95a8d4 Iustin Pop
    if not nv_dict:
988 2c95a8d4 Iustin Pop
      return result
989 2c95a8d4 Iustin Pop
990 72737a7f Iustin Pop
    node_lvs = self.rpc.call_volume_list(nodes, vg_name)
991 2c95a8d4 Iustin Pop
992 2c95a8d4 Iustin Pop
    to_act = set()
993 2c95a8d4 Iustin Pop
    for node in nodes:
994 2c95a8d4 Iustin Pop
      # node_volume
995 2c95a8d4 Iustin Pop
      lvs = node_lvs[node]
996 2c95a8d4 Iustin Pop
997 b63ed789 Iustin Pop
      if isinstance(lvs, basestring):
998 b63ed789 Iustin Pop
        logger.Info("error enumerating LVs on node %s: %s" % (node, lvs))
999 b63ed789 Iustin Pop
        res_nlvm[node] = lvs
1000 b63ed789 Iustin Pop
      elif not isinstance(lvs, dict):
1001 2c95a8d4 Iustin Pop
        logger.Info("connection to node %s failed or invalid data returned" %
1002 2c95a8d4 Iustin Pop
                    (node,))
1003 2c95a8d4 Iustin Pop
        res_nodes.append(node)
1004 2c95a8d4 Iustin Pop
        continue
1005 2c95a8d4 Iustin Pop
1006 2c95a8d4 Iustin Pop
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1007 b63ed789 Iustin Pop
        inst = nv_dict.pop((node, lv_name), None)
1008 b63ed789 Iustin Pop
        if (not lv_online and inst is not None
1009 b63ed789 Iustin Pop
            and inst.name not in res_instances):
1010 b08d5a87 Iustin Pop
          res_instances.append(inst.name)
1011 2c95a8d4 Iustin Pop
1012 b63ed789 Iustin Pop
    # any leftover items in nv_dict are missing LVs, let's arrange the
1013 b63ed789 Iustin Pop
    # data better
1014 b63ed789 Iustin Pop
    for key, inst in nv_dict.iteritems():
1015 b63ed789 Iustin Pop
      if inst.name not in res_missing:
1016 b63ed789 Iustin Pop
        res_missing[inst.name] = []
1017 b63ed789 Iustin Pop
      res_missing[inst.name].append(key)
1018 b63ed789 Iustin Pop
1019 2c95a8d4 Iustin Pop
    return result
1020 2c95a8d4 Iustin Pop
1021 2c95a8d4 Iustin Pop
1022 07bd8a51 Iustin Pop
class LURenameCluster(LogicalUnit):
1023 07bd8a51 Iustin Pop
  """Rename the cluster.
1024 07bd8a51 Iustin Pop

1025 07bd8a51 Iustin Pop
  """
1026 07bd8a51 Iustin Pop
  HPATH = "cluster-rename"
1027 07bd8a51 Iustin Pop
  HTYPE = constants.HTYPE_CLUSTER
1028 07bd8a51 Iustin Pop
  _OP_REQP = ["name"]
1029 07bd8a51 Iustin Pop
1030 07bd8a51 Iustin Pop
  def BuildHooksEnv(self):
1031 07bd8a51 Iustin Pop
    """Build hooks env.
1032 07bd8a51 Iustin Pop

1033 07bd8a51 Iustin Pop
    """
1034 07bd8a51 Iustin Pop
    env = {
1035 d6a02168 Michael Hanselmann
      "OP_TARGET": self.cfg.GetClusterName(),
1036 07bd8a51 Iustin Pop
      "NEW_NAME": self.op.name,
1037 07bd8a51 Iustin Pop
      }
1038 d6a02168 Michael Hanselmann
    mn = self.cfg.GetMasterNode()
1039 07bd8a51 Iustin Pop
    return env, [mn], [mn]
1040 07bd8a51 Iustin Pop
1041 07bd8a51 Iustin Pop
  def CheckPrereq(self):
1042 07bd8a51 Iustin Pop
    """Verify that the passed name is a valid one.
1043 07bd8a51 Iustin Pop

1044 07bd8a51 Iustin Pop
    """
1045 89e1fc26 Iustin Pop
    hostname = utils.HostInfo(self.op.name)
1046 07bd8a51 Iustin Pop
1047 bcf043c9 Iustin Pop
    new_name = hostname.name
1048 bcf043c9 Iustin Pop
    self.ip = new_ip = hostname.ip
1049 d6a02168 Michael Hanselmann
    old_name = self.cfg.GetClusterName()
1050 d6a02168 Michael Hanselmann
    old_ip = self.cfg.GetMasterIP()
1051 07bd8a51 Iustin Pop
    if new_name == old_name and new_ip == old_ip:
1052 07bd8a51 Iustin Pop
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1053 07bd8a51 Iustin Pop
                                 " cluster has changed")
1054 07bd8a51 Iustin Pop
    if new_ip != old_ip:
1055 937f983d Guido Trotter
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
1056 07bd8a51 Iustin Pop
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1057 07bd8a51 Iustin Pop
                                   " reachable on the network. Aborting." %
1058 07bd8a51 Iustin Pop
                                   new_ip)
1059 07bd8a51 Iustin Pop
1060 07bd8a51 Iustin Pop
    self.op.name = new_name
1061 07bd8a51 Iustin Pop
1062 07bd8a51 Iustin Pop
  def Exec(self, feedback_fn):
1063 07bd8a51 Iustin Pop
    """Rename the cluster.
1064 07bd8a51 Iustin Pop

1065 07bd8a51 Iustin Pop
    """
1066 07bd8a51 Iustin Pop
    clustername = self.op.name
1067 07bd8a51 Iustin Pop
    ip = self.ip
1068 07bd8a51 Iustin Pop
1069 07bd8a51 Iustin Pop
    # shutdown the master IP
1070 d6a02168 Michael Hanselmann
    master = self.cfg.GetMasterNode()
1071 72737a7f Iustin Pop
    if not self.rpc.call_node_stop_master(master, False):
1072 07bd8a51 Iustin Pop
      raise errors.OpExecError("Could not disable the master role")
1073 07bd8a51 Iustin Pop
1074 07bd8a51 Iustin Pop
    try:
1075 07bd8a51 Iustin Pop
      # modify the sstore
1076 d6a02168 Michael Hanselmann
      # TODO: sstore
1077 07bd8a51 Iustin Pop
      ss.SetKey(ss.SS_MASTER_IP, ip)
1078 07bd8a51 Iustin Pop
      ss.SetKey(ss.SS_CLUSTER_NAME, clustername)
1079 07bd8a51 Iustin Pop
1080 07bd8a51 Iustin Pop
      # Distribute updated ss config to all nodes
1081 07bd8a51 Iustin Pop
      myself = self.cfg.GetNodeInfo(master)
1082 07bd8a51 Iustin Pop
      dist_nodes = self.cfg.GetNodeList()
1083 07bd8a51 Iustin Pop
      if myself.name in dist_nodes:
1084 07bd8a51 Iustin Pop
        dist_nodes.remove(myself.name)
1085 07bd8a51 Iustin Pop
1086 07bd8a51 Iustin Pop
      logger.Debug("Copying updated ssconf data to all nodes")
1087 07bd8a51 Iustin Pop
      for keyname in [ss.SS_CLUSTER_NAME, ss.SS_MASTER_IP]:
1088 07bd8a51 Iustin Pop
        fname = ss.KeyToFilename(keyname)
1089 72737a7f Iustin Pop
        result = self.rpc.call_upload_file(dist_nodes, fname)
1090 07bd8a51 Iustin Pop
        for to_node in dist_nodes:
1091 07bd8a51 Iustin Pop
          if not result[to_node]:
1092 07bd8a51 Iustin Pop
            logger.Error("copy of file %s to node %s failed" %
1093 07bd8a51 Iustin Pop
                         (fname, to_node))
1094 07bd8a51 Iustin Pop
    finally:
1095 72737a7f Iustin Pop
      if not self.rpc.call_node_start_master(master, False):
1096 f4bc1f2c Michael Hanselmann
        logger.Error("Could not re-enable the master role on the master,"
1097 f4bc1f2c Michael Hanselmann
                     " please restart manually.")
1098 07bd8a51 Iustin Pop
1099 07bd8a51 Iustin Pop
1100 8084f9f6 Manuel Franceschini
def _RecursiveCheckIfLVMBased(disk):
1101 8084f9f6 Manuel Franceschini
  """Check if the given disk or its children are lvm-based.
1102 8084f9f6 Manuel Franceschini

1103 8084f9f6 Manuel Franceschini
  Args:
1104 8084f9f6 Manuel Franceschini
    disk: ganeti.objects.Disk object
1105 8084f9f6 Manuel Franceschini

1106 8084f9f6 Manuel Franceschini
  Returns:
1107 8084f9f6 Manuel Franceschini
    boolean indicating whether a LD_LV dev_type was found or not
1108 8084f9f6 Manuel Franceschini

1109 8084f9f6 Manuel Franceschini
  """
1110 8084f9f6 Manuel Franceschini
  if disk.children:
1111 8084f9f6 Manuel Franceschini
    for chdisk in disk.children:
1112 8084f9f6 Manuel Franceschini
      if _RecursiveCheckIfLVMBased(chdisk):
1113 8084f9f6 Manuel Franceschini
        return True
1114 8084f9f6 Manuel Franceschini
  return disk.dev_type == constants.LD_LV
1115 8084f9f6 Manuel Franceschini
1116 8084f9f6 Manuel Franceschini
1117 8084f9f6 Manuel Franceschini
class LUSetClusterParams(LogicalUnit):
1118 8084f9f6 Manuel Franceschini
  """Change the parameters of the cluster.
1119 8084f9f6 Manuel Franceschini

1120 8084f9f6 Manuel Franceschini
  """
1121 8084f9f6 Manuel Franceschini
  HPATH = "cluster-modify"
1122 8084f9f6 Manuel Franceschini
  HTYPE = constants.HTYPE_CLUSTER
1123 8084f9f6 Manuel Franceschini
  _OP_REQP = []
1124 c53279cf Guido Trotter
  REQ_BGL = False
1125 c53279cf Guido Trotter
1126 c53279cf Guido Trotter
  def ExpandNames(self):
1127 c53279cf Guido Trotter
    # FIXME: in the future maybe other cluster params won't require checking on
1128 c53279cf Guido Trotter
    # all nodes to be modified.
1129 c53279cf Guido Trotter
    self.needed_locks = {
1130 c53279cf Guido Trotter
      locking.LEVEL_NODE: locking.ALL_SET,
1131 c53279cf Guido Trotter
    }
1132 c53279cf Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1133 8084f9f6 Manuel Franceschini
1134 8084f9f6 Manuel Franceschini
  def BuildHooksEnv(self):
1135 8084f9f6 Manuel Franceschini
    """Build hooks env.
1136 8084f9f6 Manuel Franceschini

1137 8084f9f6 Manuel Franceschini
    """
1138 8084f9f6 Manuel Franceschini
    env = {
1139 d6a02168 Michael Hanselmann
      "OP_TARGET": self.cfg.GetClusterName(),
1140 8084f9f6 Manuel Franceschini
      "NEW_VG_NAME": self.op.vg_name,
1141 8084f9f6 Manuel Franceschini
      }
1142 d6a02168 Michael Hanselmann
    mn = self.cfg.GetMasterNode()
1143 8084f9f6 Manuel Franceschini
    return env, [mn], [mn]
1144 8084f9f6 Manuel Franceschini
1145 8084f9f6 Manuel Franceschini
  def CheckPrereq(self):
1146 8084f9f6 Manuel Franceschini
    """Check prerequisites.
1147 8084f9f6 Manuel Franceschini

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

1151 8084f9f6 Manuel Franceschini
    """
1152 c53279cf Guido Trotter
    # FIXME: This only works because there is only one parameter that can be
1153 c53279cf Guido Trotter
    # changed or removed.
1154 8084f9f6 Manuel Franceschini
    if not self.op.vg_name:
1155 c53279cf Guido Trotter
      instances = self.cfg.GetAllInstancesInfo().values()
1156 8084f9f6 Manuel Franceschini
      for inst in instances:
1157 8084f9f6 Manuel Franceschini
        for disk in inst.disks:
1158 8084f9f6 Manuel Franceschini
          if _RecursiveCheckIfLVMBased(disk):
1159 8084f9f6 Manuel Franceschini
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1160 8084f9f6 Manuel Franceschini
                                       " lvm-based instances exist")
1161 8084f9f6 Manuel Franceschini
1162 8084f9f6 Manuel Franceschini
    # if vg_name not None, checks given volume group on all nodes
1163 8084f9f6 Manuel Franceschini
    if self.op.vg_name:
1164 c53279cf Guido Trotter
      node_list = self.acquired_locks[locking.LEVEL_NODE]
1165 72737a7f Iustin Pop
      vglist = self.rpc.call_vg_list(node_list)
1166 8084f9f6 Manuel Franceschini
      for node in node_list:
1167 8d1a2a64 Michael Hanselmann
        vgstatus = utils.CheckVolumeGroupSize(vglist[node], self.op.vg_name,
1168 8d1a2a64 Michael Hanselmann
                                              constants.MIN_VG_SIZE)
1169 8084f9f6 Manuel Franceschini
        if vgstatus:
1170 8084f9f6 Manuel Franceschini
          raise errors.OpPrereqError("Error on node '%s': %s" %
1171 8084f9f6 Manuel Franceschini
                                     (node, vgstatus))
1172 8084f9f6 Manuel Franceschini
1173 8084f9f6 Manuel Franceschini
  def Exec(self, feedback_fn):
1174 8084f9f6 Manuel Franceschini
    """Change the parameters of the cluster.
1175 8084f9f6 Manuel Franceschini

1176 8084f9f6 Manuel Franceschini
    """
1177 8084f9f6 Manuel Franceschini
    if self.op.vg_name != self.cfg.GetVGName():
1178 8084f9f6 Manuel Franceschini
      self.cfg.SetVGName(self.op.vg_name)
1179 8084f9f6 Manuel Franceschini
    else:
1180 8084f9f6 Manuel Franceschini
      feedback_fn("Cluster LVM configuration already in desired"
1181 8084f9f6 Manuel Franceschini
                  " state, not changing")
1182 8084f9f6 Manuel Franceschini
1183 8084f9f6 Manuel Franceschini
1184 b9bddb6b Iustin Pop
def _WaitForSync(lu, instance, oneshot=False, unlock=False):
1185 a8083063 Iustin Pop
  """Sleep and poll for an instance's disk to sync.
1186 a8083063 Iustin Pop

1187 a8083063 Iustin Pop
  """
1188 a8083063 Iustin Pop
  if not instance.disks:
1189 a8083063 Iustin Pop
    return True
1190 a8083063 Iustin Pop
1191 a8083063 Iustin Pop
  if not oneshot:
1192 b9bddb6b Iustin Pop
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1193 a8083063 Iustin Pop
1194 a8083063 Iustin Pop
  node = instance.primary_node
1195 a8083063 Iustin Pop
1196 a8083063 Iustin Pop
  for dev in instance.disks:
1197 b9bddb6b Iustin Pop
    lu.cfg.SetDiskID(dev, node)
1198 a8083063 Iustin Pop
1199 a8083063 Iustin Pop
  retries = 0
1200 a8083063 Iustin Pop
  while True:
1201 a8083063 Iustin Pop
    max_time = 0
1202 a8083063 Iustin Pop
    done = True
1203 a8083063 Iustin Pop
    cumul_degraded = False
1204 72737a7f Iustin Pop
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1205 a8083063 Iustin Pop
    if not rstats:
1206 b9bddb6b Iustin Pop
      lu.proc.LogWarning("Can't get any data from node %s" % node)
1207 a8083063 Iustin Pop
      retries += 1
1208 a8083063 Iustin Pop
      if retries >= 10:
1209 3ecf6786 Iustin Pop
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1210 3ecf6786 Iustin Pop
                                 " aborting." % node)
1211 a8083063 Iustin Pop
      time.sleep(6)
1212 a8083063 Iustin Pop
      continue
1213 a8083063 Iustin Pop
    retries = 0
1214 a8083063 Iustin Pop
    for i in range(len(rstats)):
1215 a8083063 Iustin Pop
      mstat = rstats[i]
1216 a8083063 Iustin Pop
      if mstat is None:
1217 b9bddb6b Iustin Pop
        lu.proc.LogWarning("Can't compute data for node %s/%s" %
1218 b9bddb6b Iustin Pop
                           (node, instance.disks[i].iv_name))
1219 a8083063 Iustin Pop
        continue
1220 0834c866 Iustin Pop
      # we ignore the ldisk parameter
1221 0834c866 Iustin Pop
      perc_done, est_time, is_degraded, _ = mstat
1222 a8083063 Iustin Pop
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1223 a8083063 Iustin Pop
      if perc_done is not None:
1224 a8083063 Iustin Pop
        done = False
1225 a8083063 Iustin Pop
        if est_time is not None:
1226 a8083063 Iustin Pop
          rem_time = "%d estimated seconds remaining" % est_time
1227 a8083063 Iustin Pop
          max_time = est_time
1228 a8083063 Iustin Pop
        else:
1229 a8083063 Iustin Pop
          rem_time = "no time estimate"
1230 b9bddb6b Iustin Pop
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
1231 b9bddb6b Iustin Pop
                        (instance.disks[i].iv_name, perc_done, rem_time))
1232 a8083063 Iustin Pop
    if done or oneshot:
1233 a8083063 Iustin Pop
      break
1234 a8083063 Iustin Pop
1235 d4fa5c23 Iustin Pop
    time.sleep(min(60, max_time))
1236 a8083063 Iustin Pop
1237 a8083063 Iustin Pop
  if done:
1238 b9bddb6b Iustin Pop
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1239 a8083063 Iustin Pop
  return not cumul_degraded
1240 a8083063 Iustin Pop
1241 a8083063 Iustin Pop
1242 b9bddb6b Iustin Pop
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
1243 a8083063 Iustin Pop
  """Check that mirrors are not degraded.
1244 a8083063 Iustin Pop

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

1249 a8083063 Iustin Pop
  """
1250 b9bddb6b Iustin Pop
  lu.cfg.SetDiskID(dev, node)
1251 0834c866 Iustin Pop
  if ldisk:
1252 0834c866 Iustin Pop
    idx = 6
1253 0834c866 Iustin Pop
  else:
1254 0834c866 Iustin Pop
    idx = 5
1255 a8083063 Iustin Pop
1256 a8083063 Iustin Pop
  result = True
1257 a8083063 Iustin Pop
  if on_primary or dev.AssembleOnSecondary():
1258 72737a7f Iustin Pop
    rstats = lu.rpc.call_blockdev_find(node, dev)
1259 a8083063 Iustin Pop
    if not rstats:
1260 aa9d0c32 Guido Trotter
      logger.ToStderr("Node %s: Disk degraded, not found or node down" % node)
1261 a8083063 Iustin Pop
      result = False
1262 a8083063 Iustin Pop
    else:
1263 0834c866 Iustin Pop
      result = result and (not rstats[idx])
1264 a8083063 Iustin Pop
  if dev.children:
1265 a8083063 Iustin Pop
    for child in dev.children:
1266 b9bddb6b Iustin Pop
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
1267 a8083063 Iustin Pop
1268 a8083063 Iustin Pop
  return result
1269 a8083063 Iustin Pop
1270 a8083063 Iustin Pop
1271 a8083063 Iustin Pop
class LUDiagnoseOS(NoHooksLU):
1272 a8083063 Iustin Pop
  """Logical unit for OS diagnose/query.
1273 a8083063 Iustin Pop

1274 a8083063 Iustin Pop
  """
1275 1f9430d6 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1276 6bf01bbb Guido Trotter
  REQ_BGL = False
1277 a8083063 Iustin Pop
1278 6bf01bbb Guido Trotter
  def ExpandNames(self):
1279 1f9430d6 Iustin Pop
    if self.op.names:
1280 1f9430d6 Iustin Pop
      raise errors.OpPrereqError("Selective OS query not supported")
1281 1f9430d6 Iustin Pop
1282 1f9430d6 Iustin Pop
    self.dynamic_fields = frozenset(["name", "valid", "node_status"])
1283 1f9430d6 Iustin Pop
    _CheckOutputFields(static=[],
1284 1f9430d6 Iustin Pop
                       dynamic=self.dynamic_fields,
1285 1f9430d6 Iustin Pop
                       selected=self.op.output_fields)
1286 1f9430d6 Iustin Pop
1287 6bf01bbb Guido Trotter
    # Lock all nodes, in shared mode
1288 6bf01bbb Guido Trotter
    self.needed_locks = {}
1289 6bf01bbb Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1290 e310b019 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1291 6bf01bbb Guido Trotter
1292 6bf01bbb Guido Trotter
  def CheckPrereq(self):
1293 6bf01bbb Guido Trotter
    """Check prerequisites.
1294 6bf01bbb Guido Trotter

1295 6bf01bbb Guido Trotter
    """
1296 6bf01bbb Guido Trotter
1297 1f9430d6 Iustin Pop
  @staticmethod
1298 1f9430d6 Iustin Pop
  def _DiagnoseByOS(node_list, rlist):
1299 1f9430d6 Iustin Pop
    """Remaps a per-node return list into an a per-os per-node dictionary
1300 1f9430d6 Iustin Pop

1301 1f9430d6 Iustin Pop
      Args:
1302 1f9430d6 Iustin Pop
        node_list: a list with the names of all nodes
1303 1f9430d6 Iustin Pop
        rlist: a map with node names as keys and OS objects as values
1304 1f9430d6 Iustin Pop

1305 1f9430d6 Iustin Pop
      Returns:
1306 1f9430d6 Iustin Pop
        map: a map with osnames as keys and as value another map, with
1307 1f9430d6 Iustin Pop
             nodes as
1308 1f9430d6 Iustin Pop
             keys and list of OS objects as values
1309 1f9430d6 Iustin Pop
             e.g. {"debian-etch": {"node1": [<object>,...],
1310 1f9430d6 Iustin Pop
                                   "node2": [<object>,]}
1311 1f9430d6 Iustin Pop
                  }
1312 1f9430d6 Iustin Pop

1313 1f9430d6 Iustin Pop
    """
1314 1f9430d6 Iustin Pop
    all_os = {}
1315 1f9430d6 Iustin Pop
    for node_name, nr in rlist.iteritems():
1316 1f9430d6 Iustin Pop
      if not nr:
1317 1f9430d6 Iustin Pop
        continue
1318 b4de68a9 Iustin Pop
      for os_obj in nr:
1319 b4de68a9 Iustin Pop
        if os_obj.name not in all_os:
1320 1f9430d6 Iustin Pop
          # build a list of nodes for this os containing empty lists
1321 1f9430d6 Iustin Pop
          # for each node in node_list
1322 b4de68a9 Iustin Pop
          all_os[os_obj.name] = {}
1323 1f9430d6 Iustin Pop
          for nname in node_list:
1324 b4de68a9 Iustin Pop
            all_os[os_obj.name][nname] = []
1325 b4de68a9 Iustin Pop
        all_os[os_obj.name][node_name].append(os_obj)
1326 1f9430d6 Iustin Pop
    return all_os
1327 a8083063 Iustin Pop
1328 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1329 a8083063 Iustin Pop
    """Compute the list of OSes.
1330 a8083063 Iustin Pop

1331 a8083063 Iustin Pop
    """
1332 6bf01bbb Guido Trotter
    node_list = self.acquired_locks[locking.LEVEL_NODE]
1333 72737a7f Iustin Pop
    node_data = self.rpc.call_os_diagnose(node_list)
1334 a8083063 Iustin Pop
    if node_data == False:
1335 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't gather the list of OSes")
1336 1f9430d6 Iustin Pop
    pol = self._DiagnoseByOS(node_list, node_data)
1337 1f9430d6 Iustin Pop
    output = []
1338 1f9430d6 Iustin Pop
    for os_name, os_data in pol.iteritems():
1339 1f9430d6 Iustin Pop
      row = []
1340 1f9430d6 Iustin Pop
      for field in self.op.output_fields:
1341 1f9430d6 Iustin Pop
        if field == "name":
1342 1f9430d6 Iustin Pop
          val = os_name
1343 1f9430d6 Iustin Pop
        elif field == "valid":
1344 1f9430d6 Iustin Pop
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1345 1f9430d6 Iustin Pop
        elif field == "node_status":
1346 1f9430d6 Iustin Pop
          val = {}
1347 1f9430d6 Iustin Pop
          for node_name, nos_list in os_data.iteritems():
1348 1f9430d6 Iustin Pop
            val[node_name] = [(v.status, v.path) for v in nos_list]
1349 1f9430d6 Iustin Pop
        else:
1350 1f9430d6 Iustin Pop
          raise errors.ParameterError(field)
1351 1f9430d6 Iustin Pop
        row.append(val)
1352 1f9430d6 Iustin Pop
      output.append(row)
1353 1f9430d6 Iustin Pop
1354 1f9430d6 Iustin Pop
    return output
1355 a8083063 Iustin Pop
1356 a8083063 Iustin Pop
1357 a8083063 Iustin Pop
class LURemoveNode(LogicalUnit):
1358 a8083063 Iustin Pop
  """Logical unit for removing a node.
1359 a8083063 Iustin Pop

1360 a8083063 Iustin Pop
  """
1361 a8083063 Iustin Pop
  HPATH = "node-remove"
1362 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1363 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1364 a8083063 Iustin Pop
1365 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1366 a8083063 Iustin Pop
    """Build hooks env.
1367 a8083063 Iustin Pop

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

1371 a8083063 Iustin Pop
    """
1372 396e1b78 Michael Hanselmann
    env = {
1373 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1374 396e1b78 Michael Hanselmann
      "NODE_NAME": self.op.node_name,
1375 396e1b78 Michael Hanselmann
      }
1376 a8083063 Iustin Pop
    all_nodes = self.cfg.GetNodeList()
1377 a8083063 Iustin Pop
    all_nodes.remove(self.op.node_name)
1378 396e1b78 Michael Hanselmann
    return env, all_nodes, all_nodes
1379 a8083063 Iustin Pop
1380 a8083063 Iustin Pop
  def CheckPrereq(self):
1381 a8083063 Iustin Pop
    """Check prerequisites.
1382 a8083063 Iustin Pop

1383 a8083063 Iustin Pop
    This checks:
1384 a8083063 Iustin Pop
     - the node exists in the configuration
1385 a8083063 Iustin Pop
     - it does not have primary or secondary instances
1386 a8083063 Iustin Pop
     - it's not the master
1387 a8083063 Iustin Pop

1388 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1389 a8083063 Iustin Pop

1390 a8083063 Iustin Pop
    """
1391 a8083063 Iustin Pop
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1392 a8083063 Iustin Pop
    if node is None:
1393 a02bc76e Iustin Pop
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1394 a8083063 Iustin Pop
1395 a8083063 Iustin Pop
    instance_list = self.cfg.GetInstanceList()
1396 a8083063 Iustin Pop
1397 d6a02168 Michael Hanselmann
    masternode = self.cfg.GetMasterNode()
1398 a8083063 Iustin Pop
    if node.name == masternode:
1399 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node is the master node,"
1400 3ecf6786 Iustin Pop
                                 " you need to failover first.")
1401 a8083063 Iustin Pop
1402 a8083063 Iustin Pop
    for instance_name in instance_list:
1403 a8083063 Iustin Pop
      instance = self.cfg.GetInstanceInfo(instance_name)
1404 a8083063 Iustin Pop
      if node.name == instance.primary_node:
1405 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Instance %s still running on the node,"
1406 3ecf6786 Iustin Pop
                                   " please remove first." % instance_name)
1407 a8083063 Iustin Pop
      if node.name in instance.secondary_nodes:
1408 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1409 3ecf6786 Iustin Pop
                                   " please remove first." % instance_name)
1410 a8083063 Iustin Pop
    self.op.node_name = node.name
1411 a8083063 Iustin Pop
    self.node = node
1412 a8083063 Iustin Pop
1413 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1414 a8083063 Iustin Pop
    """Removes the node from the cluster.
1415 a8083063 Iustin Pop

1416 a8083063 Iustin Pop
    """
1417 a8083063 Iustin Pop
    node = self.node
1418 a8083063 Iustin Pop
    logger.Info("stopping the node daemon and removing configs from node %s" %
1419 a8083063 Iustin Pop
                node.name)
1420 a8083063 Iustin Pop
1421 d8470559 Michael Hanselmann
    self.context.RemoveNode(node.name)
1422 a8083063 Iustin Pop
1423 72737a7f Iustin Pop
    self.rpc.call_node_leave_cluster(node.name)
1424 c8a0948f Michael Hanselmann
1425 a8083063 Iustin Pop
1426 a8083063 Iustin Pop
class LUQueryNodes(NoHooksLU):
1427 a8083063 Iustin Pop
  """Logical unit for querying nodes.
1428 a8083063 Iustin Pop

1429 a8083063 Iustin Pop
  """
1430 246e180a Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1431 35705d8f Guido Trotter
  REQ_BGL = False
1432 a8083063 Iustin Pop
1433 35705d8f Guido Trotter
  def ExpandNames(self):
1434 e8a4c138 Iustin Pop
    self.dynamic_fields = frozenset([
1435 e8a4c138 Iustin Pop
      "dtotal", "dfree",
1436 e8a4c138 Iustin Pop
      "mtotal", "mnode", "mfree",
1437 e8a4c138 Iustin Pop
      "bootid",
1438 e8a4c138 Iustin Pop
      "ctotal",
1439 e8a4c138 Iustin Pop
      ])
1440 a8083063 Iustin Pop
1441 c8d8b4c8 Iustin Pop
    self.static_fields = frozenset([
1442 c8d8b4c8 Iustin Pop
      "name", "pinst_cnt", "sinst_cnt",
1443 c8d8b4c8 Iustin Pop
      "pinst_list", "sinst_list",
1444 c8d8b4c8 Iustin Pop
      "pip", "sip", "tags",
1445 38d7239a Iustin Pop
      "serial_no",
1446 c8d8b4c8 Iustin Pop
      ])
1447 c8d8b4c8 Iustin Pop
1448 c8d8b4c8 Iustin Pop
    _CheckOutputFields(static=self.static_fields,
1449 dcb93971 Michael Hanselmann
                       dynamic=self.dynamic_fields,
1450 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
1451 a8083063 Iustin Pop
1452 35705d8f Guido Trotter
    self.needed_locks = {}
1453 35705d8f Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1454 c8d8b4c8 Iustin Pop
1455 c8d8b4c8 Iustin Pop
    if self.op.names:
1456 c8d8b4c8 Iustin Pop
      self.wanted = _GetWantedNodes(self, self.op.names)
1457 35705d8f Guido Trotter
    else:
1458 c8d8b4c8 Iustin Pop
      self.wanted = locking.ALL_SET
1459 c8d8b4c8 Iustin Pop
1460 c8d8b4c8 Iustin Pop
    self.do_locking = not self.static_fields.issuperset(self.op.output_fields)
1461 c8d8b4c8 Iustin Pop
    if self.do_locking:
1462 c8d8b4c8 Iustin Pop
      # if we don't request only static fields, we need to lock the nodes
1463 c8d8b4c8 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
1464 c8d8b4c8 Iustin Pop
1465 35705d8f Guido Trotter
1466 35705d8f Guido Trotter
  def CheckPrereq(self):
1467 35705d8f Guido Trotter
    """Check prerequisites.
1468 35705d8f Guido Trotter

1469 35705d8f Guido Trotter
    """
1470 c8d8b4c8 Iustin Pop
    # The validation of the node list is done in the _GetWantedNodes,
1471 c8d8b4c8 Iustin Pop
    # if non empty, and if empty, there's no validation to do
1472 c8d8b4c8 Iustin Pop
    pass
1473 a8083063 Iustin Pop
1474 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1475 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
1476 a8083063 Iustin Pop

1477 a8083063 Iustin Pop
    """
1478 c8d8b4c8 Iustin Pop
    all_info = self.cfg.GetAllNodesInfo()
1479 c8d8b4c8 Iustin Pop
    if self.do_locking:
1480 c8d8b4c8 Iustin Pop
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
1481 3fa93523 Guido Trotter
    elif self.wanted != locking.ALL_SET:
1482 3fa93523 Guido Trotter
      nodenames = self.wanted
1483 3fa93523 Guido Trotter
      missing = set(nodenames).difference(all_info.keys())
1484 3fa93523 Guido Trotter
      if missing:
1485 7b3a8fb5 Iustin Pop
        raise errors.OpExecError(
1486 3fa93523 Guido Trotter
          "Some nodes were removed before retrieving their data: %s" % missing)
1487 c8d8b4c8 Iustin Pop
    else:
1488 c8d8b4c8 Iustin Pop
      nodenames = all_info.keys()
1489 c1f1cbb2 Iustin Pop
1490 c1f1cbb2 Iustin Pop
    nodenames = utils.NiceSort(nodenames)
1491 c8d8b4c8 Iustin Pop
    nodelist = [all_info[name] for name in nodenames]
1492 a8083063 Iustin Pop
1493 a8083063 Iustin Pop
    # begin data gathering
1494 a8083063 Iustin Pop
1495 a8083063 Iustin Pop
    if self.dynamic_fields.intersection(self.op.output_fields):
1496 a8083063 Iustin Pop
      live_data = {}
1497 72737a7f Iustin Pop
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
1498 72737a7f Iustin Pop
                                          self.cfg.GetHypervisorType())
1499 a8083063 Iustin Pop
      for name in nodenames:
1500 a8083063 Iustin Pop
        nodeinfo = node_data.get(name, None)
1501 a8083063 Iustin Pop
        if nodeinfo:
1502 a8083063 Iustin Pop
          live_data[name] = {
1503 a8083063 Iustin Pop
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1504 a8083063 Iustin Pop
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1505 a8083063 Iustin Pop
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1506 a8083063 Iustin Pop
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1507 a8083063 Iustin Pop
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1508 e8a4c138 Iustin Pop
            "ctotal": utils.TryConvert(int, nodeinfo['cpu_total']),
1509 3ef10550 Michael Hanselmann
            "bootid": nodeinfo['bootid'],
1510 a8083063 Iustin Pop
            }
1511 a8083063 Iustin Pop
        else:
1512 a8083063 Iustin Pop
          live_data[name] = {}
1513 a8083063 Iustin Pop
    else:
1514 a8083063 Iustin Pop
      live_data = dict.fromkeys(nodenames, {})
1515 a8083063 Iustin Pop
1516 ec223efb Iustin Pop
    node_to_primary = dict([(name, set()) for name in nodenames])
1517 ec223efb Iustin Pop
    node_to_secondary = dict([(name, set()) for name in nodenames])
1518 a8083063 Iustin Pop
1519 ec223efb Iustin Pop
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1520 ec223efb Iustin Pop
                             "sinst_cnt", "sinst_list"))
1521 ec223efb Iustin Pop
    if inst_fields & frozenset(self.op.output_fields):
1522 a8083063 Iustin Pop
      instancelist = self.cfg.GetInstanceList()
1523 a8083063 Iustin Pop
1524 ec223efb Iustin Pop
      for instance_name in instancelist:
1525 ec223efb Iustin Pop
        inst = self.cfg.GetInstanceInfo(instance_name)
1526 ec223efb Iustin Pop
        if inst.primary_node in node_to_primary:
1527 ec223efb Iustin Pop
          node_to_primary[inst.primary_node].add(inst.name)
1528 ec223efb Iustin Pop
        for secnode in inst.secondary_nodes:
1529 ec223efb Iustin Pop
          if secnode in node_to_secondary:
1530 ec223efb Iustin Pop
            node_to_secondary[secnode].add(inst.name)
1531 a8083063 Iustin Pop
1532 a8083063 Iustin Pop
    # end data gathering
1533 a8083063 Iustin Pop
1534 a8083063 Iustin Pop
    output = []
1535 a8083063 Iustin Pop
    for node in nodelist:
1536 a8083063 Iustin Pop
      node_output = []
1537 a8083063 Iustin Pop
      for field in self.op.output_fields:
1538 a8083063 Iustin Pop
        if field == "name":
1539 a8083063 Iustin Pop
          val = node.name
1540 ec223efb Iustin Pop
        elif field == "pinst_list":
1541 ec223efb Iustin Pop
          val = list(node_to_primary[node.name])
1542 ec223efb Iustin Pop
        elif field == "sinst_list":
1543 ec223efb Iustin Pop
          val = list(node_to_secondary[node.name])
1544 ec223efb Iustin Pop
        elif field == "pinst_cnt":
1545 ec223efb Iustin Pop
          val = len(node_to_primary[node.name])
1546 ec223efb Iustin Pop
        elif field == "sinst_cnt":
1547 ec223efb Iustin Pop
          val = len(node_to_secondary[node.name])
1548 a8083063 Iustin Pop
        elif field == "pip":
1549 a8083063 Iustin Pop
          val = node.primary_ip
1550 a8083063 Iustin Pop
        elif field == "sip":
1551 a8083063 Iustin Pop
          val = node.secondary_ip
1552 130a6a6f Iustin Pop
        elif field == "tags":
1553 130a6a6f Iustin Pop
          val = list(node.GetTags())
1554 38d7239a Iustin Pop
        elif field == "serial_no":
1555 38d7239a Iustin Pop
          val = node.serial_no
1556 a8083063 Iustin Pop
        elif field in self.dynamic_fields:
1557 ec223efb Iustin Pop
          val = live_data[node.name].get(field, None)
1558 a8083063 Iustin Pop
        else:
1559 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
1560 a8083063 Iustin Pop
        node_output.append(val)
1561 a8083063 Iustin Pop
      output.append(node_output)
1562 a8083063 Iustin Pop
1563 a8083063 Iustin Pop
    return output
1564 a8083063 Iustin Pop
1565 a8083063 Iustin Pop
1566 dcb93971 Michael Hanselmann
class LUQueryNodeVolumes(NoHooksLU):
1567 dcb93971 Michael Hanselmann
  """Logical unit for getting volumes on node(s).
1568 dcb93971 Michael Hanselmann

1569 dcb93971 Michael Hanselmann
  """
1570 dcb93971 Michael Hanselmann
  _OP_REQP = ["nodes", "output_fields"]
1571 21a15682 Guido Trotter
  REQ_BGL = False
1572 21a15682 Guido Trotter
1573 21a15682 Guido Trotter
  def ExpandNames(self):
1574 21a15682 Guido Trotter
    _CheckOutputFields(static=["node"],
1575 21a15682 Guido Trotter
                       dynamic=["phys", "vg", "name", "size", "instance"],
1576 21a15682 Guido Trotter
                       selected=self.op.output_fields)
1577 21a15682 Guido Trotter
1578 21a15682 Guido Trotter
    self.needed_locks = {}
1579 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
1580 21a15682 Guido Trotter
    if not self.op.nodes:
1581 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1582 21a15682 Guido Trotter
    else:
1583 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
1584 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
1585 dcb93971 Michael Hanselmann
1586 dcb93971 Michael Hanselmann
  def CheckPrereq(self):
1587 dcb93971 Michael Hanselmann
    """Check prerequisites.
1588 dcb93971 Michael Hanselmann

1589 dcb93971 Michael Hanselmann
    This checks that the fields required are valid output fields.
1590 dcb93971 Michael Hanselmann

1591 dcb93971 Michael Hanselmann
    """
1592 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
1593 dcb93971 Michael Hanselmann
1594 dcb93971 Michael Hanselmann
  def Exec(self, feedback_fn):
1595 dcb93971 Michael Hanselmann
    """Computes the list of nodes and their attributes.
1596 dcb93971 Michael Hanselmann

1597 dcb93971 Michael Hanselmann
    """
1598 a7ba5e53 Iustin Pop
    nodenames = self.nodes
1599 72737a7f Iustin Pop
    volumes = self.rpc.call_node_volumes(nodenames)
1600 dcb93971 Michael Hanselmann
1601 dcb93971 Michael Hanselmann
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1602 dcb93971 Michael Hanselmann
             in self.cfg.GetInstanceList()]
1603 dcb93971 Michael Hanselmann
1604 dcb93971 Michael Hanselmann
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1605 dcb93971 Michael Hanselmann
1606 dcb93971 Michael Hanselmann
    output = []
1607 dcb93971 Michael Hanselmann
    for node in nodenames:
1608 37d19eb2 Michael Hanselmann
      if node not in volumes or not volumes[node]:
1609 37d19eb2 Michael Hanselmann
        continue
1610 37d19eb2 Michael Hanselmann
1611 dcb93971 Michael Hanselmann
      node_vols = volumes[node][:]
1612 dcb93971 Michael Hanselmann
      node_vols.sort(key=lambda vol: vol['dev'])
1613 dcb93971 Michael Hanselmann
1614 dcb93971 Michael Hanselmann
      for vol in node_vols:
1615 dcb93971 Michael Hanselmann
        node_output = []
1616 dcb93971 Michael Hanselmann
        for field in self.op.output_fields:
1617 dcb93971 Michael Hanselmann
          if field == "node":
1618 dcb93971 Michael Hanselmann
            val = node
1619 dcb93971 Michael Hanselmann
          elif field == "phys":
1620 dcb93971 Michael Hanselmann
            val = vol['dev']
1621 dcb93971 Michael Hanselmann
          elif field == "vg":
1622 dcb93971 Michael Hanselmann
            val = vol['vg']
1623 dcb93971 Michael Hanselmann
          elif field == "name":
1624 dcb93971 Michael Hanselmann
            val = vol['name']
1625 dcb93971 Michael Hanselmann
          elif field == "size":
1626 dcb93971 Michael Hanselmann
            val = int(float(vol['size']))
1627 dcb93971 Michael Hanselmann
          elif field == "instance":
1628 dcb93971 Michael Hanselmann
            for inst in ilist:
1629 dcb93971 Michael Hanselmann
              if node not in lv_by_node[inst]:
1630 dcb93971 Michael Hanselmann
                continue
1631 dcb93971 Michael Hanselmann
              if vol['name'] in lv_by_node[inst][node]:
1632 dcb93971 Michael Hanselmann
                val = inst.name
1633 dcb93971 Michael Hanselmann
                break
1634 dcb93971 Michael Hanselmann
            else:
1635 dcb93971 Michael Hanselmann
              val = '-'
1636 dcb93971 Michael Hanselmann
          else:
1637 3ecf6786 Iustin Pop
            raise errors.ParameterError(field)
1638 dcb93971 Michael Hanselmann
          node_output.append(str(val))
1639 dcb93971 Michael Hanselmann
1640 dcb93971 Michael Hanselmann
        output.append(node_output)
1641 dcb93971 Michael Hanselmann
1642 dcb93971 Michael Hanselmann
    return output
1643 dcb93971 Michael Hanselmann
1644 dcb93971 Michael Hanselmann
1645 a8083063 Iustin Pop
class LUAddNode(LogicalUnit):
1646 a8083063 Iustin Pop
  """Logical unit for adding node to the cluster.
1647 a8083063 Iustin Pop

1648 a8083063 Iustin Pop
  """
1649 a8083063 Iustin Pop
  HPATH = "node-add"
1650 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1651 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1652 a8083063 Iustin Pop
1653 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1654 a8083063 Iustin Pop
    """Build hooks env.
1655 a8083063 Iustin Pop

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

1658 a8083063 Iustin Pop
    """
1659 a8083063 Iustin Pop
    env = {
1660 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1661 a8083063 Iustin Pop
      "NODE_NAME": self.op.node_name,
1662 a8083063 Iustin Pop
      "NODE_PIP": self.op.primary_ip,
1663 a8083063 Iustin Pop
      "NODE_SIP": self.op.secondary_ip,
1664 a8083063 Iustin Pop
      }
1665 a8083063 Iustin Pop
    nodes_0 = self.cfg.GetNodeList()
1666 a8083063 Iustin Pop
    nodes_1 = nodes_0 + [self.op.node_name, ]
1667 a8083063 Iustin Pop
    return env, nodes_0, nodes_1
1668 a8083063 Iustin Pop
1669 a8083063 Iustin Pop
  def CheckPrereq(self):
1670 a8083063 Iustin Pop
    """Check prerequisites.
1671 a8083063 Iustin Pop

1672 a8083063 Iustin Pop
    This checks:
1673 a8083063 Iustin Pop
     - the new node is not already in the config
1674 a8083063 Iustin Pop
     - it is resolvable
1675 a8083063 Iustin Pop
     - its parameters (single/dual homed) matches the cluster
1676 a8083063 Iustin Pop

1677 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1678 a8083063 Iustin Pop

1679 a8083063 Iustin Pop
    """
1680 a8083063 Iustin Pop
    node_name = self.op.node_name
1681 a8083063 Iustin Pop
    cfg = self.cfg
1682 a8083063 Iustin Pop
1683 89e1fc26 Iustin Pop
    dns_data = utils.HostInfo(node_name)
1684 a8083063 Iustin Pop
1685 bcf043c9 Iustin Pop
    node = dns_data.name
1686 bcf043c9 Iustin Pop
    primary_ip = self.op.primary_ip = dns_data.ip
1687 a8083063 Iustin Pop
    secondary_ip = getattr(self.op, "secondary_ip", None)
1688 a8083063 Iustin Pop
    if secondary_ip is None:
1689 a8083063 Iustin Pop
      secondary_ip = primary_ip
1690 a8083063 Iustin Pop
    if not utils.IsValidIP(secondary_ip):
1691 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid secondary IP given")
1692 a8083063 Iustin Pop
    self.op.secondary_ip = secondary_ip
1693 e7c6e02b Michael Hanselmann
1694 a8083063 Iustin Pop
    node_list = cfg.GetNodeList()
1695 e7c6e02b Michael Hanselmann
    if not self.op.readd and node in node_list:
1696 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1697 e7c6e02b Michael Hanselmann
                                 node)
1698 e7c6e02b Michael Hanselmann
    elif self.op.readd and node not in node_list:
1699 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1700 a8083063 Iustin Pop
1701 a8083063 Iustin Pop
    for existing_node_name in node_list:
1702 a8083063 Iustin Pop
      existing_node = cfg.GetNodeInfo(existing_node_name)
1703 e7c6e02b Michael Hanselmann
1704 e7c6e02b Michael Hanselmann
      if self.op.readd and node == existing_node_name:
1705 e7c6e02b Michael Hanselmann
        if (existing_node.primary_ip != primary_ip or
1706 e7c6e02b Michael Hanselmann
            existing_node.secondary_ip != secondary_ip):
1707 e7c6e02b Michael Hanselmann
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
1708 e7c6e02b Michael Hanselmann
                                     " address configuration as before")
1709 e7c6e02b Michael Hanselmann
        continue
1710 e7c6e02b Michael Hanselmann
1711 a8083063 Iustin Pop
      if (existing_node.primary_ip == primary_ip or
1712 a8083063 Iustin Pop
          existing_node.secondary_ip == primary_ip or
1713 a8083063 Iustin Pop
          existing_node.primary_ip == secondary_ip or
1714 a8083063 Iustin Pop
          existing_node.secondary_ip == secondary_ip):
1715 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1716 3ecf6786 Iustin Pop
                                   " existing node %s" % existing_node.name)
1717 a8083063 Iustin Pop
1718 a8083063 Iustin Pop
    # check that the type of the node (single versus dual homed) is the
1719 a8083063 Iustin Pop
    # same as for the master
1720 d6a02168 Michael Hanselmann
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
1721 a8083063 Iustin Pop
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1722 a8083063 Iustin Pop
    newbie_singlehomed = secondary_ip == primary_ip
1723 a8083063 Iustin Pop
    if master_singlehomed != newbie_singlehomed:
1724 a8083063 Iustin Pop
      if master_singlehomed:
1725 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has no private ip but the"
1726 3ecf6786 Iustin Pop
                                   " new node has one")
1727 a8083063 Iustin Pop
      else:
1728 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has a private ip but the"
1729 3ecf6786 Iustin Pop
                                   " new node doesn't have one")
1730 a8083063 Iustin Pop
1731 a8083063 Iustin Pop
    # checks reachablity
1732 b15d625f Iustin Pop
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
1733 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node not reachable by ping")
1734 a8083063 Iustin Pop
1735 a8083063 Iustin Pop
    if not newbie_singlehomed:
1736 a8083063 Iustin Pop
      # check reachability from my secondary ip to newbie's secondary ip
1737 b15d625f Iustin Pop
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
1738 b15d625f Iustin Pop
                           source=myself.secondary_ip):
1739 f4bc1f2c Michael Hanselmann
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
1740 f4bc1f2c Michael Hanselmann
                                   " based ping to noded port")
1741 a8083063 Iustin Pop
1742 a8083063 Iustin Pop
    self.new_node = objects.Node(name=node,
1743 a8083063 Iustin Pop
                                 primary_ip=primary_ip,
1744 a8083063 Iustin Pop
                                 secondary_ip=secondary_ip)
1745 a8083063 Iustin Pop
1746 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1747 a8083063 Iustin Pop
    """Adds the new node to the cluster.
1748 a8083063 Iustin Pop

1749 a8083063 Iustin Pop
    """
1750 a8083063 Iustin Pop
    new_node = self.new_node
1751 a8083063 Iustin Pop
    node = new_node.name
1752 a8083063 Iustin Pop
1753 a8083063 Iustin Pop
    # check connectivity
1754 72737a7f Iustin Pop
    result = self.rpc.call_version([node])[node]
1755 a8083063 Iustin Pop
    if result:
1756 a8083063 Iustin Pop
      if constants.PROTOCOL_VERSION == result:
1757 a8083063 Iustin Pop
        logger.Info("communication to node %s fine, sw version %s match" %
1758 a8083063 Iustin Pop
                    (node, result))
1759 a8083063 Iustin Pop
      else:
1760 3ecf6786 Iustin Pop
        raise errors.OpExecError("Version mismatch master version %s,"
1761 3ecf6786 Iustin Pop
                                 " node version %s" %
1762 3ecf6786 Iustin Pop
                                 (constants.PROTOCOL_VERSION, result))
1763 a8083063 Iustin Pop
    else:
1764 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot get version from the new node")
1765 a8083063 Iustin Pop
1766 a8083063 Iustin Pop
    # setup ssh on node
1767 a8083063 Iustin Pop
    logger.Info("copy ssh key to node %s" % node)
1768 70d9e3d8 Iustin Pop
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1769 a8083063 Iustin Pop
    keyarray = []
1770 70d9e3d8 Iustin Pop
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
1771 70d9e3d8 Iustin Pop
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
1772 70d9e3d8 Iustin Pop
                priv_key, pub_key]
1773 a8083063 Iustin Pop
1774 a8083063 Iustin Pop
    for i in keyfiles:
1775 a8083063 Iustin Pop
      f = open(i, 'r')
1776 a8083063 Iustin Pop
      try:
1777 a8083063 Iustin Pop
        keyarray.append(f.read())
1778 a8083063 Iustin Pop
      finally:
1779 a8083063 Iustin Pop
        f.close()
1780 a8083063 Iustin Pop
1781 72737a7f Iustin Pop
    result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
1782 72737a7f Iustin Pop
                                    keyarray[2],
1783 72737a7f Iustin Pop
                                    keyarray[3], keyarray[4], keyarray[5])
1784 a8083063 Iustin Pop
1785 a8083063 Iustin Pop
    if not result:
1786 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
1787 a8083063 Iustin Pop
1788 a8083063 Iustin Pop
    # Add node to our /etc/hosts, and add key to known_hosts
1789 d9c02ca6 Michael Hanselmann
    utils.AddHostToEtcHosts(new_node.name)
1790 c8a0948f Michael Hanselmann
1791 a8083063 Iustin Pop
    if new_node.secondary_ip != new_node.primary_ip:
1792 caad16e2 Iustin Pop
      if not self.rpc.call_node_has_ip_address(new_node.name,
1793 caad16e2 Iustin Pop
                                               new_node.secondary_ip):
1794 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
1795 f4bc1f2c Michael Hanselmann
                                 " you gave (%s). Please fix and re-run this"
1796 f4bc1f2c Michael Hanselmann
                                 " command." % new_node.secondary_ip)
1797 a8083063 Iustin Pop
1798 d6a02168 Michael Hanselmann
    node_verify_list = [self.cfg.GetMasterNode()]
1799 5c0527ed Guido Trotter
    node_verify_param = {
1800 5c0527ed Guido Trotter
      'nodelist': [node],
1801 5c0527ed Guido Trotter
      # TODO: do a node-net-test as well?
1802 5c0527ed Guido Trotter
    }
1803 5c0527ed Guido Trotter
1804 72737a7f Iustin Pop
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
1805 72737a7f Iustin Pop
                                       self.cfg.GetClusterName())
1806 5c0527ed Guido Trotter
    for verifier in node_verify_list:
1807 5c0527ed Guido Trotter
      if not result[verifier]:
1808 5c0527ed Guido Trotter
        raise errors.OpExecError("Cannot communicate with %s's node daemon"
1809 5c0527ed Guido Trotter
                                 " for remote verification" % verifier)
1810 5c0527ed Guido Trotter
      if result[verifier]['nodelist']:
1811 5c0527ed Guido Trotter
        for failed in result[verifier]['nodelist']:
1812 5c0527ed Guido Trotter
          feedback_fn("ssh/hostname verification failed %s -> %s" %
1813 5c0527ed Guido Trotter
                      (verifier, result[verifier]['nodelist'][failed]))
1814 5c0527ed Guido Trotter
        raise errors.OpExecError("ssh/hostname verification failed.")
1815 ff98055b Iustin Pop
1816 a8083063 Iustin Pop
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1817 a8083063 Iustin Pop
    # including the node just added
1818 d6a02168 Michael Hanselmann
    myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
1819 102b115b Michael Hanselmann
    dist_nodes = self.cfg.GetNodeList()
1820 102b115b Michael Hanselmann
    if not self.op.readd:
1821 102b115b Michael Hanselmann
      dist_nodes.append(node)
1822 a8083063 Iustin Pop
    if myself.name in dist_nodes:
1823 a8083063 Iustin Pop
      dist_nodes.remove(myself.name)
1824 a8083063 Iustin Pop
1825 a8083063 Iustin Pop
    logger.Debug("Copying hosts and known_hosts to all nodes")
1826 107711b0 Michael Hanselmann
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
1827 72737a7f Iustin Pop
      result = self.rpc.call_upload_file(dist_nodes, fname)
1828 a8083063 Iustin Pop
      for to_node in dist_nodes:
1829 a8083063 Iustin Pop
        if not result[to_node]:
1830 a8083063 Iustin Pop
          logger.Error("copy of file %s to node %s failed" %
1831 a8083063 Iustin Pop
                       (fname, to_node))
1832 a8083063 Iustin Pop
1833 d6a02168 Michael Hanselmann
    to_copy = []
1834 00cd937c Iustin Pop
    if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors:
1835 2a6469d5 Alexander Schreiber
      to_copy.append(constants.VNC_PASSWORD_FILE)
1836 a8083063 Iustin Pop
    for fname in to_copy:
1837 72737a7f Iustin Pop
      result = self.rpc.call_upload_file([node], fname)
1838 b5602d15 Guido Trotter
      if not result[node]:
1839 a8083063 Iustin Pop
        logger.Error("could not copy file %s to node %s" % (fname, node))
1840 a8083063 Iustin Pop
1841 d8470559 Michael Hanselmann
    if self.op.readd:
1842 d8470559 Michael Hanselmann
      self.context.ReaddNode(new_node)
1843 d8470559 Michael Hanselmann
    else:
1844 d8470559 Michael Hanselmann
      self.context.AddNode(new_node)
1845 a8083063 Iustin Pop
1846 a8083063 Iustin Pop
1847 a8083063 Iustin Pop
class LUQueryClusterInfo(NoHooksLU):
1848 a8083063 Iustin Pop
  """Query cluster configuration.
1849 a8083063 Iustin Pop

1850 a8083063 Iustin Pop
  """
1851 a8083063 Iustin Pop
  _OP_REQP = []
1852 59322403 Iustin Pop
  REQ_MASTER = False
1853 642339cf Guido Trotter
  REQ_BGL = False
1854 642339cf Guido Trotter
1855 642339cf Guido Trotter
  def ExpandNames(self):
1856 642339cf Guido Trotter
    self.needed_locks = {}
1857 a8083063 Iustin Pop
1858 a8083063 Iustin Pop
  def CheckPrereq(self):
1859 a8083063 Iustin Pop
    """No prerequsites needed for this LU.
1860 a8083063 Iustin Pop

1861 a8083063 Iustin Pop
    """
1862 a8083063 Iustin Pop
    pass
1863 a8083063 Iustin Pop
1864 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1865 a8083063 Iustin Pop
    """Return cluster config.
1866 a8083063 Iustin Pop

1867 a8083063 Iustin Pop
    """
1868 a8083063 Iustin Pop
    result = {
1869 d6a02168 Michael Hanselmann
      "name": self.cfg.GetClusterName(),
1870 a8083063 Iustin Pop
      "software_version": constants.RELEASE_VERSION,
1871 a8083063 Iustin Pop
      "protocol_version": constants.PROTOCOL_VERSION,
1872 a8083063 Iustin Pop
      "config_version": constants.CONFIG_VERSION,
1873 a8083063 Iustin Pop
      "os_api_version": constants.OS_API_VERSION,
1874 a8083063 Iustin Pop
      "export_version": constants.EXPORT_VERSION,
1875 d6a02168 Michael Hanselmann
      "master": self.cfg.GetMasterNode(),
1876 a8083063 Iustin Pop
      "architecture": (platform.architecture()[0], platform.machine()),
1877 d6a02168 Michael Hanselmann
      "hypervisor_type": self.cfg.GetHypervisorType(),
1878 e69d05fd Iustin Pop
      "enabled_hypervisors": self.cfg.GetClusterInfo().enabled_hypervisors,
1879 a8083063 Iustin Pop
      }
1880 a8083063 Iustin Pop
1881 a8083063 Iustin Pop
    return result
1882 a8083063 Iustin Pop
1883 a8083063 Iustin Pop
1884 ae5849b5 Michael Hanselmann
class LUQueryConfigValues(NoHooksLU):
1885 ae5849b5 Michael Hanselmann
  """Return configuration values.
1886 a8083063 Iustin Pop

1887 a8083063 Iustin Pop
  """
1888 a8083063 Iustin Pop
  _OP_REQP = []
1889 642339cf Guido Trotter
  REQ_BGL = False
1890 642339cf Guido Trotter
1891 642339cf Guido Trotter
  def ExpandNames(self):
1892 642339cf Guido Trotter
    self.needed_locks = {}
1893 a8083063 Iustin Pop
1894 ae5849b5 Michael Hanselmann
    static_fields = ["cluster_name", "master_node"]
1895 ae5849b5 Michael Hanselmann
    _CheckOutputFields(static=static_fields,
1896 ae5849b5 Michael Hanselmann
                       dynamic=[],
1897 ae5849b5 Michael Hanselmann
                       selected=self.op.output_fields)
1898 ae5849b5 Michael Hanselmann
1899 a8083063 Iustin Pop
  def CheckPrereq(self):
1900 a8083063 Iustin Pop
    """No prerequisites.
1901 a8083063 Iustin Pop

1902 a8083063 Iustin Pop
    """
1903 a8083063 Iustin Pop
    pass
1904 a8083063 Iustin Pop
1905 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1906 a8083063 Iustin Pop
    """Dump a representation of the cluster config to the standard output.
1907 a8083063 Iustin Pop

1908 a8083063 Iustin Pop
    """
1909 ae5849b5 Michael Hanselmann
    values = []
1910 ae5849b5 Michael Hanselmann
    for field in self.op.output_fields:
1911 ae5849b5 Michael Hanselmann
      if field == "cluster_name":
1912 ae5849b5 Michael Hanselmann
        values.append(self.cfg.GetClusterName())
1913 ae5849b5 Michael Hanselmann
      elif field == "master_node":
1914 ae5849b5 Michael Hanselmann
        values.append(self.cfg.GetMasterNode())
1915 ae5849b5 Michael Hanselmann
      else:
1916 ae5849b5 Michael Hanselmann
        raise errors.ParameterError(field)
1917 ae5849b5 Michael Hanselmann
    return values
1918 a8083063 Iustin Pop
1919 a8083063 Iustin Pop
1920 a8083063 Iustin Pop
class LUActivateInstanceDisks(NoHooksLU):
1921 a8083063 Iustin Pop
  """Bring up an instance's disks.
1922 a8083063 Iustin Pop

1923 a8083063 Iustin Pop
  """
1924 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
1925 f22a8ba3 Guido Trotter
  REQ_BGL = False
1926 f22a8ba3 Guido Trotter
1927 f22a8ba3 Guido Trotter
  def ExpandNames(self):
1928 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
1929 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
1930 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1931 f22a8ba3 Guido Trotter
1932 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
1933 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
1934 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
1935 a8083063 Iustin Pop
1936 a8083063 Iustin Pop
  def CheckPrereq(self):
1937 a8083063 Iustin Pop
    """Check prerequisites.
1938 a8083063 Iustin Pop

1939 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
1940 a8083063 Iustin Pop

1941 a8083063 Iustin Pop
    """
1942 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
1943 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
1944 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
1945 a8083063 Iustin Pop
1946 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1947 a8083063 Iustin Pop
    """Activate the disks.
1948 a8083063 Iustin Pop

1949 a8083063 Iustin Pop
    """
1950 b9bddb6b Iustin Pop
    disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance)
1951 a8083063 Iustin Pop
    if not disks_ok:
1952 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot activate block devices")
1953 a8083063 Iustin Pop
1954 a8083063 Iustin Pop
    return disks_info
1955 a8083063 Iustin Pop
1956 a8083063 Iustin Pop
1957 b9bddb6b Iustin Pop
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False):
1958 a8083063 Iustin Pop
  """Prepare the block devices for an instance.
1959 a8083063 Iustin Pop

1960 a8083063 Iustin Pop
  This sets up the block devices on all nodes.
1961 a8083063 Iustin Pop

1962 a8083063 Iustin Pop
  Args:
1963 a8083063 Iustin Pop
    instance: a ganeti.objects.Instance object
1964 a8083063 Iustin Pop
    ignore_secondaries: if true, errors on secondary nodes won't result
1965 a8083063 Iustin Pop
                        in an error return from the function
1966 a8083063 Iustin Pop

1967 a8083063 Iustin Pop
  Returns:
1968 a8083063 Iustin Pop
    false if the operation failed
1969 a8083063 Iustin Pop
    list of (host, instance_visible_name, node_visible_name) if the operation
1970 a8083063 Iustin Pop
         suceeded with the mapping from node devices to instance devices
1971 a8083063 Iustin Pop
  """
1972 a8083063 Iustin Pop
  device_info = []
1973 a8083063 Iustin Pop
  disks_ok = True
1974 fdbd668d Iustin Pop
  iname = instance.name
1975 fdbd668d Iustin Pop
  # With the two passes mechanism we try to reduce the window of
1976 fdbd668d Iustin Pop
  # opportunity for the race condition of switching DRBD to primary
1977 fdbd668d Iustin Pop
  # before handshaking occured, but we do not eliminate it
1978 fdbd668d Iustin Pop
1979 fdbd668d Iustin Pop
  # The proper fix would be to wait (with some limits) until the
1980 fdbd668d Iustin Pop
  # connection has been made and drbd transitions from WFConnection
1981 fdbd668d Iustin Pop
  # into any other network-connected state (Connected, SyncTarget,
1982 fdbd668d Iustin Pop
  # SyncSource, etc.)
1983 fdbd668d Iustin Pop
1984 fdbd668d Iustin Pop
  # 1st pass, assemble on all nodes in secondary mode
1985 a8083063 Iustin Pop
  for inst_disk in instance.disks:
1986 a8083063 Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
1987 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(node_disk, node)
1988 72737a7f Iustin Pop
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
1989 a8083063 Iustin Pop
      if not result:
1990 f4bc1f2c Michael Hanselmann
        logger.Error("could not prepare block device %s on node %s"
1991 fdbd668d Iustin Pop
                     " (is_primary=False, pass=1)" % (inst_disk.iv_name, node))
1992 fdbd668d Iustin Pop
        if not ignore_secondaries:
1993 a8083063 Iustin Pop
          disks_ok = False
1994 fdbd668d Iustin Pop
1995 fdbd668d Iustin Pop
  # FIXME: race condition on drbd migration to primary
1996 fdbd668d Iustin Pop
1997 fdbd668d Iustin Pop
  # 2nd pass, do only the primary node
1998 fdbd668d Iustin Pop
  for inst_disk in instance.disks:
1999 fdbd668d Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2000 fdbd668d Iustin Pop
      if node != instance.primary_node:
2001 fdbd668d Iustin Pop
        continue
2002 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(node_disk, node)
2003 72737a7f Iustin Pop
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
2004 fdbd668d Iustin Pop
      if not result:
2005 fdbd668d Iustin Pop
        logger.Error("could not prepare block device %s on node %s"
2006 fdbd668d Iustin Pop
                     " (is_primary=True, pass=2)" % (inst_disk.iv_name, node))
2007 fdbd668d Iustin Pop
        disks_ok = False
2008 fdbd668d Iustin Pop
    device_info.append((instance.primary_node, inst_disk.iv_name, result))
2009 a8083063 Iustin Pop
2010 b352ab5b Iustin Pop
  # leave the disks configured for the primary node
2011 b352ab5b Iustin Pop
  # this is a workaround that would be fixed better by
2012 b352ab5b Iustin Pop
  # improving the logical/physical id handling
2013 b352ab5b Iustin Pop
  for disk in instance.disks:
2014 b9bddb6b Iustin Pop
    lu.cfg.SetDiskID(disk, instance.primary_node)
2015 b352ab5b Iustin Pop
2016 a8083063 Iustin Pop
  return disks_ok, device_info
2017 a8083063 Iustin Pop
2018 a8083063 Iustin Pop
2019 b9bddb6b Iustin Pop
def _StartInstanceDisks(lu, instance, force):
2020 3ecf6786 Iustin Pop
  """Start the disks of an instance.
2021 3ecf6786 Iustin Pop

2022 3ecf6786 Iustin Pop
  """
2023 b9bddb6b Iustin Pop
  disks_ok, dummy = _AssembleInstanceDisks(lu, instance,
2024 fe7b0351 Michael Hanselmann
                                           ignore_secondaries=force)
2025 fe7b0351 Michael Hanselmann
  if not disks_ok:
2026 b9bddb6b Iustin Pop
    _ShutdownInstanceDisks(lu, instance)
2027 fe7b0351 Michael Hanselmann
    if force is not None and not force:
2028 fe7b0351 Michael Hanselmann
      logger.Error("If the message above refers to a secondary node,"
2029 fe7b0351 Michael Hanselmann
                   " you can retry the operation using '--force'.")
2030 3ecf6786 Iustin Pop
    raise errors.OpExecError("Disk consistency error")
2031 fe7b0351 Michael Hanselmann
2032 fe7b0351 Michael Hanselmann
2033 a8083063 Iustin Pop
class LUDeactivateInstanceDisks(NoHooksLU):
2034 a8083063 Iustin Pop
  """Shutdown an instance's disks.
2035 a8083063 Iustin Pop

2036 a8083063 Iustin Pop
  """
2037 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2038 f22a8ba3 Guido Trotter
  REQ_BGL = False
2039 f22a8ba3 Guido Trotter
2040 f22a8ba3 Guido Trotter
  def ExpandNames(self):
2041 f22a8ba3 Guido Trotter
    self._ExpandAndLockInstance()
2042 f22a8ba3 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2043 f22a8ba3 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2044 f22a8ba3 Guido Trotter
2045 f22a8ba3 Guido Trotter
  def DeclareLocks(self, level):
2046 f22a8ba3 Guido Trotter
    if level == locking.LEVEL_NODE:
2047 f22a8ba3 Guido Trotter
      self._LockInstancesNodes()
2048 a8083063 Iustin Pop
2049 a8083063 Iustin Pop
  def CheckPrereq(self):
2050 a8083063 Iustin Pop
    """Check prerequisites.
2051 a8083063 Iustin Pop

2052 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2053 a8083063 Iustin Pop

2054 a8083063 Iustin Pop
    """
2055 f22a8ba3 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2056 f22a8ba3 Guido Trotter
    assert self.instance is not None, \
2057 f22a8ba3 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2058 a8083063 Iustin Pop
2059 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2060 a8083063 Iustin Pop
    """Deactivate the disks
2061 a8083063 Iustin Pop

2062 a8083063 Iustin Pop
    """
2063 a8083063 Iustin Pop
    instance = self.instance
2064 b9bddb6b Iustin Pop
    _SafeShutdownInstanceDisks(self, instance)
2065 a8083063 Iustin Pop
2066 a8083063 Iustin Pop
2067 b9bddb6b Iustin Pop
def _SafeShutdownInstanceDisks(lu, instance):
2068 155d6c75 Guido Trotter
  """Shutdown block devices of an instance.
2069 155d6c75 Guido Trotter

2070 155d6c75 Guido Trotter
  This function checks if an instance is running, before calling
2071 155d6c75 Guido Trotter
  _ShutdownInstanceDisks.
2072 155d6c75 Guido Trotter

2073 155d6c75 Guido Trotter
  """
2074 72737a7f Iustin Pop
  ins_l = lu.rpc.call_instance_list([instance.primary_node],
2075 72737a7f Iustin Pop
                                      [instance.hypervisor])
2076 155d6c75 Guido Trotter
  ins_l = ins_l[instance.primary_node]
2077 155d6c75 Guido Trotter
  if not type(ins_l) is list:
2078 155d6c75 Guido Trotter
    raise errors.OpExecError("Can't contact node '%s'" %
2079 155d6c75 Guido Trotter
                             instance.primary_node)
2080 155d6c75 Guido Trotter
2081 155d6c75 Guido Trotter
  if instance.name in ins_l:
2082 155d6c75 Guido Trotter
    raise errors.OpExecError("Instance is running, can't shutdown"
2083 155d6c75 Guido Trotter
                             " block devices.")
2084 155d6c75 Guido Trotter
2085 b9bddb6b Iustin Pop
  _ShutdownInstanceDisks(lu, instance)
2086 a8083063 Iustin Pop
2087 a8083063 Iustin Pop
2088 b9bddb6b Iustin Pop
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
2089 a8083063 Iustin Pop
  """Shutdown block devices of an instance.
2090 a8083063 Iustin Pop

2091 a8083063 Iustin Pop
  This does the shutdown on all nodes of the instance.
2092 a8083063 Iustin Pop

2093 a8083063 Iustin Pop
  If the ignore_primary is false, errors on the primary node are
2094 a8083063 Iustin Pop
  ignored.
2095 a8083063 Iustin Pop

2096 a8083063 Iustin Pop
  """
2097 a8083063 Iustin Pop
  result = True
2098 a8083063 Iustin Pop
  for disk in instance.disks:
2099 a8083063 Iustin Pop
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2100 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(top_disk, node)
2101 72737a7f Iustin Pop
      if not lu.rpc.call_blockdev_shutdown(node, top_disk):
2102 a8083063 Iustin Pop
        logger.Error("could not shutdown block device %s on node %s" %
2103 a8083063 Iustin Pop
                     (disk.iv_name, node))
2104 a8083063 Iustin Pop
        if not ignore_primary or node != instance.primary_node:
2105 a8083063 Iustin Pop
          result = False
2106 a8083063 Iustin Pop
  return result
2107 a8083063 Iustin Pop
2108 a8083063 Iustin Pop
2109 b9bddb6b Iustin Pop
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor):
2110 d4f16fd9 Iustin Pop
  """Checks if a node has enough free memory.
2111 d4f16fd9 Iustin Pop

2112 d4f16fd9 Iustin Pop
  This function check if a given node has the needed amount of free
2113 d4f16fd9 Iustin Pop
  memory. In case the node has less memory or we cannot get the
2114 d4f16fd9 Iustin Pop
  information from the node, this function raise an OpPrereqError
2115 d4f16fd9 Iustin Pop
  exception.
2116 d4f16fd9 Iustin Pop

2117 b9bddb6b Iustin Pop
  @type lu: C{LogicalUnit}
2118 b9bddb6b Iustin Pop
  @param lu: a logical unit from which we get configuration data
2119 e69d05fd Iustin Pop
  @type node: C{str}
2120 e69d05fd Iustin Pop
  @param node: the node to check
2121 e69d05fd Iustin Pop
  @type reason: C{str}
2122 e69d05fd Iustin Pop
  @param reason: string to use in the error message
2123 e69d05fd Iustin Pop
  @type requested: C{int}
2124 e69d05fd Iustin Pop
  @param requested: the amount of memory in MiB to check for
2125 e69d05fd Iustin Pop
  @type hypervisor: C{str}
2126 e69d05fd Iustin Pop
  @param hypervisor: the hypervisor to ask for memory stats
2127 e69d05fd Iustin Pop
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
2128 e69d05fd Iustin Pop
      we cannot check the node
2129 d4f16fd9 Iustin Pop

2130 d4f16fd9 Iustin Pop
  """
2131 72737a7f Iustin Pop
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor)
2132 d4f16fd9 Iustin Pop
  if not nodeinfo or not isinstance(nodeinfo, dict):
2133 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Could not contact node %s for resource"
2134 d4f16fd9 Iustin Pop
                             " information" % (node,))
2135 d4f16fd9 Iustin Pop
2136 d4f16fd9 Iustin Pop
  free_mem = nodeinfo[node].get('memory_free')
2137 d4f16fd9 Iustin Pop
  if not isinstance(free_mem, int):
2138 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2139 d4f16fd9 Iustin Pop
                             " was '%s'" % (node, free_mem))
2140 d4f16fd9 Iustin Pop
  if requested > free_mem:
2141 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2142 d4f16fd9 Iustin Pop
                             " needed %s MiB, available %s MiB" %
2143 d4f16fd9 Iustin Pop
                             (node, reason, requested, free_mem))
2144 d4f16fd9 Iustin Pop
2145 d4f16fd9 Iustin Pop
2146 a8083063 Iustin Pop
class LUStartupInstance(LogicalUnit):
2147 a8083063 Iustin Pop
  """Starts an instance.
2148 a8083063 Iustin Pop

2149 a8083063 Iustin Pop
  """
2150 a8083063 Iustin Pop
  HPATH = "instance-start"
2151 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2152 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "force"]
2153 e873317a Guido Trotter
  REQ_BGL = False
2154 e873317a Guido Trotter
2155 e873317a Guido Trotter
  def ExpandNames(self):
2156 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2157 e873317a Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2158 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2159 e873317a Guido Trotter
2160 e873317a Guido Trotter
  def DeclareLocks(self, level):
2161 e873317a Guido Trotter
    if level == locking.LEVEL_NODE:
2162 e873317a Guido Trotter
      self._LockInstancesNodes()
2163 a8083063 Iustin Pop
2164 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2165 a8083063 Iustin Pop
    """Build hooks env.
2166 a8083063 Iustin Pop

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

2169 a8083063 Iustin Pop
    """
2170 a8083063 Iustin Pop
    env = {
2171 a8083063 Iustin Pop
      "FORCE": self.op.force,
2172 a8083063 Iustin Pop
      }
2173 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2174 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2175 a8083063 Iustin Pop
          list(self.instance.secondary_nodes))
2176 a8083063 Iustin Pop
    return env, nl, nl
2177 a8083063 Iustin Pop
2178 a8083063 Iustin Pop
  def CheckPrereq(self):
2179 a8083063 Iustin Pop
    """Check prerequisites.
2180 a8083063 Iustin Pop

2181 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2182 a8083063 Iustin Pop

2183 a8083063 Iustin Pop
    """
2184 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2185 e873317a Guido Trotter
    assert self.instance is not None, \
2186 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2187 a8083063 Iustin Pop
2188 338e51e8 Iustin Pop
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2189 a8083063 Iustin Pop
    # check bridges existance
2190 b9bddb6b Iustin Pop
    _CheckInstanceBridgesExist(self, instance)
2191 a8083063 Iustin Pop
2192 b9bddb6b Iustin Pop
    _CheckNodeFreeMemory(self, instance.primary_node,
2193 d4f16fd9 Iustin Pop
                         "starting instance %s" % instance.name,
2194 338e51e8 Iustin Pop
                         bep[constants.BE_MEMORY], instance.hypervisor)
2195 d4f16fd9 Iustin Pop
2196 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2197 a8083063 Iustin Pop
    """Start the instance.
2198 a8083063 Iustin Pop

2199 a8083063 Iustin Pop
    """
2200 a8083063 Iustin Pop
    instance = self.instance
2201 a8083063 Iustin Pop
    force = self.op.force
2202 a8083063 Iustin Pop
    extra_args = getattr(self.op, "extra_args", "")
2203 a8083063 Iustin Pop
2204 fe482621 Iustin Pop
    self.cfg.MarkInstanceUp(instance.name)
2205 fe482621 Iustin Pop
2206 a8083063 Iustin Pop
    node_current = instance.primary_node
2207 a8083063 Iustin Pop
2208 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, instance, force)
2209 a8083063 Iustin Pop
2210 72737a7f Iustin Pop
    if not self.rpc.call_instance_start(node_current, instance, extra_args):
2211 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, instance)
2212 3ecf6786 Iustin Pop
      raise errors.OpExecError("Could not start instance")
2213 a8083063 Iustin Pop
2214 a8083063 Iustin Pop
2215 bf6929a2 Alexander Schreiber
class LURebootInstance(LogicalUnit):
2216 bf6929a2 Alexander Schreiber
  """Reboot an instance.
2217 bf6929a2 Alexander Schreiber

2218 bf6929a2 Alexander Schreiber
  """
2219 bf6929a2 Alexander Schreiber
  HPATH = "instance-reboot"
2220 bf6929a2 Alexander Schreiber
  HTYPE = constants.HTYPE_INSTANCE
2221 bf6929a2 Alexander Schreiber
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2222 e873317a Guido Trotter
  REQ_BGL = False
2223 e873317a Guido Trotter
2224 e873317a Guido Trotter
  def ExpandNames(self):
2225 0fcc5db3 Guido Trotter
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2226 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
2227 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL]:
2228 0fcc5db3 Guido Trotter
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2229 0fcc5db3 Guido Trotter
                                  (constants.INSTANCE_REBOOT_SOFT,
2230 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_HARD,
2231 0fcc5db3 Guido Trotter
                                   constants.INSTANCE_REBOOT_FULL))
2232 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2233 e873317a Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2234 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2235 e873317a Guido Trotter
2236 e873317a Guido Trotter
  def DeclareLocks(self, level):
2237 e873317a Guido Trotter
    if level == locking.LEVEL_NODE:
2238 849da276 Guido Trotter
      primary_only = not constants.INSTANCE_REBOOT_FULL
2239 849da276 Guido Trotter
      self._LockInstancesNodes(primary_only=primary_only)
2240 bf6929a2 Alexander Schreiber
2241 bf6929a2 Alexander Schreiber
  def BuildHooksEnv(self):
2242 bf6929a2 Alexander Schreiber
    """Build hooks env.
2243 bf6929a2 Alexander Schreiber

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

2246 bf6929a2 Alexander Schreiber
    """
2247 bf6929a2 Alexander Schreiber
    env = {
2248 bf6929a2 Alexander Schreiber
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2249 bf6929a2 Alexander Schreiber
      }
2250 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2251 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2252 bf6929a2 Alexander Schreiber
          list(self.instance.secondary_nodes))
2253 bf6929a2 Alexander Schreiber
    return env, nl, nl
2254 bf6929a2 Alexander Schreiber
2255 bf6929a2 Alexander Schreiber
  def CheckPrereq(self):
2256 bf6929a2 Alexander Schreiber
    """Check prerequisites.
2257 bf6929a2 Alexander Schreiber

2258 bf6929a2 Alexander Schreiber
    This checks that the instance is in the cluster.
2259 bf6929a2 Alexander Schreiber

2260 bf6929a2 Alexander Schreiber
    """
2261 e873317a Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2262 e873317a Guido Trotter
    assert self.instance is not None, \
2263 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2264 bf6929a2 Alexander Schreiber
2265 bf6929a2 Alexander Schreiber
    # check bridges existance
2266 b9bddb6b Iustin Pop
    _CheckInstanceBridgesExist(self, instance)
2267 bf6929a2 Alexander Schreiber
2268 bf6929a2 Alexander Schreiber
  def Exec(self, feedback_fn):
2269 bf6929a2 Alexander Schreiber
    """Reboot the instance.
2270 bf6929a2 Alexander Schreiber

2271 bf6929a2 Alexander Schreiber
    """
2272 bf6929a2 Alexander Schreiber
    instance = self.instance
2273 bf6929a2 Alexander Schreiber
    ignore_secondaries = self.op.ignore_secondaries
2274 bf6929a2 Alexander Schreiber
    reboot_type = self.op.reboot_type
2275 bf6929a2 Alexander Schreiber
    extra_args = getattr(self.op, "extra_args", "")
2276 bf6929a2 Alexander Schreiber
2277 bf6929a2 Alexander Schreiber
    node_current = instance.primary_node
2278 bf6929a2 Alexander Schreiber
2279 bf6929a2 Alexander Schreiber
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2280 bf6929a2 Alexander Schreiber
                       constants.INSTANCE_REBOOT_HARD]:
2281 72737a7f Iustin Pop
      if not self.rpc.call_instance_reboot(node_current, instance,
2282 72737a7f Iustin Pop
                                           reboot_type, extra_args):
2283 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("Could not reboot instance")
2284 bf6929a2 Alexander Schreiber
    else:
2285 72737a7f Iustin Pop
      if not self.rpc.call_instance_shutdown(node_current, instance):
2286 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("could not shutdown instance for full reboot")
2287 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, instance)
2288 b9bddb6b Iustin Pop
      _StartInstanceDisks(self, instance, ignore_secondaries)
2289 72737a7f Iustin Pop
      if not self.rpc.call_instance_start(node_current, instance, extra_args):
2290 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
2291 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("Could not start instance for full reboot")
2292 bf6929a2 Alexander Schreiber
2293 bf6929a2 Alexander Schreiber
    self.cfg.MarkInstanceUp(instance.name)
2294 bf6929a2 Alexander Schreiber
2295 bf6929a2 Alexander Schreiber
2296 a8083063 Iustin Pop
class LUShutdownInstance(LogicalUnit):
2297 a8083063 Iustin Pop
  """Shutdown an instance.
2298 a8083063 Iustin Pop

2299 a8083063 Iustin Pop
  """
2300 a8083063 Iustin Pop
  HPATH = "instance-stop"
2301 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2302 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2303 e873317a Guido Trotter
  REQ_BGL = False
2304 e873317a Guido Trotter
2305 e873317a Guido Trotter
  def ExpandNames(self):
2306 e873317a Guido Trotter
    self._ExpandAndLockInstance()
2307 e873317a Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2308 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2309 e873317a Guido Trotter
2310 e873317a Guido Trotter
  def DeclareLocks(self, level):
2311 e873317a Guido Trotter
    if level == locking.LEVEL_NODE:
2312 e873317a Guido Trotter
      self._LockInstancesNodes()
2313 a8083063 Iustin Pop
2314 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2315 a8083063 Iustin Pop
    """Build hooks env.
2316 a8083063 Iustin Pop

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

2319 a8083063 Iustin Pop
    """
2320 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2321 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2322 a8083063 Iustin Pop
          list(self.instance.secondary_nodes))
2323 a8083063 Iustin Pop
    return env, nl, nl
2324 a8083063 Iustin Pop
2325 a8083063 Iustin Pop
  def CheckPrereq(self):
2326 a8083063 Iustin Pop
    """Check prerequisites.
2327 a8083063 Iustin Pop

2328 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2329 a8083063 Iustin Pop

2330 a8083063 Iustin Pop
    """
2331 e873317a Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2332 e873317a Guido Trotter
    assert self.instance is not None, \
2333 e873317a Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2334 a8083063 Iustin Pop
2335 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2336 a8083063 Iustin Pop
    """Shutdown the instance.
2337 a8083063 Iustin Pop

2338 a8083063 Iustin Pop
    """
2339 a8083063 Iustin Pop
    instance = self.instance
2340 a8083063 Iustin Pop
    node_current = instance.primary_node
2341 fe482621 Iustin Pop
    self.cfg.MarkInstanceDown(instance.name)
2342 72737a7f Iustin Pop
    if not self.rpc.call_instance_shutdown(node_current, instance):
2343 a8083063 Iustin Pop
      logger.Error("could not shutdown instance")
2344 a8083063 Iustin Pop
2345 b9bddb6b Iustin Pop
    _ShutdownInstanceDisks(self, instance)
2346 a8083063 Iustin Pop
2347 a8083063 Iustin Pop
2348 fe7b0351 Michael Hanselmann
class LUReinstallInstance(LogicalUnit):
2349 fe7b0351 Michael Hanselmann
  """Reinstall an instance.
2350 fe7b0351 Michael Hanselmann

2351 fe7b0351 Michael Hanselmann
  """
2352 fe7b0351 Michael Hanselmann
  HPATH = "instance-reinstall"
2353 fe7b0351 Michael Hanselmann
  HTYPE = constants.HTYPE_INSTANCE
2354 fe7b0351 Michael Hanselmann
  _OP_REQP = ["instance_name"]
2355 4e0b4d2d Guido Trotter
  REQ_BGL = False
2356 4e0b4d2d Guido Trotter
2357 4e0b4d2d Guido Trotter
  def ExpandNames(self):
2358 4e0b4d2d Guido Trotter
    self._ExpandAndLockInstance()
2359 4e0b4d2d Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2360 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2361 4e0b4d2d Guido Trotter
2362 4e0b4d2d Guido Trotter
  def DeclareLocks(self, level):
2363 4e0b4d2d Guido Trotter
    if level == locking.LEVEL_NODE:
2364 4e0b4d2d Guido Trotter
      self._LockInstancesNodes()
2365 fe7b0351 Michael Hanselmann
2366 fe7b0351 Michael Hanselmann
  def BuildHooksEnv(self):
2367 fe7b0351 Michael Hanselmann
    """Build hooks env.
2368 fe7b0351 Michael Hanselmann

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

2371 fe7b0351 Michael Hanselmann
    """
2372 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2373 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2374 fe7b0351 Michael Hanselmann
          list(self.instance.secondary_nodes))
2375 fe7b0351 Michael Hanselmann
    return env, nl, nl
2376 fe7b0351 Michael Hanselmann
2377 fe7b0351 Michael Hanselmann
  def CheckPrereq(self):
2378 fe7b0351 Michael Hanselmann
    """Check prerequisites.
2379 fe7b0351 Michael Hanselmann

2380 fe7b0351 Michael Hanselmann
    This checks that the instance is in the cluster and is not running.
2381 fe7b0351 Michael Hanselmann

2382 fe7b0351 Michael Hanselmann
    """
2383 4e0b4d2d Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2384 4e0b4d2d Guido Trotter
    assert instance is not None, \
2385 4e0b4d2d Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2386 4e0b4d2d Guido Trotter
2387 fe7b0351 Michael Hanselmann
    if instance.disk_template == constants.DT_DISKLESS:
2388 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2389 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2390 fe7b0351 Michael Hanselmann
    if instance.status != "down":
2391 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2392 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2393 72737a7f Iustin Pop
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2394 72737a7f Iustin Pop
                                              instance.name,
2395 72737a7f Iustin Pop
                                              instance.hypervisor)
2396 fe7b0351 Michael Hanselmann
    if remote_info:
2397 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2398 3ecf6786 Iustin Pop
                                 (self.op.instance_name,
2399 3ecf6786 Iustin Pop
                                  instance.primary_node))
2400 d0834de3 Michael Hanselmann
2401 d0834de3 Michael Hanselmann
    self.op.os_type = getattr(self.op, "os_type", None)
2402 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2403 d0834de3 Michael Hanselmann
      # OS verification
2404 d0834de3 Michael Hanselmann
      pnode = self.cfg.GetNodeInfo(
2405 d0834de3 Michael Hanselmann
        self.cfg.ExpandNodeName(instance.primary_node))
2406 d0834de3 Michael Hanselmann
      if pnode is None:
2407 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2408 3ecf6786 Iustin Pop
                                   self.op.pnode)
2409 72737a7f Iustin Pop
      os_obj = self.rpc.call_os_get(pnode.name, self.op.os_type)
2410 dfa96ded Guido Trotter
      if not os_obj:
2411 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2412 3ecf6786 Iustin Pop
                                   " primary node"  % self.op.os_type)
2413 d0834de3 Michael Hanselmann
2414 fe7b0351 Michael Hanselmann
    self.instance = instance
2415 fe7b0351 Michael Hanselmann
2416 fe7b0351 Michael Hanselmann
  def Exec(self, feedback_fn):
2417 fe7b0351 Michael Hanselmann
    """Reinstall the instance.
2418 fe7b0351 Michael Hanselmann

2419 fe7b0351 Michael Hanselmann
    """
2420 fe7b0351 Michael Hanselmann
    inst = self.instance
2421 fe7b0351 Michael Hanselmann
2422 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2423 d0834de3 Michael Hanselmann
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2424 d0834de3 Michael Hanselmann
      inst.os = self.op.os_type
2425 97abc79f Iustin Pop
      self.cfg.Update(inst)
2426 d0834de3 Michael Hanselmann
2427 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, inst, None)
2428 fe7b0351 Michael Hanselmann
    try:
2429 fe7b0351 Michael Hanselmann
      feedback_fn("Running the instance OS create scripts...")
2430 72737a7f Iustin Pop
      if not self.rpc.call_instance_os_add(inst.primary_node, inst,
2431 72737a7f Iustin Pop
                                           "sda", "sdb"):
2432 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Could not install OS for instance %s"
2433 f4bc1f2c Michael Hanselmann
                                 " on node %s" %
2434 3ecf6786 Iustin Pop
                                 (inst.name, inst.primary_node))
2435 fe7b0351 Michael Hanselmann
    finally:
2436 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, inst)
2437 fe7b0351 Michael Hanselmann
2438 fe7b0351 Michael Hanselmann
2439 decd5f45 Iustin Pop
class LURenameInstance(LogicalUnit):
2440 decd5f45 Iustin Pop
  """Rename an instance.
2441 decd5f45 Iustin Pop

2442 decd5f45 Iustin Pop
  """
2443 decd5f45 Iustin Pop
  HPATH = "instance-rename"
2444 decd5f45 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2445 decd5f45 Iustin Pop
  _OP_REQP = ["instance_name", "new_name"]
2446 decd5f45 Iustin Pop
2447 decd5f45 Iustin Pop
  def BuildHooksEnv(self):
2448 decd5f45 Iustin Pop
    """Build hooks env.
2449 decd5f45 Iustin Pop

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

2452 decd5f45 Iustin Pop
    """
2453 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2454 decd5f45 Iustin Pop
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2455 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] +
2456 decd5f45 Iustin Pop
          list(self.instance.secondary_nodes))
2457 decd5f45 Iustin Pop
    return env, nl, nl
2458 decd5f45 Iustin Pop
2459 decd5f45 Iustin Pop
  def CheckPrereq(self):
2460 decd5f45 Iustin Pop
    """Check prerequisites.
2461 decd5f45 Iustin Pop

2462 decd5f45 Iustin Pop
    This checks that the instance is in the cluster and is not running.
2463 decd5f45 Iustin Pop

2464 decd5f45 Iustin Pop
    """
2465 decd5f45 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2466 decd5f45 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2467 decd5f45 Iustin Pop
    if instance is None:
2468 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2469 decd5f45 Iustin Pop
                                 self.op.instance_name)
2470 decd5f45 Iustin Pop
    if instance.status != "down":
2471 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2472 decd5f45 Iustin Pop
                                 self.op.instance_name)
2473 72737a7f Iustin Pop
    remote_info = self.rpc.call_instance_info(instance.primary_node,
2474 72737a7f Iustin Pop
                                              instance.name,
2475 72737a7f Iustin Pop
                                              instance.hypervisor)
2476 decd5f45 Iustin Pop
    if remote_info:
2477 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2478 decd5f45 Iustin Pop
                                 (self.op.instance_name,
2479 decd5f45 Iustin Pop
                                  instance.primary_node))
2480 decd5f45 Iustin Pop
    self.instance = instance
2481 decd5f45 Iustin Pop
2482 decd5f45 Iustin Pop
    # new name verification
2483 89e1fc26 Iustin Pop
    name_info = utils.HostInfo(self.op.new_name)
2484 decd5f45 Iustin Pop
2485 89e1fc26 Iustin Pop
    self.op.new_name = new_name = name_info.name
2486 7bde3275 Guido Trotter
    instance_list = self.cfg.GetInstanceList()
2487 7bde3275 Guido Trotter
    if new_name in instance_list:
2488 7bde3275 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2489 c09f363f Manuel Franceschini
                                 new_name)
2490 7bde3275 Guido Trotter
2491 decd5f45 Iustin Pop
    if not getattr(self.op, "ignore_ip", False):
2492 937f983d Guido Trotter
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
2493 decd5f45 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2494 89e1fc26 Iustin Pop
                                   (name_info.ip, new_name))
2495 decd5f45 Iustin Pop
2496 decd5f45 Iustin Pop
2497 decd5f45 Iustin Pop
  def Exec(self, feedback_fn):
2498 decd5f45 Iustin Pop
    """Reinstall the instance.
2499 decd5f45 Iustin Pop

2500 decd5f45 Iustin Pop
    """
2501 decd5f45 Iustin Pop
    inst = self.instance
2502 decd5f45 Iustin Pop
    old_name = inst.name
2503 decd5f45 Iustin Pop
2504 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2505 b23c4333 Manuel Franceschini
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2506 b23c4333 Manuel Franceschini
2507 decd5f45 Iustin Pop
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2508 74b5913f Guido Trotter
    # Change the instance lock. This is definitely safe while we hold the BGL
2509 74b5913f Guido Trotter
    self.context.glm.remove(locking.LEVEL_INSTANCE, inst.name)
2510 74b5913f Guido Trotter
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
2511 decd5f45 Iustin Pop
2512 decd5f45 Iustin Pop
    # re-read the instance from the configuration after rename
2513 decd5f45 Iustin Pop
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2514 decd5f45 Iustin Pop
2515 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2516 b23c4333 Manuel Franceschini
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2517 72737a7f Iustin Pop
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
2518 72737a7f Iustin Pop
                                                     old_file_storage_dir,
2519 72737a7f Iustin Pop
                                                     new_file_storage_dir)
2520 b23c4333 Manuel Franceschini
2521 b23c4333 Manuel Franceschini
      if not result:
2522 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2523 b23c4333 Manuel Franceschini
                                 " directory '%s' to '%s' (but the instance"
2524 b23c4333 Manuel Franceschini
                                 " has been renamed in Ganeti)" % (
2525 b23c4333 Manuel Franceschini
                                 inst.primary_node, old_file_storage_dir,
2526 b23c4333 Manuel Franceschini
                                 new_file_storage_dir))
2527 b23c4333 Manuel Franceschini
2528 b23c4333 Manuel Franceschini
      if not result[0]:
2529 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2530 b23c4333 Manuel Franceschini
                                 " (but the instance has been renamed in"
2531 b23c4333 Manuel Franceschini
                                 " Ganeti)" % (old_file_storage_dir,
2532 b23c4333 Manuel Franceschini
                                               new_file_storage_dir))
2533 b23c4333 Manuel Franceschini
2534 b9bddb6b Iustin Pop
    _StartInstanceDisks(self, inst, None)
2535 decd5f45 Iustin Pop
    try:
2536 72737a7f Iustin Pop
      if not self.rpc.call_instance_run_rename(inst.primary_node, inst,
2537 72737a7f Iustin Pop
                                               old_name,
2538 72737a7f Iustin Pop
                                               "sda", "sdb"):
2539 6291574d Alexander Schreiber
        msg = ("Could not run OS rename script for instance %s on node %s"
2540 6291574d Alexander Schreiber
               " (but the instance has been renamed in Ganeti)" %
2541 decd5f45 Iustin Pop
               (inst.name, inst.primary_node))
2542 decd5f45 Iustin Pop
        logger.Error(msg)
2543 decd5f45 Iustin Pop
    finally:
2544 b9bddb6b Iustin Pop
      _ShutdownInstanceDisks(self, inst)
2545 decd5f45 Iustin Pop
2546 decd5f45 Iustin Pop
2547 a8083063 Iustin Pop
class LURemoveInstance(LogicalUnit):
2548 a8083063 Iustin Pop
  """Remove an instance.
2549 a8083063 Iustin Pop

2550 a8083063 Iustin Pop
  """
2551 a8083063 Iustin Pop
  HPATH = "instance-remove"
2552 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2553 5c54b832 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_failures"]
2554 cf472233 Guido Trotter
  REQ_BGL = False
2555 cf472233 Guido Trotter
2556 cf472233 Guido Trotter
  def ExpandNames(self):
2557 cf472233 Guido Trotter
    self._ExpandAndLockInstance()
2558 cf472233 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2559 cf472233 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2560 cf472233 Guido Trotter
2561 cf472233 Guido Trotter
  def DeclareLocks(self, level):
2562 cf472233 Guido Trotter
    if level == locking.LEVEL_NODE:
2563 cf472233 Guido Trotter
      self._LockInstancesNodes()
2564 a8083063 Iustin Pop
2565 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2566 a8083063 Iustin Pop
    """Build hooks env.
2567 a8083063 Iustin Pop

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

2570 a8083063 Iustin Pop
    """
2571 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance)
2572 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()]
2573 a8083063 Iustin Pop
    return env, nl, nl
2574 a8083063 Iustin Pop
2575 a8083063 Iustin Pop
  def CheckPrereq(self):
2576 a8083063 Iustin Pop
    """Check prerequisites.
2577 a8083063 Iustin Pop

2578 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2579 a8083063 Iustin Pop

2580 a8083063 Iustin Pop
    """
2581 cf472233 Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2582 cf472233 Guido Trotter
    assert self.instance is not None, \
2583 cf472233 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2584 a8083063 Iustin Pop
2585 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2586 a8083063 Iustin Pop
    """Remove the instance.
2587 a8083063 Iustin Pop

2588 a8083063 Iustin Pop
    """
2589 a8083063 Iustin Pop
    instance = self.instance
2590 a8083063 Iustin Pop
    logger.Info("shutting down instance %s on node %s" %
2591 a8083063 Iustin Pop
                (instance.name, instance.primary_node))
2592 a8083063 Iustin Pop
2593 72737a7f Iustin Pop
    if not self.rpc.call_instance_shutdown(instance.primary_node, instance):
2594 1d67656e Iustin Pop
      if self.op.ignore_failures:
2595 1d67656e Iustin Pop
        feedback_fn("Warning: can't shutdown instance")
2596 1d67656e Iustin Pop
      else:
2597 1d67656e Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2598 1d67656e Iustin Pop
                                 (instance.name, instance.primary_node))
2599 a8083063 Iustin Pop
2600 a8083063 Iustin Pop
    logger.Info("removing block devices for instance %s" % instance.name)
2601 a8083063 Iustin Pop
2602 b9bddb6b Iustin Pop
    if not _RemoveDisks(self, instance):
2603 1d67656e Iustin Pop
      if self.op.ignore_failures:
2604 1d67656e Iustin Pop
        feedback_fn("Warning: can't remove instance's disks")
2605 1d67656e Iustin Pop
      else:
2606 1d67656e Iustin Pop
        raise errors.OpExecError("Can't remove instance's disks")
2607 a8083063 Iustin Pop
2608 a8083063 Iustin Pop
    logger.Info("removing instance %s out of cluster config" % instance.name)
2609 a8083063 Iustin Pop
2610 a8083063 Iustin Pop
    self.cfg.RemoveInstance(instance.name)
2611 cf472233 Guido Trotter
    self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
2612 a8083063 Iustin Pop
2613 a8083063 Iustin Pop
2614 a8083063 Iustin Pop
class LUQueryInstances(NoHooksLU):
2615 a8083063 Iustin Pop
  """Logical unit for querying instances.
2616 a8083063 Iustin Pop

2617 a8083063 Iustin Pop
  """
2618 069dcc86 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
2619 7eb9d8f7 Guido Trotter
  REQ_BGL = False
2620 a8083063 Iustin Pop
2621 7eb9d8f7 Guido Trotter
  def ExpandNames(self):
2622 d8052456 Iustin Pop
    self.dynamic_fields = frozenset(["oper_state", "oper_ram", "status"])
2623 338e51e8 Iustin Pop
    hvp = ["hv/%s" % name for name in constants.HVS_PARAMETERS]
2624 338e51e8 Iustin Pop
    bep = ["be/%s" % name for name in constants.BES_PARAMETERS]
2625 57a2fb91 Iustin Pop
    self.static_fields = frozenset([
2626 57a2fb91 Iustin Pop
      "name", "os", "pnode", "snodes",
2627 57a2fb91 Iustin Pop
      "admin_state", "admin_ram",
2628 57a2fb91 Iustin Pop
      "disk_template", "ip", "mac", "bridge",
2629 57a2fb91 Iustin Pop
      "sda_size", "sdb_size", "vcpus", "tags",
2630 5018a335 Iustin Pop
      "network_port",
2631 5018a335 Iustin Pop
      "serial_no", "hypervisor", "hvparams",
2632 338e51e8 Iustin Pop
      ] + hvp + bep)
2633 338e51e8 Iustin Pop
2634 57a2fb91 Iustin Pop
    _CheckOutputFields(static=self.static_fields,
2635 dcb93971 Michael Hanselmann
                       dynamic=self.dynamic_fields,
2636 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
2637 a8083063 Iustin Pop
2638 7eb9d8f7 Guido Trotter
    self.needed_locks = {}
2639 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_INSTANCE] = 1
2640 7eb9d8f7 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
2641 7eb9d8f7 Guido Trotter
2642 57a2fb91 Iustin Pop
    if self.op.names:
2643 57a2fb91 Iustin Pop
      self.wanted = _GetWantedInstances(self, self.op.names)
2644 7eb9d8f7 Guido Trotter
    else:
2645 57a2fb91 Iustin Pop
      self.wanted = locking.ALL_SET
2646 7eb9d8f7 Guido Trotter
2647 57a2fb91 Iustin Pop
    self.do_locking = not self.static_fields.issuperset(self.op.output_fields)
2648 57a2fb91 Iustin Pop
    if self.do_locking:
2649 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
2650 57a2fb91 Iustin Pop
      self.needed_locks[locking.LEVEL_NODE] = []
2651 57a2fb91 Iustin Pop
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2652 7eb9d8f7 Guido Trotter
2653 7eb9d8f7 Guido Trotter
  def DeclareLocks(self, level):
2654 57a2fb91 Iustin Pop
    if level == locking.LEVEL_NODE and self.do_locking:
2655 7eb9d8f7 Guido Trotter
      self._LockInstancesNodes()
2656 7eb9d8f7 Guido Trotter
2657 7eb9d8f7 Guido Trotter
  def CheckPrereq(self):
2658 7eb9d8f7 Guido Trotter
    """Check prerequisites.
2659 7eb9d8f7 Guido Trotter

2660 7eb9d8f7 Guido Trotter
    """
2661 57a2fb91 Iustin Pop
    pass
2662 069dcc86 Iustin Pop
2663 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2664 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
2665 a8083063 Iustin Pop

2666 a8083063 Iustin Pop
    """
2667 57a2fb91 Iustin Pop
    all_info = self.cfg.GetAllInstancesInfo()
2668 57a2fb91 Iustin Pop
    if self.do_locking:
2669 57a2fb91 Iustin Pop
      instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2670 3fa93523 Guido Trotter
    elif self.wanted != locking.ALL_SET:
2671 3fa93523 Guido Trotter
      instance_names = self.wanted
2672 3fa93523 Guido Trotter
      missing = set(instance_names).difference(all_info.keys())
2673 3fa93523 Guido Trotter
      if missing:
2674 7b3a8fb5 Iustin Pop
        raise errors.OpExecError(
2675 3fa93523 Guido Trotter
          "Some instances were removed before retrieving their data: %s"
2676 3fa93523 Guido Trotter
          % missing)
2677 57a2fb91 Iustin Pop
    else:
2678 57a2fb91 Iustin Pop
      instance_names = all_info.keys()
2679 c1f1cbb2 Iustin Pop
2680 c1f1cbb2 Iustin Pop
    instance_names = utils.NiceSort(instance_names)
2681 57a2fb91 Iustin Pop
    instance_list = [all_info[iname] for iname in instance_names]
2682 a8083063 Iustin Pop
2683 a8083063 Iustin Pop
    # begin data gathering
2684 a8083063 Iustin Pop
2685 a8083063 Iustin Pop
    nodes = frozenset([inst.primary_node for inst in instance_list])
2686 e69d05fd Iustin Pop
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
2687 a8083063 Iustin Pop
2688 a8083063 Iustin Pop
    bad_nodes = []
2689 a8083063 Iustin Pop
    if self.dynamic_fields.intersection(self.op.output_fields):
2690 a8083063 Iustin Pop
      live_data = {}
2691 72737a7f Iustin Pop
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
2692 a8083063 Iustin Pop
      for name in nodes:
2693 a8083063 Iustin Pop
        result = node_data[name]
2694 a8083063 Iustin Pop
        if result:
2695 a8083063 Iustin Pop
          live_data.update(result)
2696 a8083063 Iustin Pop
        elif result == False:
2697 a8083063 Iustin Pop
          bad_nodes.append(name)
2698 a8083063 Iustin Pop
        # else no instance is alive
2699 a8083063 Iustin Pop
    else:
2700 a8083063 Iustin Pop
      live_data = dict([(name, {}) for name in instance_names])
2701 a8083063 Iustin Pop
2702 a8083063 Iustin Pop
    # end data gathering
2703 a8083063 Iustin Pop
2704 5018a335 Iustin Pop
    HVPREFIX = "hv/"
2705 338e51e8 Iustin Pop
    BEPREFIX = "be/"
2706 a8083063 Iustin Pop
    output = []
2707 a8083063 Iustin Pop
    for instance in instance_list:
2708 a8083063 Iustin Pop
      iout = []
2709 5018a335 Iustin Pop
      i_hv = self.cfg.GetClusterInfo().FillHV(instance)
2710 338e51e8 Iustin Pop
      i_be = self.cfg.GetClusterInfo().FillBE(instance)
2711 a8083063 Iustin Pop
      for field in self.op.output_fields:
2712 a8083063 Iustin Pop
        if field == "name":
2713 a8083063 Iustin Pop
          val = instance.name
2714 a8083063 Iustin Pop
        elif field == "os":
2715 a8083063 Iustin Pop
          val = instance.os
2716 a8083063 Iustin Pop
        elif field == "pnode":
2717 a8083063 Iustin Pop
          val = instance.primary_node
2718 a8083063 Iustin Pop
        elif field == "snodes":
2719 8a23d2d3 Iustin Pop
          val = list(instance.secondary_nodes)
2720 a8083063 Iustin Pop
        elif field == "admin_state":
2721 8a23d2d3 Iustin Pop
          val = (instance.status != "down")
2722 a8083063 Iustin Pop
        elif field == "oper_state":
2723 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
2724 8a23d2d3 Iustin Pop
            val = None
2725 a8083063 Iustin Pop
          else:
2726 8a23d2d3 Iustin Pop
            val = bool(live_data.get(instance.name))
2727 d8052456 Iustin Pop
        elif field == "status":
2728 d8052456 Iustin Pop
          if instance.primary_node in bad_nodes:
2729 d8052456 Iustin Pop
            val = "ERROR_nodedown"
2730 d8052456 Iustin Pop
          else:
2731 d8052456 Iustin Pop
            running = bool(live_data.get(instance.name))
2732 d8052456 Iustin Pop
            if running:
2733 d8052456 Iustin Pop
              if instance.status != "down":
2734 d8052456 Iustin Pop
                val = "running"
2735 d8052456 Iustin Pop
              else:
2736 d8052456 Iustin Pop
                val = "ERROR_up"
2737 d8052456 Iustin Pop
            else:
2738 d8052456 Iustin Pop
              if instance.status != "down":
2739 d8052456 Iustin Pop
                val = "ERROR_down"
2740 d8052456 Iustin Pop
              else:
2741 d8052456 Iustin Pop
                val = "ADMIN_down"
2742 a8083063 Iustin Pop
        elif field == "oper_ram":
2743 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
2744 8a23d2d3 Iustin Pop
            val = None
2745 a8083063 Iustin Pop
          elif instance.name in live_data:
2746 a8083063 Iustin Pop
            val = live_data[instance.name].get("memory", "?")
2747 a8083063 Iustin Pop
          else:
2748 a8083063 Iustin Pop
            val = "-"
2749 a8083063 Iustin Pop
        elif field == "disk_template":
2750 a8083063 Iustin Pop
          val = instance.disk_template
2751 a8083063 Iustin Pop
        elif field == "ip":
2752 a8083063 Iustin Pop
          val = instance.nics[0].ip
2753 a8083063 Iustin Pop
        elif field == "bridge":
2754 a8083063 Iustin Pop
          val = instance.nics[0].bridge
2755 a8083063 Iustin Pop
        elif field == "mac":
2756 a8083063 Iustin Pop
          val = instance.nics[0].mac
2757 644eeef9 Iustin Pop
        elif field == "sda_size" or field == "sdb_size":
2758 644eeef9 Iustin Pop
          disk = instance.FindDisk(field[:3])
2759 644eeef9 Iustin Pop
          if disk is None:
2760 8a23d2d3 Iustin Pop
            val = None
2761 644eeef9 Iustin Pop
          else:
2762 644eeef9 Iustin Pop
            val = disk.size
2763 130a6a6f Iustin Pop
        elif field == "tags":
2764 130a6a6f Iustin Pop
          val = list(instance.GetTags())
2765 38d7239a Iustin Pop
        elif field == "serial_no":
2766 38d7239a Iustin Pop
          val = instance.serial_no
2767 5018a335 Iustin Pop
        elif field == "network_port":
2768 5018a335 Iustin Pop
          val = instance.network_port
2769 338e51e8 Iustin Pop
        elif field == "hypervisor":
2770 338e51e8 Iustin Pop
          val = instance.hypervisor
2771 338e51e8 Iustin Pop
        elif field == "hvparams":
2772 338e51e8 Iustin Pop
          val = i_hv
2773 5018a335 Iustin Pop
        elif (field.startswith(HVPREFIX) and
2774 5018a335 Iustin Pop
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS):
2775 5018a335 Iustin Pop
          val = i_hv.get(field[len(HVPREFIX):], None)
2776 338e51e8 Iustin Pop
        elif field == "beparams":
2777 338e51e8 Iustin Pop
          val = i_be
2778 338e51e8 Iustin Pop
        elif (field.startswith(BEPREFIX) and
2779 338e51e8 Iustin Pop
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
2780 338e51e8 Iustin Pop
          val = i_be.get(field[len(BEPREFIX):], None)
2781 a8083063 Iustin Pop
        else:
2782 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
2783 a8083063 Iustin Pop
        iout.append(val)
2784 a8083063 Iustin Pop
      output.append(iout)
2785 a8083063 Iustin Pop
2786 a8083063 Iustin Pop
    return output
2787 a8083063 Iustin Pop
2788 a8083063 Iustin Pop
2789 a8083063 Iustin Pop
class LUFailoverInstance(LogicalUnit):
2790 a8083063 Iustin Pop
  """Failover an instance.
2791 a8083063 Iustin Pop

2792 a8083063 Iustin Pop
  """
2793 a8083063 Iustin Pop
  HPATH = "instance-failover"
2794 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2795 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_consistency"]
2796 c9e5c064 Guido Trotter
  REQ_BGL = False
2797 c9e5c064 Guido Trotter
2798 c9e5c064 Guido Trotter
  def ExpandNames(self):
2799 c9e5c064 Guido Trotter
    self._ExpandAndLockInstance()
2800 c9e5c064 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
2801 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2802 c9e5c064 Guido Trotter
2803 c9e5c064 Guido Trotter
  def DeclareLocks(self, level):
2804 c9e5c064 Guido Trotter
    if level == locking.LEVEL_NODE:
2805 c9e5c064 Guido Trotter
      self._LockInstancesNodes()
2806 a8083063 Iustin Pop
2807 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2808 a8083063 Iustin Pop
    """Build hooks env.
2809 a8083063 Iustin Pop

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

2812 a8083063 Iustin Pop
    """
2813 a8083063 Iustin Pop
    env = {
2814 a8083063 Iustin Pop
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2815 a8083063 Iustin Pop
      }
2816 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
2817 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes)
2818 a8083063 Iustin Pop
    return env, nl, nl
2819 a8083063 Iustin Pop
2820 a8083063 Iustin Pop
  def CheckPrereq(self):
2821 a8083063 Iustin Pop
    """Check prerequisites.
2822 a8083063 Iustin Pop

2823 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2824 a8083063 Iustin Pop

2825 a8083063 Iustin Pop
    """
2826 c9e5c064 Guido Trotter
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
2827 c9e5c064 Guido Trotter
    assert self.instance is not None, \
2828 c9e5c064 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
2829 a8083063 Iustin Pop
2830 338e51e8 Iustin Pop
    bep = self.cfg.GetClusterInfo().FillBE(instance)
2831 a1f445d3 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
2832 2a710df1 Michael Hanselmann
      raise errors.OpPrereqError("Instance's disk layout is not"
2833 a1f445d3 Iustin Pop
                                 " network mirrored, cannot failover.")
2834 2a710df1 Michael Hanselmann
2835 2a710df1 Michael Hanselmann
    secondary_nodes = instance.secondary_nodes
2836 2a710df1 Michael Hanselmann
    if not secondary_nodes:
2837 2a710df1 Michael Hanselmann
      raise errors.ProgrammerError("no secondary node but using "
2838 abdf0113 Iustin Pop
                                   "a mirrored disk template")
2839 2a710df1 Michael Hanselmann
2840 2a710df1 Michael Hanselmann
    target_node = secondary_nodes[0]
2841 d4f16fd9 Iustin Pop
    # check memory requirements on the secondary node
2842 b9bddb6b Iustin Pop
    _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
2843 338e51e8 Iustin Pop
                         instance.name, bep[constants.BE_MEMORY],
2844 e69d05fd Iustin Pop
                         instance.hypervisor)
2845 3a7c308e Guido Trotter
2846 a8083063 Iustin Pop
    # check bridge existance
2847 a8083063 Iustin Pop
    brlist = [nic.bridge for nic in instance.nics]
2848 72737a7f Iustin Pop
    if not self.rpc.call_bridges_exist(target_node, brlist):
2849 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("One or more target bridges %s does not"
2850 3ecf6786 Iustin Pop
                                 " exist on destination node '%s'" %
2851 50ff9a7a Iustin Pop
                                 (brlist, target_node))
2852 a8083063 Iustin Pop
2853 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2854 a8083063 Iustin Pop
    """Failover an instance.
2855 a8083063 Iustin Pop

2856 a8083063 Iustin Pop
    The failover is done by shutting it down on its present node and
2857 a8083063 Iustin Pop
    starting it on the secondary.
2858 a8083063 Iustin Pop

2859 a8083063 Iustin Pop
    """
2860 a8083063 Iustin Pop
    instance = self.instance
2861 a8083063 Iustin Pop
2862 a8083063 Iustin Pop
    source_node = instance.primary_node
2863 a8083063 Iustin Pop
    target_node = instance.secondary_nodes[0]
2864 a8083063 Iustin Pop
2865 a8083063 Iustin Pop
    feedback_fn("* checking disk consistency between source and target")
2866 a8083063 Iustin Pop
    for dev in instance.disks:
2867 abdf0113 Iustin Pop
      # for drbd, these are drbd over lvm
2868 b9bddb6b Iustin Pop
      if not _CheckDiskConsistency(self, dev, target_node, False):
2869 a0aaa0d0 Guido Trotter
        if instance.status == "up" and not self.op.ignore_consistency:
2870 3ecf6786 Iustin Pop
          raise errors.OpExecError("Disk %s is degraded on target node,"
2871 3ecf6786 Iustin Pop
                                   " aborting failover." % dev.iv_name)
2872 a8083063 Iustin Pop
2873 a8083063 Iustin Pop
    feedback_fn("* shutting down instance on source node")
2874 a8083063 Iustin Pop
    logger.Info("Shutting down instance %s on node %s" %
2875 a8083063 Iustin Pop
                (instance.name, source_node))
2876 a8083063 Iustin Pop
2877 72737a7f Iustin Pop
    if not self.rpc.call_instance_shutdown(source_node, instance):
2878 24a40d57 Iustin Pop
      if self.op.ignore_consistency:
2879 24a40d57 Iustin Pop
        logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2880 24a40d57 Iustin Pop
                     " anyway. Please make sure node %s is down"  %
2881 24a40d57 Iustin Pop
                     (instance.name, source_node, source_node))
2882 24a40d57 Iustin Pop
      else:
2883 24a40d57 Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2884 24a40d57 Iustin Pop
                                 (instance.name, source_node))
2885 a8083063 Iustin Pop
2886 a8083063 Iustin Pop
    feedback_fn("* deactivating the instance's disks on source node")
2887 b9bddb6b Iustin Pop
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
2888 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't shut down the instance's disks.")
2889 a8083063 Iustin Pop
2890 a8083063 Iustin Pop
    instance.primary_node = target_node
2891 a8083063 Iustin Pop
    # distribute new instance config to the other nodes
2892 b6102dab Guido Trotter
    self.cfg.Update(instance)
2893 a8083063 Iustin Pop
2894 12a0cfbe Guido Trotter
    # Only start the instance if it's marked as up
2895 12a0cfbe Guido Trotter
    if instance.status == "up":
2896 12a0cfbe Guido Trotter
      feedback_fn("* activating the instance's disks on target node")
2897 12a0cfbe Guido Trotter
      logger.Info("Starting instance %s on node %s" %
2898 12a0cfbe Guido Trotter
                  (instance.name, target_node))
2899 12a0cfbe Guido Trotter
2900 b9bddb6b Iustin Pop
      disks_ok, dummy = _AssembleInstanceDisks(self, instance,
2901 12a0cfbe Guido Trotter
                                               ignore_secondaries=True)
2902 12a0cfbe Guido Trotter
      if not disks_ok:
2903 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
2904 12a0cfbe Guido Trotter
        raise errors.OpExecError("Can't activate the instance's disks")
2905 a8083063 Iustin Pop
2906 12a0cfbe Guido Trotter
      feedback_fn("* starting the instance on the target node")
2907 72737a7f Iustin Pop
      if not self.rpc.call_instance_start(target_node, instance, None):
2908 b9bddb6b Iustin Pop
        _ShutdownInstanceDisks(self, instance)
2909 12a0cfbe Guido Trotter
        raise errors.OpExecError("Could not start instance %s on node %s." %
2910 12a0cfbe Guido Trotter
                                 (instance.name, target_node))
2911 a8083063 Iustin Pop
2912 a8083063 Iustin Pop
2913 b9bddb6b Iustin Pop
def _CreateBlockDevOnPrimary(lu, node, instance, device, info):
2914 a8083063 Iustin Pop
  """Create a tree of block devices on the primary node.
2915 a8083063 Iustin Pop

2916 a8083063 Iustin Pop
  This always creates all devices.
2917 a8083063 Iustin Pop

2918 a8083063 Iustin Pop
  """
2919 a8083063 Iustin Pop
  if device.children:
2920 a8083063 Iustin Pop
    for child in device.children:
2921 b9bddb6b Iustin Pop
      if not _CreateBlockDevOnPrimary(lu, node, instance, child, info):
2922 a8083063 Iustin Pop
        return False
2923 a8083063 Iustin Pop
2924 b9bddb6b Iustin Pop
  lu.cfg.SetDiskID(device, node)
2925 72737a7f Iustin Pop
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
2926 72737a7f Iustin Pop
                                       instance.name, True, info)
2927 a8083063 Iustin Pop
  if not new_id:
2928 a8083063 Iustin Pop
    return False
2929 a8083063 Iustin Pop
  if device.physical_id is None:
2930 a8083063 Iustin Pop
    device.physical_id = new_id
2931 a8083063 Iustin Pop
  return True
2932 a8083063 Iustin Pop
2933 a8083063 Iustin Pop
2934 b9bddb6b Iustin Pop
def _CreateBlockDevOnSecondary(lu, node, instance, device, force, info):
2935 a8083063 Iustin Pop
  """Create a tree of block devices on a secondary node.
2936 a8083063 Iustin Pop

2937 a8083063 Iustin Pop
  If this device type has to be created on secondaries, create it and
2938 a8083063 Iustin Pop
  all its children.
2939 a8083063 Iustin Pop

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

2942 a8083063 Iustin Pop
  """
2943 a8083063 Iustin Pop
  if device.CreateOnSecondary():
2944 a8083063 Iustin Pop
    force = True
2945 a8083063 Iustin Pop
  if device.children:
2946 a8083063 Iustin Pop
    for child in device.children:
2947 b9bddb6b Iustin Pop
      if not _CreateBlockDevOnSecondary(lu, node, instance,
2948 3f78eef2 Iustin Pop
                                        child, force, info):
2949 a8083063 Iustin Pop
        return False
2950 a8083063 Iustin Pop
2951 a8083063 Iustin Pop
  if not force:
2952 a8083063 Iustin Pop
    return True
2953 b9bddb6b Iustin Pop
  lu.cfg.SetDiskID(device, node)
2954 72737a7f Iustin Pop
  new_id = lu.rpc.call_blockdev_create(node, device, device.size,
2955 72737a7f Iustin Pop
                                       instance.name, False, info)
2956 a8083063 Iustin Pop
  if not new_id:
2957 a8083063 Iustin Pop
    return False
2958 a8083063 Iustin Pop
  if device.physical_id is None:
2959 a8083063 Iustin Pop
    device.physical_id = new_id
2960 a8083063 Iustin Pop
  return True
2961 a8083063 Iustin Pop
2962 a8083063 Iustin Pop
2963 b9bddb6b Iustin Pop
def _GenerateUniqueNames(lu, exts):
2964 923b1523 Iustin Pop
  """Generate a suitable LV name.
2965 923b1523 Iustin Pop

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

2968 923b1523 Iustin Pop
  """
2969 923b1523 Iustin Pop
  results = []
2970 923b1523 Iustin Pop
  for val in exts:
2971 b9bddb6b Iustin Pop
    new_id = lu.cfg.GenerateUniqueID()
2972 923b1523 Iustin Pop
    results.append("%s%s" % (new_id, val))
2973 923b1523 Iustin Pop
  return results
2974 923b1523 Iustin Pop
2975 923b1523 Iustin Pop
2976 b9bddb6b Iustin Pop
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
2977 ffa1c0dc Iustin Pop
                         p_minor, s_minor):
2978 a1f445d3 Iustin Pop
  """Generate a drbd8 device complete with its children.
2979 a1f445d3 Iustin Pop

2980 a1f445d3 Iustin Pop
  """
2981 b9bddb6b Iustin Pop
  port = lu.cfg.AllocatePort()
2982 b9bddb6b Iustin Pop
  vgname = lu.cfg.GetVGName()
2983 b9bddb6b Iustin Pop
  shared_secret = lu.cfg.GenerateDRBDSecret()
2984 a1f445d3 Iustin Pop
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2985 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[0]))
2986 a1f445d3 Iustin Pop
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2987 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[1]))
2988 a1f445d3 Iustin Pop
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
2989 ffa1c0dc Iustin Pop
                          logical_id=(primary, secondary, port,
2990 f9518d38 Iustin Pop
                                      p_minor, s_minor,
2991 f9518d38 Iustin Pop
                                      shared_secret),
2992 ffa1c0dc Iustin Pop
                          children=[dev_data, dev_meta],
2993 a1f445d3 Iustin Pop
                          iv_name=iv_name)
2994 a1f445d3 Iustin Pop
  return drbd_dev
2995 a1f445d3 Iustin Pop
2996 7c0d6283 Michael Hanselmann
2997 b9bddb6b Iustin Pop
def _GenerateDiskTemplate(lu, template_name,
2998 a8083063 Iustin Pop
                          instance_name, primary_node,
2999 0f1a06e3 Manuel Franceschini
                          secondary_nodes, disk_sz, swap_sz,
3000 0f1a06e3 Manuel Franceschini
                          file_storage_dir, file_driver):
3001 a8083063 Iustin Pop
  """Generate the entire disk layout for a given template type.
3002 a8083063 Iustin Pop

3003 a8083063 Iustin Pop
  """
3004 a8083063 Iustin Pop
  #TODO: compute space requirements
3005 a8083063 Iustin Pop
3006 b9bddb6b Iustin Pop
  vgname = lu.cfg.GetVGName()
3007 3517d9b9 Manuel Franceschini
  if template_name == constants.DT_DISKLESS:
3008 a8083063 Iustin Pop
    disks = []
3009 3517d9b9 Manuel Franceschini
  elif template_name == constants.DT_PLAIN:
3010 a8083063 Iustin Pop
    if len(secondary_nodes) != 0:
3011 a8083063 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
3012 923b1523 Iustin Pop
3013 b9bddb6b Iustin Pop
    names = _GenerateUniqueNames(lu, [".sda", ".sdb"])
3014 fe96220b Iustin Pop
    sda_dev = objects.Disk(dev_type=constants.LD_LV, size=disk_sz,
3015 923b1523 Iustin Pop
                           logical_id=(vgname, names[0]),
3016 a8083063 Iustin Pop
                           iv_name = "sda")
3017 fe96220b Iustin Pop
    sdb_dev = objects.Disk(dev_type=constants.LD_LV, size=swap_sz,
3018 923b1523 Iustin Pop
                           logical_id=(vgname, names[1]),
3019 a8083063 Iustin Pop
                           iv_name = "sdb")
3020 a8083063 Iustin Pop
    disks = [sda_dev, sdb_dev]
3021 a1f445d3 Iustin Pop
  elif template_name == constants.DT_DRBD8:
3022 a1f445d3 Iustin Pop
    if len(secondary_nodes) != 1:
3023 a1f445d3 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
3024 a1f445d3 Iustin Pop
    remote_node = secondary_nodes[0]
3025 ffa1c0dc Iustin Pop
    (minor_pa, minor_pb,
3026 b9bddb6b Iustin Pop
     minor_sa, minor_sb) = lu.cfg.AllocateDRBDMinor(
3027 a1578d63 Iustin Pop
      [primary_node, primary_node, remote_node, remote_node], instance_name)
3028 ffa1c0dc Iustin Pop
3029 b9bddb6b Iustin Pop
    names = _GenerateUniqueNames(lu, [".sda_data", ".sda_meta",
3030 b9bddb6b Iustin Pop
                                      ".sdb_data", ".sdb_meta"])
3031 b9bddb6b Iustin Pop
    drbd_sda_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3032 ffa1c0dc Iustin Pop
                                        disk_sz, names[0:2], "sda",
3033 ffa1c0dc Iustin Pop
                                        minor_pa, minor_sa)
3034 b9bddb6b Iustin Pop
    drbd_sdb_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
3035 ffa1c0dc Iustin Pop
                                        swap_sz, names[2:4], "sdb",
3036 ffa1c0dc Iustin Pop
                                        minor_pb, minor_sb)
3037 a1f445d3 Iustin Pop
    disks = [drbd_sda_dev, drbd_sdb_dev]
3038 0f1a06e3 Manuel Franceschini
  elif template_name == constants.DT_FILE:
3039 0f1a06e3 Manuel Franceschini
    if len(secondary_nodes) != 0:
3040 0f1a06e3 Manuel Franceschini
      raise errors.ProgrammerError("Wrong template configuration")
3041 0f1a06e3 Manuel Franceschini
3042 0f1a06e3 Manuel Franceschini
    file_sda_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk_sz,
3043 0f1a06e3 Manuel Franceschini
                                iv_name="sda", logical_id=(file_driver,
3044 0f1a06e3 Manuel Franceschini
                                "%s/sda" % file_storage_dir))
3045 0f1a06e3 Manuel Franceschini
    file_sdb_dev = objects.Disk(dev_type=constants.LD_FILE, size=swap_sz,
3046 0f1a06e3 Manuel Franceschini
                                iv_name="sdb", logical_id=(file_driver,
3047 0f1a06e3 Manuel Franceschini
                                "%s/sdb" % file_storage_dir))
3048 0f1a06e3 Manuel Franceschini
    disks = [file_sda_dev, file_sdb_dev]
3049 a8083063 Iustin Pop
  else:
3050 a8083063 Iustin Pop
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3051 a8083063 Iustin Pop
  return disks
3052 a8083063 Iustin Pop
3053 a8083063 Iustin Pop
3054 a0c3fea1 Michael Hanselmann
def _GetInstanceInfoText(instance):
3055 3ecf6786 Iustin Pop
  """Compute that text that should be added to the disk's metadata.
3056 3ecf6786 Iustin Pop

3057 3ecf6786 Iustin Pop
  """
3058 a0c3fea1 Michael Hanselmann
  return "originstname+%s" % instance.name
3059 a0c3fea1 Michael Hanselmann
3060 a0c3fea1 Michael Hanselmann
3061 b9bddb6b Iustin Pop
def _CreateDisks(lu, instance):
3062 a8083063 Iustin Pop
  """Create all disks for an instance.
3063 a8083063 Iustin Pop

3064 a8083063 Iustin Pop
  This abstracts away some work from AddInstance.
3065 a8083063 Iustin Pop

3066 a8083063 Iustin Pop
  Args:
3067 a8083063 Iustin Pop
    instance: the instance object
3068 a8083063 Iustin Pop

3069 a8083063 Iustin Pop
  Returns:
3070 a8083063 Iustin Pop
    True or False showing the success of the creation process
3071 a8083063 Iustin Pop

3072 a8083063 Iustin Pop
  """
3073 a0c3fea1 Michael Hanselmann
  info = _GetInstanceInfoText(instance)
3074 a0c3fea1 Michael Hanselmann
3075 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3076 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3077 72737a7f Iustin Pop
    result = lu.rpc.call_file_storage_dir_create(instance.primary_node,
3078 72737a7f Iustin Pop
                                                 file_storage_dir)
3079 0f1a06e3 Manuel Franceschini
3080 0f1a06e3 Manuel Franceschini
    if not result:
3081 b62ddbe5 Guido Trotter
      logger.Error("Could not connect to node '%s'" % instance.primary_node)
3082 0f1a06e3 Manuel Franceschini
      return False
3083 0f1a06e3 Manuel Franceschini
3084 0f1a06e3 Manuel Franceschini
    if not result[0]:
3085 0f1a06e3 Manuel Franceschini
      logger.Error("failed to create directory '%s'" % file_storage_dir)
3086 0f1a06e3 Manuel Franceschini
      return False
3087 0f1a06e3 Manuel Franceschini
3088 a8083063 Iustin Pop
  for device in instance.disks:
3089 a8083063 Iustin Pop
    logger.Info("creating volume %s for instance %s" %
3090 1c6e3627 Manuel Franceschini
                (device.iv_name, instance.name))
3091 a8083063 Iustin Pop
    #HARDCODE
3092 a8083063 Iustin Pop
    for secondary_node in instance.secondary_nodes:
3093 b9bddb6b Iustin Pop
      if not _CreateBlockDevOnSecondary(lu, secondary_node, instance,
3094 3f78eef2 Iustin Pop
                                        device, False, info):
3095 a8083063 Iustin Pop
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
3096 a8083063 Iustin Pop
                     (device.iv_name, device, secondary_node))
3097 a8083063 Iustin Pop
        return False
3098 a8083063 Iustin Pop
    #HARDCODE
3099 b9bddb6b Iustin Pop
    if not _CreateBlockDevOnPrimary(lu, instance.primary_node,
3100 3f78eef2 Iustin Pop
                                    instance, device, info):
3101 a8083063 Iustin Pop
      logger.Error("failed to create volume %s on primary!" %
3102 a8083063 Iustin Pop
                   device.iv_name)
3103 a8083063 Iustin Pop
      return False
3104 1c6e3627 Manuel Franceschini
3105 a8083063 Iustin Pop
  return True
3106 a8083063 Iustin Pop
3107 a8083063 Iustin Pop
3108 b9bddb6b Iustin Pop
def _RemoveDisks(lu, instance):
3109 a8083063 Iustin Pop
  """Remove all disks for an instance.
3110 a8083063 Iustin Pop

3111 a8083063 Iustin Pop
  This abstracts away some work from `AddInstance()` and
3112 a8083063 Iustin Pop
  `RemoveInstance()`. Note that in case some of the devices couldn't
3113 1d67656e Iustin Pop
  be removed, the removal will continue with the other ones (compare
3114 a8083063 Iustin Pop
  with `_CreateDisks()`).
3115 a8083063 Iustin Pop

3116 a8083063 Iustin Pop
  Args:
3117 a8083063 Iustin Pop
    instance: the instance object
3118 a8083063 Iustin Pop

3119 a8083063 Iustin Pop
  Returns:
3120 a8083063 Iustin Pop
    True or False showing the success of the removal proces
3121 a8083063 Iustin Pop

3122 a8083063 Iustin Pop
  """
3123 a8083063 Iustin Pop
  logger.Info("removing block devices for instance %s" % instance.name)
3124 a8083063 Iustin Pop
3125 a8083063 Iustin Pop
  result = True
3126 a8083063 Iustin Pop
  for device in instance.disks:
3127 a8083063 Iustin Pop
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3128 b9bddb6b Iustin Pop
      lu.cfg.SetDiskID(disk, node)
3129 72737a7f Iustin Pop
      if not lu.rpc.call_blockdev_remove(node, disk):
3130 a8083063 Iustin Pop
        logger.Error("could not remove block device %s on node %s,"
3131 a8083063 Iustin Pop
                     " continuing anyway" %
3132 a8083063 Iustin Pop
                     (device.iv_name, node))
3133 a8083063 Iustin Pop
        result = False
3134 0f1a06e3 Manuel Franceschini
3135 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3136 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3137 72737a7f Iustin Pop
    if not lu.rpc.call_file_storage_dir_remove(instance.primary_node,
3138 72737a7f Iustin Pop
                                               file_storage_dir):
3139 0f1a06e3 Manuel Franceschini
      logger.Error("could not remove directory '%s'" % file_storage_dir)
3140 0f1a06e3 Manuel Franceschini
      result = False
3141 0f1a06e3 Manuel Franceschini
3142 a8083063 Iustin Pop
  return result
3143 a8083063 Iustin Pop
3144 a8083063 Iustin Pop
3145 e2fe6369 Iustin Pop
def _ComputeDiskSize(disk_template, disk_size, swap_size):
3146 e2fe6369 Iustin Pop
  """Compute disk size requirements in the volume group
3147 e2fe6369 Iustin Pop

3148 e2fe6369 Iustin Pop
  This is currently hard-coded for the two-drive layout.
3149 e2fe6369 Iustin Pop

3150 e2fe6369 Iustin Pop
  """
3151 e2fe6369 Iustin Pop
  # Required free disk space as a function of disk and swap space
3152 e2fe6369 Iustin Pop
  req_size_dict = {
3153 e2fe6369 Iustin Pop
    constants.DT_DISKLESS: None,
3154 e2fe6369 Iustin Pop
    constants.DT_PLAIN: disk_size + swap_size,
3155 e2fe6369 Iustin Pop
    # 256 MB are added for drbd metadata, 128MB for each drbd device
3156 e2fe6369 Iustin Pop
    constants.DT_DRBD8: disk_size + swap_size + 256,
3157 e2fe6369 Iustin Pop
    constants.DT_FILE: None,
3158 e2fe6369 Iustin Pop
  }
3159 e2fe6369 Iustin Pop
3160 e2fe6369 Iustin Pop
  if disk_template not in req_size_dict:
3161 e2fe6369 Iustin Pop
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3162 e2fe6369 Iustin Pop
                                 " is unknown" %  disk_template)
3163 e2fe6369 Iustin Pop
3164 e2fe6369 Iustin Pop
  return req_size_dict[disk_template]
3165 e2fe6369 Iustin Pop
3166 e2fe6369 Iustin Pop
3167 74409b12 Iustin Pop
def _CheckHVParams(lu, nodenames, hvname, hvparams):
3168 74409b12 Iustin Pop
  """Hypervisor parameter validation.
3169 74409b12 Iustin Pop

3170 74409b12 Iustin Pop
  This function abstract the hypervisor parameter validation to be
3171 74409b12 Iustin Pop
  used in both instance create and instance modify.
3172 74409b12 Iustin Pop

3173 74409b12 Iustin Pop
  @type lu: L{LogicalUnit}
3174 74409b12 Iustin Pop
  @param lu: the logical unit for which we check
3175 74409b12 Iustin Pop
  @type nodenames: list
3176 74409b12 Iustin Pop
  @param nodenames: the list of nodes on which we should check
3177 74409b12 Iustin Pop
  @type hvname: string
3178 74409b12 Iustin Pop
  @param hvname: the name of the hypervisor we should use
3179 74409b12 Iustin Pop
  @type hvparams: dict
3180 74409b12 Iustin Pop
  @param hvparams: the parameters which we need to check
3181 74409b12 Iustin Pop
  @raise errors.OpPrereqError: if the parameters are not valid
3182 74409b12 Iustin Pop

3183 74409b12 Iustin Pop
  """
3184 74409b12 Iustin Pop
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
3185 74409b12 Iustin Pop
                                                  hvname,
3186 74409b12 Iustin Pop
                                                  hvparams)
3187 74409b12 Iustin Pop
  for node in nodenames:
3188 74409b12 Iustin Pop
    info = hvinfo.get(node, None)
3189 74409b12 Iustin Pop
    if not info or not isinstance(info, (tuple, list)):
3190 74409b12 Iustin Pop
      raise errors.OpPrereqError("Cannot get current information"
3191 74409b12 Iustin Pop
                                 " from node '%s' (%s)" % (node, info))
3192 74409b12 Iustin Pop
    if not info[0]:
3193 74409b12 Iustin Pop
      raise errors.OpPrereqError("Hypervisor parameter validation failed:"
3194 74409b12 Iustin Pop
                                 " %s" % info[1])
3195 74409b12 Iustin Pop
3196 74409b12 Iustin Pop
3197 a8083063 Iustin Pop
class LUCreateInstance(LogicalUnit):
3198 a8083063 Iustin Pop
  """Create an instance.
3199 a8083063 Iustin Pop

3200 a8083063 Iustin Pop
  """
3201 a8083063 Iustin Pop
  HPATH = "instance-add"
3202 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3203 338e51e8 Iustin Pop
  _OP_REQP = ["instance_name", "disk_size",
3204 338e51e8 Iustin Pop
              "disk_template", "swap_size", "mode", "start",
3205 338e51e8 Iustin Pop
              "wait_for_sync", "ip_check", "mac",
3206 338e51e8 Iustin Pop
              "hvparams", "beparams"]
3207 7baf741d Guido Trotter
  REQ_BGL = False
3208 7baf741d Guido Trotter
3209 7baf741d Guido Trotter
  def _ExpandNode(self, node):
3210 7baf741d Guido Trotter
    """Expands and checks one node name.
3211 7baf741d Guido Trotter

3212 7baf741d Guido Trotter
    """
3213 7baf741d Guido Trotter
    node_full = self.cfg.ExpandNodeName(node)
3214 7baf741d Guido Trotter
    if node_full is None:
3215 7baf741d Guido Trotter
      raise errors.OpPrereqError("Unknown node %s" % node)
3216 7baf741d Guido Trotter
    return node_full
3217 7baf741d Guido Trotter
3218 7baf741d Guido Trotter
  def ExpandNames(self):
3219 7baf741d Guido Trotter
    """ExpandNames for CreateInstance.
3220 7baf741d Guido Trotter

3221 7baf741d Guido Trotter
    Figure out the right locks for instance creation.
3222 7baf741d Guido Trotter

3223 7baf741d Guido Trotter
    """
3224 7baf741d Guido Trotter
    self.needed_locks = {}
3225 7baf741d Guido Trotter
3226 7baf741d Guido Trotter
    # set optional parameters to none if they don't exist
3227 6785674e Iustin Pop
    for attr in ["pnode", "snode", "iallocator", "hypervisor"]:
3228 7baf741d Guido Trotter
      if not hasattr(self.op, attr):
3229 7baf741d Guido Trotter
        setattr(self.op, attr, None)
3230 7baf741d Guido Trotter
3231 4b2f38dd Iustin Pop
    # cheap checks, mostly valid constants given
3232 4b2f38dd Iustin Pop
3233 7baf741d Guido Trotter
    # verify creation mode
3234 7baf741d Guido Trotter
    if self.op.mode not in (constants.INSTANCE_CREATE,
3235 7baf741d Guido Trotter
                            constants.INSTANCE_IMPORT):
3236 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3237 7baf741d Guido Trotter
                                 self.op.mode)
3238 4b2f38dd Iustin Pop
3239 7baf741d Guido Trotter
    # disk template and mirror node verification
3240 7baf741d Guido Trotter
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3241 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid disk template name")
3242 7baf741d Guido Trotter
3243 4b2f38dd Iustin Pop
    if self.op.hypervisor is None:
3244 4b2f38dd Iustin Pop
      self.op.hypervisor = self.cfg.GetHypervisorType()
3245 4b2f38dd Iustin Pop
3246 8705eb96 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
3247 8705eb96 Iustin Pop
    enabled_hvs = cluster.enabled_hypervisors
3248 4b2f38dd Iustin Pop
    if self.op.hypervisor not in enabled_hvs:
3249 4b2f38dd Iustin Pop
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
3250 4b2f38dd Iustin Pop
                                 " cluster (%s)" % (self.op.hypervisor,
3251 4b2f38dd Iustin Pop
                                  ",".join(enabled_hvs)))
3252 4b2f38dd Iustin Pop
3253 6785674e Iustin Pop
    # check hypervisor parameter syntax (locally)
3254 6785674e Iustin Pop
3255 8705eb96 Iustin Pop
    filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
3256 8705eb96 Iustin Pop
                                  self.op.hvparams)
3257 6785674e Iustin Pop
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
3258 8705eb96 Iustin Pop
    hv_type.CheckParameterSyntax(filled_hvp)
3259 6785674e Iustin Pop
3260 338e51e8 Iustin Pop
    # fill and remember the beparams dict
3261 338e51e8 Iustin Pop
    self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
3262 338e51e8 Iustin Pop
                                    self.op.beparams)
3263 338e51e8 Iustin Pop
3264 7baf741d Guido Trotter
    #### instance parameters check
3265 7baf741d Guido Trotter
3266 7baf741d Guido Trotter
    # instance name verification
3267 7baf741d Guido Trotter
    hostname1 = utils.HostInfo(self.op.instance_name)
3268 7baf741d Guido Trotter
    self.op.instance_name = instance_name = hostname1.name
3269 7baf741d Guido Trotter
3270 7baf741d Guido Trotter
    # this is just a preventive check, but someone might still add this
3271 7baf741d Guido Trotter
    # instance in the meantime, and creation will fail at lock-add time
3272 7baf741d Guido Trotter
    if instance_name in self.cfg.GetInstanceList():
3273 7baf741d Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3274 7baf741d Guido Trotter
                                 instance_name)
3275 7baf741d Guido Trotter
3276 7baf741d Guido Trotter
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
3277 7baf741d Guido Trotter
3278 7baf741d Guido Trotter
    # ip validity checks
3279 7baf741d Guido Trotter
    ip = getattr(self.op, "ip", None)
3280 7baf741d Guido Trotter
    if ip is None or ip.lower() == "none":
3281 7baf741d Guido Trotter
      inst_ip = None
3282 7baf741d Guido Trotter
    elif ip.lower() == "auto":
3283 7baf741d Guido Trotter
      inst_ip = hostname1.ip
3284 7baf741d Guido Trotter
    else:
3285 7baf741d Guido Trotter
      if not utils.IsValidIP(ip):
3286 7baf741d Guido Trotter
        raise errors.OpPrereqError("given IP address '%s' doesn't look"
3287 7baf741d Guido Trotter
                                   " like a valid IP" % ip)
3288 7baf741d Guido Trotter
      inst_ip = ip
3289 7baf741d Guido Trotter
    self.inst_ip = self.op.ip = inst_ip
3290 7baf741d Guido Trotter
    # used in CheckPrereq for ip ping check
3291 7baf741d Guido Trotter
    self.check_ip = hostname1.ip
3292 7baf741d Guido Trotter
3293 7baf741d Guido Trotter
    # MAC address verification
3294 7baf741d Guido Trotter
    if self.op.mac != "auto":
3295 7baf741d Guido Trotter
      if not utils.IsValidMac(self.op.mac.lower()):
3296 7baf741d Guido Trotter
        raise errors.OpPrereqError("invalid MAC address specified: %s" %
3297 7baf741d Guido Trotter
                                   self.op.mac)
3298 7baf741d Guido Trotter
3299 7baf741d Guido Trotter
    # file storage checks
3300 7baf741d Guido Trotter
    if (self.op.file_driver and
3301 7baf741d Guido Trotter
        not self.op.file_driver in constants.FILE_DRIVER):
3302 7baf741d Guido Trotter
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3303 7baf741d Guido Trotter
                                 self.op.file_driver)
3304 7baf741d Guido Trotter
3305 7baf741d Guido Trotter
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3306 7baf741d Guido Trotter
      raise errors.OpPrereqError("File storage directory path not absolute")
3307 7baf741d Guido Trotter
3308 7baf741d Guido Trotter
    ### Node/iallocator related checks
3309 7baf741d Guido Trotter
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3310 7baf741d Guido Trotter
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3311 7baf741d Guido Trotter
                                 " node must be given")
3312 7baf741d Guido Trotter
3313 7baf741d Guido Trotter
    if self.op.iallocator:
3314 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3315 7baf741d Guido Trotter
    else:
3316 7baf741d Guido Trotter
      self.op.pnode = self._ExpandNode(self.op.pnode)
3317 7baf741d Guido Trotter
      nodelist = [self.op.pnode]
3318 7baf741d Guido Trotter
      if self.op.snode is not None:
3319 7baf741d Guido Trotter
        self.op.snode = self._ExpandNode(self.op.snode)
3320 7baf741d Guido Trotter
        nodelist.append(self.op.snode)
3321 7baf741d Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = nodelist
3322 7baf741d Guido Trotter
3323 7baf741d Guido Trotter
    # in case of import lock the source node too
3324 7baf741d Guido Trotter
    if self.op.mode == constants.INSTANCE_IMPORT:
3325 7baf741d Guido Trotter
      src_node = getattr(self.op, "src_node", None)
3326 7baf741d Guido Trotter
      src_path = getattr(self.op, "src_path", None)
3327 7baf741d Guido Trotter
3328 7baf741d Guido Trotter
      if src_node is None or src_path is None:
3329 7baf741d Guido Trotter
        raise errors.OpPrereqError("Importing an instance requires source"
3330 7baf741d Guido Trotter
                                   " node and path options")
3331 7baf741d Guido Trotter
3332 7baf741d Guido Trotter
      if not os.path.isabs(src_path):
3333 7baf741d Guido Trotter
        raise errors.OpPrereqError("The source path must be absolute")
3334 7baf741d Guido Trotter
3335 7baf741d Guido Trotter
      self.op.src_node = src_node = self._ExpandNode(src_node)
3336 7baf741d Guido Trotter
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
3337 7baf741d Guido Trotter
        self.needed_locks[locking.LEVEL_NODE].append(src_node)
3338 7baf741d Guido Trotter
3339 7baf741d Guido Trotter
    else: # INSTANCE_CREATE
3340 7baf741d Guido Trotter
      if getattr(self.op, "os_type", None) is None:
3341 7baf741d Guido Trotter
        raise errors.OpPrereqError("No guest OS specified")
3342 a8083063 Iustin Pop
3343 538475ca Iustin Pop
  def _RunAllocator(self):
3344 538475ca Iustin Pop
    """Run the allocator based on input opcode.
3345 538475ca Iustin Pop

3346 538475ca Iustin Pop
    """
3347 538475ca Iustin Pop
    disks = [{"size": self.op.disk_size, "mode": "w"},
3348 538475ca Iustin Pop
             {"size": self.op.swap_size, "mode": "w"}]
3349 538475ca Iustin Pop
    nics = [{"mac": self.op.mac, "ip": getattr(self.op, "ip", None),
3350 538475ca Iustin Pop
             "bridge": self.op.bridge}]
3351 72737a7f Iustin Pop
    ial = IAllocator(self,
3352 29859cb7 Iustin Pop
                     mode=constants.IALLOCATOR_MODE_ALLOC,
3353 d1c2dd75 Iustin Pop
                     name=self.op.instance_name,
3354 d1c2dd75 Iustin Pop
                     disk_template=self.op.disk_template,
3355 d1c2dd75 Iustin Pop
                     tags=[],
3356 d1c2dd75 Iustin Pop
                     os=self.op.os_type,
3357 338e51e8 Iustin Pop
                     vcpus=self.be_full[constants.BE_VCPUS],
3358 338e51e8 Iustin Pop
                     mem_size=self.be_full[constants.BE_MEMORY],
3359 d1c2dd75 Iustin Pop
                     disks=disks,
3360 d1c2dd75 Iustin Pop
                     nics=nics,
3361 29859cb7 Iustin Pop
                     )
3362 d1c2dd75 Iustin Pop
3363 d1c2dd75 Iustin Pop
    ial.Run(self.op.iallocator)
3364 d1c2dd75 Iustin Pop
3365 d1c2dd75 Iustin Pop
    if not ial.success:
3366 538475ca Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
3367 538475ca Iustin Pop
                                 " iallocator '%s': %s" % (self.op.iallocator,
3368 d1c2dd75 Iustin Pop
                                                           ial.info))
3369 27579978 Iustin Pop
    if len(ial.nodes) != ial.required_nodes:
3370 538475ca Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3371 538475ca Iustin Pop
                                 " of nodes (%s), required %s" %
3372 97abc79f Iustin Pop
                                 (self.op.iallocator, len(ial.nodes),
3373 1ce4bbe3 Renรฉ Nussbaumer
                                  ial.required_nodes))
3374 d1c2dd75 Iustin Pop
    self.op.pnode = ial.nodes[0]
3375 538475ca Iustin Pop
    logger.ToStdout("Selected nodes for the instance: %s" %
3376 d1c2dd75 Iustin Pop
                    (", ".join(ial.nodes),))
3377 538475ca Iustin Pop
    logger.Info("Selected nodes for instance %s via iallocator %s: %s" %
3378 d1c2dd75 Iustin Pop
                (self.op.instance_name, self.op.iallocator, ial.nodes))
3379 27579978 Iustin Pop
    if ial.required_nodes == 2:
3380 d1c2dd75 Iustin Pop
      self.op.snode = ial.nodes[1]
3381 538475ca Iustin Pop
3382 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3383 a8083063 Iustin Pop
    """Build hooks env.
3384 a8083063 Iustin Pop

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

3387 a8083063 Iustin Pop
    """
3388 a8083063 Iustin Pop
    env = {
3389 396e1b78 Michael Hanselmann
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
3390 396e1b78 Michael Hanselmann
      "INSTANCE_DISK_SIZE": self.op.disk_size,
3391 396e1b78 Michael Hanselmann
      "INSTANCE_SWAP_SIZE": self.op.swap_size,
3392 a8083063 Iustin Pop
      "INSTANCE_ADD_MODE": self.op.mode,
3393 a8083063 Iustin Pop
      }
3394 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
3395 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_NODE"] = self.op.src_node
3396 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_PATH"] = self.op.src_path
3397 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_IMAGE"] = self.src_image
3398 396e1b78 Michael Hanselmann
3399 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
3400 396e1b78 Michael Hanselmann
      primary_node=self.op.pnode,
3401 396e1b78 Michael Hanselmann
      secondary_nodes=self.secondaries,
3402 396e1b78 Michael Hanselmann
      status=self.instance_status,
3403 ecb215b5 Michael Hanselmann
      os_type=self.op.os_type,
3404 338e51e8 Iustin Pop
      memory=self.be_full[constants.BE_MEMORY],
3405 338e51e8 Iustin Pop
      vcpus=self.be_full[constants.BE_VCPUS],
3406 c7b27e9e Iustin Pop
      nics=[(self.inst_ip, self.op.bridge, self.op.mac)],
3407 396e1b78 Michael Hanselmann
    ))
3408 a8083063 Iustin Pop
3409 d6a02168 Michael Hanselmann
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
3410 a8083063 Iustin Pop
          self.secondaries)
3411 a8083063 Iustin Pop
    return env, nl, nl
3412 a8083063 Iustin Pop
3413 a8083063 Iustin Pop
3414 a8083063 Iustin Pop
  def CheckPrereq(self):
3415 a8083063 Iustin Pop
    """Check prerequisites.
3416 a8083063 Iustin Pop

3417 a8083063 Iustin Pop
    """
3418 eedc99de Manuel Franceschini
    if (not self.cfg.GetVGName() and
3419 eedc99de Manuel Franceschini
        self.op.disk_template not in constants.DTS_NOT_LVM):
3420 eedc99de Manuel Franceschini
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3421 eedc99de Manuel Franceschini
                                 " instances")
3422 eedc99de Manuel Franceschini
3423 e69d05fd Iustin Pop
3424 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
3425 7baf741d Guido Trotter
      src_node = self.op.src_node
3426 7baf741d Guido Trotter
      src_path = self.op.src_path
3427 a8083063 Iustin Pop
3428 72737a7f Iustin Pop
      export_info = self.rpc.call_export_info(src_node, src_path)
3429 a8083063 Iustin Pop
3430 a8083063 Iustin Pop
      if not export_info:
3431 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3432 a8083063 Iustin Pop
3433 a8083063 Iustin Pop
      if not export_info.has_section(constants.INISECT_EXP):
3434 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Corrupted export config")
3435 a8083063 Iustin Pop
3436 a8083063 Iustin Pop
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3437 a8083063 Iustin Pop
      if (int(ei_version) != constants.EXPORT_VERSION):
3438 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3439 3ecf6786 Iustin Pop
                                   (ei_version, constants.EXPORT_VERSION))
3440 a8083063 Iustin Pop
3441 a8083063 Iustin Pop
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
3442 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Can't import instance with more than"
3443 3ecf6786 Iustin Pop
                                   " one data disk")
3444 a8083063 Iustin Pop
3445 a8083063 Iustin Pop
      # FIXME: are the old os-es, disk sizes, etc. useful?
3446 a8083063 Iustin Pop
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3447 a8083063 Iustin Pop
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
3448 a8083063 Iustin Pop
                                                         'disk0_dump'))
3449 a8083063 Iustin Pop
      self.src_image = diskimage
3450 901a65c1 Iustin Pop
3451 7baf741d Guido Trotter
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
3452 901a65c1 Iustin Pop
3453 901a65c1 Iustin Pop
    if self.op.start and not self.op.ip_check:
3454 901a65c1 Iustin Pop
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3455 901a65c1 Iustin Pop
                                 " adding an instance in start mode")
3456 901a65c1 Iustin Pop
3457 901a65c1 Iustin Pop
    if self.op.ip_check:
3458 7baf741d Guido Trotter
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
3459 901a65c1 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3460 7b3a8fb5 Iustin Pop
                                   (self.check_ip, self.op.instance_name))
3461 901a65c1 Iustin Pop
3462 901a65c1 Iustin Pop
    # bridge verification
3463 901a65c1 Iustin Pop
    bridge = getattr(self.op, "bridge", None)
3464 901a65c1 Iustin Pop
    if bridge is None:
3465 901a65c1 Iustin Pop
      self.op.bridge = self.cfg.GetDefBridge()
3466 901a65c1 Iustin Pop
    else:
3467 901a65c1 Iustin Pop
      self.op.bridge = bridge
3468 901a65c1 Iustin Pop
3469 538475ca Iustin Pop
    #### allocator run
3470 538475ca Iustin Pop
3471 538475ca Iustin Pop
    if self.op.iallocator is not None:
3472 538475ca Iustin Pop
      self._RunAllocator()
3473 0f1a06e3 Manuel Franceschini
3474 901a65c1 Iustin Pop
    #### node related checks
3475 901a65c1 Iustin Pop
3476 901a65c1 Iustin Pop
    # check primary node
3477 7baf741d Guido Trotter
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
3478 7baf741d Guido Trotter
    assert self.pnode is not None, \
3479 7baf741d Guido Trotter
      "Cannot retrieve locked node %s" % self.op.pnode
3480 901a65c1 Iustin Pop
    self.secondaries = []
3481 901a65c1 Iustin Pop
3482 901a65c1 Iustin Pop
    # mirror node verification
3483 a1f445d3 Iustin Pop
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3484 7baf741d Guido Trotter
      if self.op.snode is None:
3485 a1f445d3 Iustin Pop
        raise errors.OpPrereqError("The networked disk templates need"
3486 3ecf6786 Iustin Pop
                                   " a mirror node")
3487 7baf741d Guido Trotter
      if self.op.snode == pnode.name:
3488 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The secondary node cannot be"
3489 3ecf6786 Iustin Pop
                                   " the primary node.")
3490 7baf741d Guido Trotter
      self.secondaries.append(self.op.snode)
3491 a8083063 Iustin Pop
3492 6785674e Iustin Pop
    nodenames = [pnode.name] + self.secondaries
3493 6785674e Iustin Pop
3494 e2fe6369 Iustin Pop
    req_size = _ComputeDiskSize(self.op.disk_template,
3495 e2fe6369 Iustin Pop
                                self.op.disk_size, self.op.swap_size)
3496 ed1ebc60 Guido Trotter
3497 8d75db10 Iustin Pop
    # Check lv size requirements
3498 8d75db10 Iustin Pop
    if req_size is not None:
3499 72737a7f Iustin Pop
      nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3500 72737a7f Iustin Pop
                                         self.op.hypervisor)
3501 8d75db10 Iustin Pop
      for node in nodenames:
3502 8d75db10 Iustin Pop
        info = nodeinfo.get(node, None)
3503 8d75db10 Iustin Pop
        if not info:
3504 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Cannot get current information"
3505 3e91897b Iustin Pop
                                     " from node '%s'" % node)
3506 8d75db10 Iustin Pop
        vg_free = info.get('vg_free', None)
3507 8d75db10 Iustin Pop
        if not isinstance(vg_free, int):
3508 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Can't compute free disk space on"
3509 8d75db10 Iustin Pop
                                     " node %s" % node)
3510 8d75db10 Iustin Pop
        if req_size > info['vg_free']:
3511 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Not enough disk space on target node %s."
3512 8d75db10 Iustin Pop
                                     " %d MB available, %d MB required" %
3513 8d75db10 Iustin Pop
                                     (node, info['vg_free'], req_size))
3514 ed1ebc60 Guido Trotter
3515 74409b12 Iustin Pop
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
3516 6785674e Iustin Pop
3517 a8083063 Iustin Pop
    # os verification
3518 72737a7f Iustin Pop
    os_obj = self.rpc.call_os_get(pnode.name, self.op.os_type)
3519 dfa96ded Guido Trotter
    if not os_obj:
3520 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
3521 3ecf6786 Iustin Pop
                                 " primary node"  % self.op.os_type)
3522 a8083063 Iustin Pop
3523 901a65c1 Iustin Pop
    # bridge check on primary node
3524 72737a7f Iustin Pop
    if not self.rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
3525 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("target bridge '%s' does not exist on"
3526 3ecf6786 Iustin Pop
                                 " destination node '%s'" %
3527 3ecf6786 Iustin Pop
                                 (self.op.bridge, pnode.name))
3528 a8083063 Iustin Pop
3529 49ce1563 Iustin Pop
    # memory check on primary node
3530 49ce1563 Iustin Pop
    if self.op.start:
3531 b9bddb6b Iustin Pop
      _CheckNodeFreeMemory(self, self.pnode.name,
3532 49ce1563 Iustin Pop
                           "creating instance %s" % self.op.instance_name,
3533 338e51e8 Iustin Pop
                           self.be_full[constants.BE_MEMORY],
3534 338e51e8 Iustin Pop
                           self.op.hypervisor)
3535 49ce1563 Iustin Pop
3536 a8083063 Iustin Pop
    if self.op.start:
3537 a8083063 Iustin Pop
      self.instance_status = 'up'
3538 a8083063 Iustin Pop
    else:
3539 a8083063 Iustin Pop
      self.instance_status = 'down'
3540 a8083063 Iustin Pop
3541 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3542 a8083063 Iustin Pop
    """Create and add the instance to the cluster.
3543 a8083063 Iustin Pop

3544 a8083063 Iustin Pop
    """
3545 a8083063 Iustin Pop
    instance = self.op.instance_name
3546 a8083063 Iustin Pop
    pnode_name = self.pnode.name
3547 a8083063 Iustin Pop
3548 1862d460 Alexander Schreiber
    if self.op.mac == "auto":
3549 ba4b62cf Iustin Pop
      mac_address = self.cfg.GenerateMAC()
3550 1862d460 Alexander Schreiber
    else:
3551 ba4b62cf Iustin Pop
      mac_address = self.op.mac
3552 1862d460 Alexander Schreiber
3553 1862d460 Alexander Schreiber
    nic = objects.NIC(bridge=self.op.bridge, mac=mac_address)
3554 a8083063 Iustin Pop
    if self.inst_ip is not None:
3555 a8083063 Iustin Pop
      nic.ip = self.inst_ip
3556 a8083063 Iustin Pop
3557 e69d05fd Iustin Pop
    ht_kind = self.op.hypervisor
3558 2a6469d5 Alexander Schreiber
    if ht_kind in constants.HTS_REQ_PORT:
3559 2a6469d5 Alexander Schreiber
      network_port = self.cfg.AllocatePort()
3560 2a6469d5 Alexander Schreiber
    else:
3561 2a6469d5 Alexander Schreiber
      network_port = None
3562 58acb49d Alexander Schreiber
3563 6785674e Iustin Pop
    ##if self.op.vnc_bind_address is None:
3564 6785674e Iustin Pop
    ##  self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
3565 31a853d2 Iustin Pop
3566 2c313123 Manuel Franceschini
    # this is needed because os.path.join does not accept None arguments
3567 2c313123 Manuel Franceschini
    if self.op.file_storage_dir is None:
3568 2c313123 Manuel Franceschini
      string_file_storage_dir = ""
3569 2c313123 Manuel Franceschini
    else:
3570 2c313123 Manuel Franceschini
      string_file_storage_dir = self.op.file_storage_dir
3571 2c313123 Manuel Franceschini
3572 0f1a06e3 Manuel Franceschini
    # build the full file storage dir path
3573 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.normpath(os.path.join(
3574 d6a02168 Michael Hanselmann
                                        self.cfg.GetFileStorageDir(),
3575 2c313123 Manuel Franceschini
                                        string_file_storage_dir, instance))
3576 0f1a06e3 Manuel Franceschini
3577 0f1a06e3 Manuel Franceschini
3578 b9bddb6b Iustin Pop
    disks = _GenerateDiskTemplate(self,
3579 a8083063 Iustin Pop
                                  self.op.disk_template,
3580 a8083063 Iustin Pop
                                  instance, pnode_name,
3581 a8083063 Iustin Pop
                                  self.secondaries, self.op.disk_size,
3582 0f1a06e3 Manuel Franceschini
                                  self.op.swap_size,
3583 0f1a06e3 Manuel Franceschini
                                  file_storage_dir,
3584 0f1a06e3 Manuel Franceschini
                                  self.op.file_driver)
3585 a8083063 Iustin Pop
3586 a8083063 Iustin Pop
    iobj = objects.Instance(name=instance, os=self.op.os_type,
3587 a8083063 Iustin Pop
                            primary_node=pnode_name,
3588 a8083063 Iustin Pop
                            nics=[nic], disks=disks,
3589 a8083063 Iustin Pop
                            disk_template=self.op.disk_template,
3590 a8083063 Iustin Pop
                            status=self.instance_status,
3591 58acb49d Alexander Schreiber
                            network_port=network_port,
3592 338e51e8 Iustin Pop
                            beparams=self.op.beparams,
3593 6785674e Iustin Pop
                            hvparams=self.op.hvparams,
3594 e69d05fd Iustin Pop
                            hypervisor=self.op.hypervisor,
3595 a8083063 Iustin Pop
                            )
3596 a8083063 Iustin Pop
3597 a8083063 Iustin Pop
    feedback_fn("* creating instance disks...")
3598 b9bddb6b Iustin Pop
    if not _CreateDisks(self, iobj):
3599 b9bddb6b Iustin Pop
      _RemoveDisks(self, iobj)
3600 a1578d63 Iustin Pop
      self.cfg.ReleaseDRBDMinors(instance)
3601 3ecf6786 Iustin Pop
      raise errors.OpExecError("Device creation failed, reverting...")
3602 a8083063 Iustin Pop
3603 a8083063 Iustin Pop
    feedback_fn("adding instance %s to cluster config" % instance)
3604 a8083063 Iustin Pop
3605 a8083063 Iustin Pop
    self.cfg.AddInstance(iobj)
3606 7baf741d Guido Trotter
    # Declare that we don't want to remove the instance lock anymore, as we've
3607 7baf741d Guido Trotter
    # added the instance to the config
3608 7baf741d Guido Trotter
    del self.remove_locks[locking.LEVEL_INSTANCE]
3609 a1578d63 Iustin Pop
    # Remove the temp. assignements for the instance's drbds
3610 a1578d63 Iustin Pop
    self.cfg.ReleaseDRBDMinors(instance)
3611 a8083063 Iustin Pop
3612 a8083063 Iustin Pop
    if self.op.wait_for_sync:
3613 b9bddb6b Iustin Pop
      disk_abort = not _WaitForSync(self, iobj)
3614 a1f445d3 Iustin Pop
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
3615 a8083063 Iustin Pop
      # make sure the disks are not degraded (still sync-ing is ok)
3616 a8083063 Iustin Pop
      time.sleep(15)
3617 a8083063 Iustin Pop
      feedback_fn("* checking mirrors status")
3618 b9bddb6b Iustin Pop
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
3619 a8083063 Iustin Pop
    else:
3620 a8083063 Iustin Pop
      disk_abort = False
3621 a8083063 Iustin Pop
3622 a8083063 Iustin Pop
    if disk_abort:
3623 b9bddb6b Iustin Pop
      _RemoveDisks(self, iobj)
3624 a8083063 Iustin Pop
      self.cfg.RemoveInstance(iobj.name)
3625 7baf741d Guido Trotter
      # Make sure the instance lock gets removed
3626 7baf741d Guido Trotter
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
3627 3ecf6786 Iustin Pop
      raise errors.OpExecError("There are some degraded disks for"
3628 3ecf6786 Iustin Pop
                               " this instance")
3629 a8083063 Iustin Pop
3630 a8083063 Iustin Pop
    feedback_fn("creating os for instance %s on node %s" %
3631 a8083063 Iustin Pop
                (instance, pnode_name))
3632 a8083063 Iustin Pop
3633 a8083063 Iustin Pop
    if iobj.disk_template != constants.DT_DISKLESS:
3634 a8083063 Iustin Pop
      if self.op.mode == constants.INSTANCE_CREATE:
3635 a8083063 Iustin Pop
        feedback_fn("* running the instance OS create scripts...")
3636 72737a7f Iustin Pop
        if not self.rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
3637 3ecf6786 Iustin Pop
          raise errors.OpExecError("could not add os for instance %s"
3638 3ecf6786 Iustin Pop
                                   " on node %s" %
3639 3ecf6786 Iustin Pop
                                   (instance, pnode_name))
3640 a8083063 Iustin Pop
3641 a8083063 Iustin Pop
      elif self.op.mode == constants.INSTANCE_IMPORT:
3642 a8083063 Iustin Pop
        feedback_fn("* running the instance OS import scripts...")
3643 a8083063 Iustin Pop
        src_node = self.op.src_node
3644 a8083063 Iustin Pop
        src_image = self.src_image
3645 62c9ec92 Iustin Pop
        cluster_name = self.cfg.GetClusterName()
3646 72737a7f Iustin Pop
        if not self.rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
3647 72737a7f Iustin Pop
                                                src_node, src_image,
3648 72737a7f Iustin Pop
                                                cluster_name):
3649 3ecf6786 Iustin Pop
          raise errors.OpExecError("Could not import os for instance"
3650 3ecf6786 Iustin Pop
                                   " %s on node %s" %
3651 3ecf6786 Iustin Pop
                                   (instance, pnode_name))
3652 a8083063 Iustin Pop
      else:
3653 a8083063 Iustin Pop
        # also checked in the prereq part
3654 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
3655 3ecf6786 Iustin Pop
                                     % self.op.mode)
3656 a8083063 Iustin Pop
3657 a8083063 Iustin Pop
    if self.op.start:
3658 a8083063 Iustin Pop
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
3659 a8083063 Iustin Pop
      feedback_fn("* starting instance...")
3660 72737a7f Iustin Pop
      if not self.rpc.call_instance_start(pnode_name, iobj, None):
3661 3ecf6786 Iustin Pop
        raise errors.OpExecError("Could not start instance")
3662 a8083063 Iustin Pop
3663 a8083063 Iustin Pop
3664 a8083063 Iustin Pop
class LUConnectConsole(NoHooksLU):
3665 a8083063 Iustin Pop
  """Connect to an instance's console.
3666 a8083063 Iustin Pop

3667 a8083063 Iustin Pop
  This is somewhat special in that it returns the command line that
3668 a8083063 Iustin Pop
  you need to run on the master node in order to connect to the
3669 a8083063 Iustin Pop
  console.
3670 a8083063 Iustin Pop

3671 a8083063 Iustin Pop
  """
3672 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
3673 8659b73e Guido Trotter
  REQ_BGL = False
3674 8659b73e Guido Trotter
3675 8659b73e Guido Trotter
  def ExpandNames(self):
3676 8659b73e Guido Trotter
    self._ExpandAndLockInstance()
3677 a8083063 Iustin Pop
3678 a8083063 Iustin Pop
  def CheckPrereq(self):
3679 a8083063 Iustin Pop
    """Check prerequisites.
3680 a8083063 Iustin Pop

3681 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3682 a8083063 Iustin Pop

3683 a8083063 Iustin Pop
    """
3684 8659b73e Guido Trotter
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3685 8659b73e Guido Trotter
    assert self.instance is not None, \
3686 8659b73e Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3687 a8083063 Iustin Pop
3688 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3689 a8083063 Iustin Pop
    """Connect to the console of an instance
3690 a8083063 Iustin Pop

3691 a8083063 Iustin Pop
    """
3692 a8083063 Iustin Pop
    instance = self.instance
3693 a8083063 Iustin Pop
    node = instance.primary_node
3694 a8083063 Iustin Pop
3695 72737a7f Iustin Pop
    node_insts = self.rpc.call_instance_list([node],
3696 72737a7f Iustin Pop
                                             [instance.hypervisor])[node]
3697 a8083063 Iustin Pop
    if node_insts is False:
3698 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't connect to node %s." % node)
3699 a8083063 Iustin Pop
3700 a8083063 Iustin Pop
    if instance.name not in node_insts:
3701 3ecf6786 Iustin Pop
      raise errors.OpExecError("Instance %s is not running." % instance.name)
3702 a8083063 Iustin Pop
3703 a8083063 Iustin Pop
    logger.Debug("connecting to console of %s on %s" % (instance.name, node))
3704 a8083063 Iustin Pop
3705 e69d05fd Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
3706 30989e69 Alexander Schreiber
    console_cmd = hyper.GetShellCommandForConsole(instance)
3707 b047857b Michael Hanselmann
3708 82122173 Iustin Pop
    # build ssh cmdline
3709 0a80a26f Michael Hanselmann
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
3710 a8083063 Iustin Pop
3711 a8083063 Iustin Pop
3712 a8083063 Iustin Pop
class LUReplaceDisks(LogicalUnit):
3713 a8083063 Iustin Pop
  """Replace the disks of an instance.
3714 a8083063 Iustin Pop

3715 a8083063 Iustin Pop
  """
3716 a8083063 Iustin Pop
  HPATH = "mirrors-replace"
3717 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3718 a9e0c397 Iustin Pop
  _OP_REQP = ["instance_name", "mode", "disks"]
3719 efd990e4 Guido Trotter
  REQ_BGL = False
3720 efd990e4 Guido Trotter
3721 efd990e4 Guido Trotter
  def ExpandNames(self):
3722 efd990e4 Guido Trotter
    self._ExpandAndLockInstance()
3723 efd990e4 Guido Trotter
3724 efd990e4 Guido Trotter
    if not hasattr(self.op, "remote_node"):
3725 efd990e4 Guido Trotter
      self.op.remote_node = None
3726 efd990e4 Guido Trotter
3727 efd990e4 Guido Trotter
    ia_name = getattr(self.op, "iallocator", None)
3728 efd990e4 Guido Trotter
    if ia_name is not None:
3729 efd990e4 Guido Trotter
      if self.op.remote_node is not None:
3730 efd990e4 Guido Trotter
        raise errors.OpPrereqError("Give either the iallocator or the new"
3731 efd990e4 Guido Trotter
                                   " secondary, not both")
3732 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3733 efd990e4 Guido Trotter
    elif self.op.remote_node is not None:
3734 efd990e4 Guido Trotter
      remote_node = self.cfg.ExpandNodeName(self.op.remote_node)
3735 efd990e4 Guido Trotter
      if remote_node is None:
3736 efd990e4 Guido Trotter
        raise errors.OpPrereqError("Node '%s' not known" %
3737 efd990e4 Guido Trotter
                                   self.op.remote_node)
3738 efd990e4 Guido Trotter
      self.op.remote_node = remote_node
3739 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
3740 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
3741 efd990e4 Guido Trotter
    else:
3742 efd990e4 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = []
3743 efd990e4 Guido Trotter
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3744 efd990e4 Guido Trotter
3745 efd990e4 Guido Trotter
  def DeclareLocks(self, level):
3746 efd990e4 Guido Trotter
    # If we're not already locking all nodes in the set we have to declare the
3747 efd990e4 Guido Trotter
    # instance's primary/secondary nodes.
3748 efd990e4 Guido Trotter
    if (level == locking.LEVEL_NODE and
3749 efd990e4 Guido Trotter
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
3750 efd990e4 Guido Trotter
      self._LockInstancesNodes()
3751 a8083063 Iustin Pop
3752 b6e82a65 Iustin Pop
  def _RunAllocator(self):
3753 b6e82a65 Iustin Pop
    """Compute a new secondary node using an IAllocator.
3754 b6e82a65 Iustin Pop

3755 b6e82a65 Iustin Pop
    """
3756 72737a7f Iustin Pop
    ial = IAllocator(self,
3757 b6e82a65 Iustin Pop
                     mode=constants.IALLOCATOR_MODE_RELOC,
3758 b6e82a65 Iustin Pop
                     name=self.op.instance_name,
3759 b6e82a65 Iustin Pop
                     relocate_from=[self.sec_node])
3760 b6e82a65 Iustin Pop
3761 b6e82a65 Iustin Pop
    ial.Run(self.op.iallocator)
3762 b6e82a65 Iustin Pop
3763 b6e82a65 Iustin Pop
    if not ial.success:
3764 b6e82a65 Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
3765 b6e82a65 Iustin Pop
                                 " iallocator '%s': %s" % (self.op.iallocator,
3766 b6e82a65 Iustin Pop
                                                           ial.info))
3767 b6e82a65 Iustin Pop
    if len(ial.nodes) != ial.required_nodes:
3768 b6e82a65 Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3769 b6e82a65 Iustin Pop
                                 " of nodes (%s), required %s" %
3770 b6e82a65 Iustin Pop
                                 (len(ial.nodes), ial.required_nodes))
3771 b6e82a65 Iustin Pop
    self.op.remote_node = ial.nodes[0]
3772 b6e82a65 Iustin Pop
    logger.ToStdout("Selected new secondary for the instance: %s" %
3773 b6e82a65 Iustin Pop
                    self.op.remote_node)
3774 b6e82a65 Iustin Pop
3775 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3776 a8083063 Iustin Pop
    """Build hooks env.
3777 a8083063 Iustin Pop

3778 a8083063 Iustin Pop
    This runs on the master, the primary and all the secondaries.
3779 a8083063 Iustin Pop

3780 a8083063 Iustin Pop
    """
3781 a8083063 Iustin Pop
    env = {
3782 a9e0c397 Iustin Pop
      "MODE": self.op.mode,
3783 a8083063 Iustin Pop
      "NEW_SECONDARY": self.op.remote_node,
3784 a8083063 Iustin Pop
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3785 a8083063 Iustin Pop
      }
3786 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
3787 0834c866 Iustin Pop
    nl = [
3788 d6a02168 Michael Hanselmann
      self.cfg.GetMasterNode(),
3789 0834c866 Iustin Pop
      self.instance.primary_node,
3790 0834c866 Iustin Pop
      ]
3791 0834c866 Iustin Pop
    if self.op.remote_node is not None:
3792 0834c866 Iustin Pop
      nl.append(self.op.remote_node)
3793 a8083063 Iustin Pop
    return env, nl, nl
3794 a8083063 Iustin Pop
3795 a8083063 Iustin Pop
  def CheckPrereq(self):
3796 a8083063 Iustin Pop
    """Check prerequisites.
3797 a8083063 Iustin Pop

3798 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3799 a8083063 Iustin Pop

3800 a8083063 Iustin Pop
    """
3801 efd990e4 Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3802 efd990e4 Guido Trotter
    assert instance is not None, \
3803 efd990e4 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
3804 a8083063 Iustin Pop
    self.instance = instance
3805 a8083063 Iustin Pop
3806 a9e0c397 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3807 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout is not"
3808 a9e0c397 Iustin Pop
                                 " network mirrored.")
3809 a8083063 Iustin Pop
3810 a8083063 Iustin Pop
    if len(instance.secondary_nodes) != 1:
3811 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The instance has a strange layout,"
3812 3ecf6786 Iustin Pop
                                 " expected one secondary but found %d" %
3813 3ecf6786 Iustin Pop
                                 len(instance.secondary_nodes))
3814 a8083063 Iustin Pop
3815 a9e0c397 Iustin Pop
    self.sec_node = instance.secondary_nodes[0]
3816 a9e0c397 Iustin Pop
3817 b6e82a65 Iustin Pop
    ia_name = getattr(self.op, "iallocator", None)
3818 b6e82a65 Iustin Pop
    if ia_name is not None:
3819 de8c7666 Guido Trotter
      self._RunAllocator()
3820 b6e82a65 Iustin Pop
3821 b6e82a65 Iustin Pop
    remote_node = self.op.remote_node
3822 a9e0c397 Iustin Pop
    if remote_node is not None:
3823 a9e0c397 Iustin Pop
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
3824 efd990e4 Guido Trotter
      assert self.remote_node_info is not None, \
3825 efd990e4 Guido Trotter
        "Cannot retrieve locked node %s" % remote_node
3826 a9e0c397 Iustin Pop
    else:
3827 a9e0c397 Iustin Pop
      self.remote_node_info = None
3828 a8083063 Iustin Pop
    if remote_node == instance.primary_node:
3829 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The specified node is the primary node of"
3830 3ecf6786 Iustin Pop
                                 " the instance.")
3831 a9e0c397 Iustin Pop
    elif remote_node == self.sec_node:
3832 0834c866 Iustin Pop
      if self.op.mode == constants.REPLACE_DISK_SEC:
3833 0834c866 Iustin Pop
        # this is for DRBD8, where we can't execute the same mode of
3834 0834c866 Iustin Pop
        # replacement as for drbd7 (no different port allocated)
3835 0834c866 Iustin Pop
        raise errors.OpPrereqError("Same secondary given, cannot execute"
3836 0834c866 Iustin Pop
                                   " replacement")
3837 a9e0c397 Iustin Pop
    if instance.disk_template == constants.DT_DRBD8:
3838 7df43a76 Iustin Pop
      if (self.op.mode == constants.REPLACE_DISK_ALL and
3839 7df43a76 Iustin Pop
          remote_node is not None):
3840 7df43a76 Iustin Pop
        # switch to replace secondary mode
3841 7df43a76 Iustin Pop
        self.op.mode = constants.REPLACE_DISK_SEC
3842 7df43a76 Iustin Pop
3843 a9e0c397 Iustin Pop
      if self.op.mode == constants.REPLACE_DISK_ALL:
3844 12c3449a Michael Hanselmann
        raise errors.OpPrereqError("Template 'drbd' only allows primary or"
3845 a9e0c397 Iustin Pop
                                   " secondary disk replacement, not"
3846 a9e0c397 Iustin Pop
                                   " both at once")
3847 a9e0c397 Iustin Pop
      elif self.op.mode == constants.REPLACE_DISK_PRI:
3848 a9e0c397 Iustin Pop
        if remote_node is not None:
3849 12c3449a Michael Hanselmann
          raise errors.OpPrereqError("Template 'drbd' does not allow changing"
3850 a9e0c397 Iustin Pop
                                     " the secondary while doing a primary"
3851 a9e0c397 Iustin Pop
                                     " node disk replacement")
3852 a9e0c397 Iustin Pop
        self.tgt_node = instance.primary_node
3853 cff90b79 Iustin Pop
        self.oth_node = instance.secondary_nodes[0]
3854 a9e0c397 Iustin Pop
      elif self.op.mode == constants.REPLACE_DISK_SEC:
3855 a9e0c397 Iustin Pop
        self.new_node = remote_node # this can be None, in which case
3856 a9e0c397 Iustin Pop
                                    # we don't change the secondary
3857 a9e0c397 Iustin Pop
        self.tgt_node = instance.secondary_nodes[0]
3858 cff90b79 Iustin Pop
        self.oth_node = instance.primary_node
3859 a9e0c397 Iustin Pop
      else:
3860 a9e0c397 Iustin Pop
        raise errors.ProgrammerError("Unhandled disk replace mode")
3861 a9e0c397 Iustin Pop
3862 a9e0c397 Iustin Pop
    for name in self.op.disks:
3863 a9e0c397 Iustin Pop
      if instance.FindDisk(name) is None:
3864 a9e0c397 Iustin Pop
        raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3865 a9e0c397 Iustin Pop
                                   (name, instance.name))
3866 a8083063 Iustin Pop
3867 a9e0c397 Iustin Pop
  def _ExecD8DiskOnly(self, feedback_fn):
3868 a9e0c397 Iustin Pop
    """Replace a disk on the primary or secondary for dbrd8.
3869 a9e0c397 Iustin Pop

3870 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
3871 a9e0c397 Iustin Pop
      - for each disk to be replaced:
3872 a9e0c397 Iustin Pop
        - create new LVs on the target node with unique names
3873 a9e0c397 Iustin Pop
        - detach old LVs from the drbd device
3874 a9e0c397 Iustin Pop
        - rename old LVs to name_replaced.<time_t>
3875 a9e0c397 Iustin Pop
        - rename new LVs to old LVs
3876 a9e0c397 Iustin Pop
        - attach the new LVs (with the old names now) to the drbd device
3877 a9e0c397 Iustin Pop
      - wait for sync across all devices
3878 a9e0c397 Iustin Pop
      - for each modified disk:
3879 a9e0c397 Iustin Pop
        - remove old LVs (which have the name name_replaces.<time_t>)
3880 a9e0c397 Iustin Pop

3881 a9e0c397 Iustin Pop
    Failures are not very well handled.
3882 cff90b79 Iustin Pop

3883 a9e0c397 Iustin Pop
    """
3884 cff90b79 Iustin Pop
    steps_total = 6
3885 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3886 a9e0c397 Iustin Pop
    instance = self.instance
3887 a9e0c397 Iustin Pop
    iv_names = {}
3888 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
3889 a9e0c397 Iustin Pop
    # start of work
3890 a9e0c397 Iustin Pop
    cfg = self.cfg
3891 a9e0c397 Iustin Pop
    tgt_node = self.tgt_node
3892 cff90b79 Iustin Pop
    oth_node = self.oth_node
3893 cff90b79 Iustin Pop
3894 cff90b79 Iustin Pop
    # Step: check device activation
3895 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
3896 cff90b79 Iustin Pop
    info("checking volume groups")
3897 cff90b79 Iustin Pop
    my_vg = cfg.GetVGName()
3898 72737a7f Iustin Pop
    results = self.rpc.call_vg_list([oth_node, tgt_node])
3899 cff90b79 Iustin Pop
    if not results:
3900 cff90b79 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
3901 cff90b79 Iustin Pop
    for node in oth_node, tgt_node:
3902 cff90b79 Iustin Pop
      res = results.get(node, False)
3903 cff90b79 Iustin Pop
      if not res or my_vg not in res:
3904 cff90b79 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3905 cff90b79 Iustin Pop
                                 (my_vg, node))
3906 cff90b79 Iustin Pop
    for dev in instance.disks:
3907 cff90b79 Iustin Pop
      if not dev.iv_name in self.op.disks:
3908 cff90b79 Iustin Pop
        continue
3909 cff90b79 Iustin Pop
      for node in tgt_node, oth_node:
3910 cff90b79 Iustin Pop
        info("checking %s on %s" % (dev.iv_name, node))
3911 cff90b79 Iustin Pop
        cfg.SetDiskID(dev, node)
3912 72737a7f Iustin Pop
        if not self.rpc.call_blockdev_find(node, dev):
3913 cff90b79 Iustin Pop
          raise errors.OpExecError("Can't find device %s on node %s" %
3914 cff90b79 Iustin Pop
                                   (dev.iv_name, node))
3915 cff90b79 Iustin Pop
3916 cff90b79 Iustin Pop
    # Step: check other node consistency
3917 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
3918 cff90b79 Iustin Pop
    for dev in instance.disks:
3919 cff90b79 Iustin Pop
      if not dev.iv_name in self.op.disks:
3920 cff90b79 Iustin Pop
        continue
3921 cff90b79 Iustin Pop
      info("checking %s consistency on %s" % (dev.iv_name, oth_node))
3922 b9bddb6b Iustin Pop
      if not _CheckDiskConsistency(self, dev, oth_node,
3923 cff90b79 Iustin Pop
                                   oth_node==instance.primary_node):
3924 cff90b79 Iustin Pop
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
3925 cff90b79 Iustin Pop
                                 " to replace disks on this node (%s)" %
3926 cff90b79 Iustin Pop
                                 (oth_node, tgt_node))
3927 cff90b79 Iustin Pop
3928 cff90b79 Iustin Pop
    # Step: create new storage
3929 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
3930 a9e0c397 Iustin Pop
    for dev in instance.disks:
3931 a9e0c397 Iustin Pop
      if not dev.iv_name in self.op.disks:
3932 a9e0c397 Iustin Pop
        continue
3933 a9e0c397 Iustin Pop
      size = dev.size
3934 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, tgt_node)
3935 a9e0c397 Iustin Pop
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3936 b9bddb6b Iustin Pop
      names = _GenerateUniqueNames(self, lv_names)
3937 a9e0c397 Iustin Pop
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3938 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[0]))
3939 a9e0c397 Iustin Pop
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3940 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[1]))
3941 a9e0c397 Iustin Pop
      new_lvs = [lv_data, lv_meta]
3942 a9e0c397 Iustin Pop
      old_lvs = dev.children
3943 a9e0c397 Iustin Pop
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
3944 cff90b79 Iustin Pop
      info("creating new local storage on %s for %s" %
3945 cff90b79 Iustin Pop
           (tgt_node, dev.iv_name))
3946 a9e0c397 Iustin Pop
      # since we *always* want to create this LV, we use the
3947 a9e0c397 Iustin Pop
      # _Create...OnPrimary (which forces the creation), even if we
3948 a9e0c397 Iustin Pop
      # are talking about the secondary node
3949 a9e0c397 Iustin Pop
      for new_lv in new_lvs:
3950 b9bddb6b Iustin Pop
        if not _CreateBlockDevOnPrimary(self, tgt_node, instance, new_lv,
3951 a9e0c397 Iustin Pop
                                        _GetInstanceInfoText(instance)):
3952 a9e0c397 Iustin Pop
          raise errors.OpExecError("Failed to create new LV named '%s' on"
3953 a9e0c397 Iustin Pop
                                   " node '%s'" %
3954 a9e0c397 Iustin Pop
                                   (new_lv.logical_id[1], tgt_node))
3955 a9e0c397 Iustin Pop
3956 cff90b79 Iustin Pop
    # Step: for each lv, detach+rename*2+attach
3957 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "change drbd configuration")
3958 cff90b79 Iustin Pop
    for dev, old_lvs, new_lvs in iv_names.itervalues():
3959 cff90b79 Iustin Pop
      info("detaching %s drbd from local storage" % dev.iv_name)
3960 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs):
3961 a9e0c397 Iustin Pop
        raise errors.OpExecError("Can't detach drbd from local storage on node"
3962 a9e0c397 Iustin Pop
                                 " %s for device %s" % (tgt_node, dev.iv_name))
3963 cff90b79 Iustin Pop
      #dev.children = []
3964 cff90b79 Iustin Pop
      #cfg.Update(instance)
3965 a9e0c397 Iustin Pop
3966 a9e0c397 Iustin Pop
      # ok, we created the new LVs, so now we know we have the needed
3967 a9e0c397 Iustin Pop
      # storage; as such, we proceed on the target node to rename
3968 a9e0c397 Iustin Pop
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
3969 c99a3cc0 Manuel Franceschini
      # using the assumption that logical_id == physical_id (which in
3970 a9e0c397 Iustin Pop
      # turn is the unique_id on that node)
3971 cff90b79 Iustin Pop
3972 cff90b79 Iustin Pop
      # FIXME(iustin): use a better name for the replaced LVs
3973 a9e0c397 Iustin Pop
      temp_suffix = int(time.time())
3974 a9e0c397 Iustin Pop
      ren_fn = lambda d, suff: (d.physical_id[0],
3975 a9e0c397 Iustin Pop
                                d.physical_id[1] + "_replaced-%s" % suff)
3976 cff90b79 Iustin Pop
      # build the rename list based on what LVs exist on the node
3977 cff90b79 Iustin Pop
      rlist = []
3978 cff90b79 Iustin Pop
      for to_ren in old_lvs:
3979 72737a7f Iustin Pop
        find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
3980 cff90b79 Iustin Pop
        if find_res is not None: # device exists
3981 cff90b79 Iustin Pop
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
3982 cff90b79 Iustin Pop
3983 cff90b79 Iustin Pop
      info("renaming the old LVs on the target node")
3984 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_rename(tgt_node, rlist):
3985 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
3986 a9e0c397 Iustin Pop
      # now we rename the new LVs to the old LVs
3987 cff90b79 Iustin Pop
      info("renaming the new LVs on the target node")
3988 a9e0c397 Iustin Pop
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
3989 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_rename(tgt_node, rlist):
3990 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
3991 cff90b79 Iustin Pop
3992 cff90b79 Iustin Pop
      for old, new in zip(old_lvs, new_lvs):
3993 cff90b79 Iustin Pop
        new.logical_id = old.logical_id
3994 cff90b79 Iustin Pop
        cfg.SetDiskID(new, tgt_node)
3995 a9e0c397 Iustin Pop
3996 cff90b79 Iustin Pop
      for disk in old_lvs:
3997 cff90b79 Iustin Pop
        disk.logical_id = ren_fn(disk, temp_suffix)
3998 cff90b79 Iustin Pop
        cfg.SetDiskID(disk, tgt_node)
3999 a9e0c397 Iustin Pop
4000 a9e0c397 Iustin Pop
      # now that the new lvs have the old name, we can add them to the device
4001 cff90b79 Iustin Pop
      info("adding new mirror component on %s" % tgt_node)
4002 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs):
4003 a9e0c397 Iustin Pop
        for new_lv in new_lvs:
4004 72737a7f Iustin Pop
          if not self.rpc.call_blockdev_remove(tgt_node, new_lv):
4005 79caa9ed Guido Trotter
            warning("Can't rollback device %s", hint="manually cleanup unused"
4006 cff90b79 Iustin Pop
                    " logical volumes")
4007 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't add local storage to drbd")
4008 a9e0c397 Iustin Pop
4009 a9e0c397 Iustin Pop
      dev.children = new_lvs
4010 a9e0c397 Iustin Pop
      cfg.Update(instance)
4011 a9e0c397 Iustin Pop
4012 cff90b79 Iustin Pop
    # Step: wait for sync
4013 a9e0c397 Iustin Pop
4014 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
4015 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
4016 a9e0c397 Iustin Pop
    # return value
4017 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
4018 b9bddb6b Iustin Pop
    _WaitForSync(self, instance, unlock=True)
4019 a9e0c397 Iustin Pop
4020 a9e0c397 Iustin Pop
    # so check manually all the devices
4021 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4022 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, instance.primary_node)
4023 72737a7f Iustin Pop
      is_degr = self.rpc.call_blockdev_find(instance.primary_node, dev)[5]
4024 a9e0c397 Iustin Pop
      if is_degr:
4025 a9e0c397 Iustin Pop
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4026 a9e0c397 Iustin Pop
4027 cff90b79 Iustin Pop
    # Step: remove old storage
4028 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
4029 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
4030 cff90b79 Iustin Pop
      info("remove logical volumes for %s" % name)
4031 a9e0c397 Iustin Pop
      for lv in old_lvs:
4032 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, tgt_node)
4033 72737a7f Iustin Pop
        if not self.rpc.call_blockdev_remove(tgt_node, lv):
4034 79caa9ed Guido Trotter
          warning("Can't remove old LV", hint="manually remove unused LVs")
4035 a9e0c397 Iustin Pop
          continue
4036 a9e0c397 Iustin Pop
4037 a9e0c397 Iustin Pop
  def _ExecD8Secondary(self, feedback_fn):
4038 a9e0c397 Iustin Pop
    """Replace the secondary node for drbd8.
4039 a9e0c397 Iustin Pop

4040 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
4041 a9e0c397 Iustin Pop
      - for all disks of the instance:
4042 a9e0c397 Iustin Pop
        - create new LVs on the new node with same names
4043 a9e0c397 Iustin Pop
        - shutdown the drbd device on the old secondary
4044 a9e0c397 Iustin Pop
        - disconnect the drbd network on the primary
4045 a9e0c397 Iustin Pop
        - create the drbd device on the new secondary
4046 a9e0c397 Iustin Pop
        - network attach the drbd on the primary, using an artifice:
4047 a9e0c397 Iustin Pop
          the drbd code for Attach() will connect to the network if it
4048 a9e0c397 Iustin Pop
          finds a device which is connected to the good local disks but
4049 a9e0c397 Iustin Pop
          not network enabled
4050 a9e0c397 Iustin Pop
      - wait for sync across all devices
4051 a9e0c397 Iustin Pop
      - remove all disks from the old secondary
4052 a9e0c397 Iustin Pop

4053 a9e0c397 Iustin Pop
    Failures are not very well handled.
4054 0834c866 Iustin Pop

4055 a9e0c397 Iustin Pop
    """
4056 0834c866 Iustin Pop
    steps_total = 6
4057 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
4058 a9e0c397 Iustin Pop
    instance = self.instance
4059 a9e0c397 Iustin Pop
    iv_names = {}
4060 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
4061 a9e0c397 Iustin Pop
    # start of work
4062 a9e0c397 Iustin Pop
    cfg = self.cfg
4063 a9e0c397 Iustin Pop
    old_node = self.tgt_node
4064 a9e0c397 Iustin Pop
    new_node = self.new_node
4065 a9e0c397 Iustin Pop
    pri_node = instance.primary_node
4066 0834c866 Iustin Pop
4067 0834c866 Iustin Pop
    # Step: check device activation
4068 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
4069 0834c866 Iustin Pop
    info("checking volume groups")
4070 0834c866 Iustin Pop
    my_vg = cfg.GetVGName()
4071 72737a7f Iustin Pop
    results = self.rpc.call_vg_list([pri_node, new_node])
4072 0834c866 Iustin Pop
    if not results:
4073 0834c866 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
4074 0834c866 Iustin Pop
    for node in pri_node, new_node:
4075 0834c866 Iustin Pop
      res = results.get(node, False)
4076 0834c866 Iustin Pop
      if not res or my_vg not in res:
4077 0834c866 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
4078 0834c866 Iustin Pop
                                 (my_vg, node))
4079 0834c866 Iustin Pop
    for dev in instance.disks:
4080 0834c866 Iustin Pop
      if not dev.iv_name in self.op.disks:
4081 0834c866 Iustin Pop
        continue
4082 0834c866 Iustin Pop
      info("checking %s on %s" % (dev.iv_name, pri_node))
4083 0834c866 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4084 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_find(pri_node, dev):
4085 0834c866 Iustin Pop
        raise errors.OpExecError("Can't find device %s on node %s" %
4086 0834c866 Iustin Pop
                                 (dev.iv_name, pri_node))
4087 0834c866 Iustin Pop
4088 0834c866 Iustin Pop
    # Step: check other node consistency
4089 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
4090 0834c866 Iustin Pop
    for dev in instance.disks:
4091 0834c866 Iustin Pop
      if not dev.iv_name in self.op.disks:
4092 0834c866 Iustin Pop
        continue
4093 0834c866 Iustin Pop
      info("checking %s consistency on %s" % (dev.iv_name, pri_node))
4094 b9bddb6b Iustin Pop
      if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True):
4095 0834c866 Iustin Pop
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4096 0834c866 Iustin Pop
                                 " unsafe to replace the secondary" %
4097 0834c866 Iustin Pop
                                 pri_node)
4098 0834c866 Iustin Pop
4099 0834c866 Iustin Pop
    # Step: create new storage
4100 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
4101 468b46f9 Iustin Pop
    for dev in instance.disks:
4102 a9e0c397 Iustin Pop
      size = dev.size
4103 0834c866 Iustin Pop
      info("adding new local storage on %s for %s" % (new_node, dev.iv_name))
4104 a9e0c397 Iustin Pop
      # since we *always* want to create this LV, we use the
4105 a9e0c397 Iustin Pop
      # _Create...OnPrimary (which forces the creation), even if we
4106 a9e0c397 Iustin Pop
      # are talking about the secondary node
4107 a9e0c397 Iustin Pop
      for new_lv in dev.children:
4108 b9bddb6b Iustin Pop
        if not _CreateBlockDevOnPrimary(self, new_node, instance, new_lv,
4109 a9e0c397 Iustin Pop
                                        _GetInstanceInfoText(instance)):
4110 a9e0c397 Iustin Pop
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4111 a9e0c397 Iustin Pop
                                   " node '%s'" %
4112 a9e0c397 Iustin Pop
                                   (new_lv.logical_id[1], new_node))
4113 a9e0c397 Iustin Pop
4114 0834c866 Iustin Pop
4115 468b46f9 Iustin Pop
    # Step 4: dbrd minors and drbd setups changes
4116 a1578d63 Iustin Pop
    # after this, we must manually remove the drbd minors on both the
4117 a1578d63 Iustin Pop
    # error and the success paths
4118 a1578d63 Iustin Pop
    minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks],
4119 a1578d63 Iustin Pop
                                   instance.name)
4120 468b46f9 Iustin Pop
    logging.debug("Allocated minors %s" % (minors,))
4121 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
4122 468b46f9 Iustin Pop
    for dev, new_minor in zip(instance.disks, minors):
4123 0834c866 Iustin Pop
      size = dev.size
4124 0834c866 Iustin Pop
      info("activating a new drbd on %s for %s" % (new_node, dev.iv_name))
4125 a9e0c397 Iustin Pop
      # create new devices on new_node
4126 ffa1c0dc Iustin Pop
      if pri_node == dev.logical_id[0]:
4127 ffa1c0dc Iustin Pop
        new_logical_id = (pri_node, new_node,
4128 f9518d38 Iustin Pop
                          dev.logical_id[2], dev.logical_id[3], new_minor,
4129 f9518d38 Iustin Pop
                          dev.logical_id[5])
4130 ffa1c0dc Iustin Pop
      else:
4131 ffa1c0dc Iustin Pop
        new_logical_id = (new_node, pri_node,
4132 f9518d38 Iustin Pop
                          dev.logical_id[2], new_minor, dev.logical_id[4],
4133 f9518d38 Iustin Pop
                          dev.logical_id[5])
4134 468b46f9 Iustin Pop
      iv_names[dev.iv_name] = (dev, dev.children, new_logical_id)
4135 a1578d63 Iustin Pop
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
4136 a1578d63 Iustin Pop
                    new_logical_id)
4137 a9e0c397 Iustin Pop
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
4138 ffa1c0dc Iustin Pop
                              logical_id=new_logical_id,
4139 a9e0c397 Iustin Pop
                              children=dev.children)
4140 b9bddb6b Iustin Pop
      if not _CreateBlockDevOnSecondary(self, new_node, instance,
4141 3f78eef2 Iustin Pop
                                        new_drbd, False,
4142 b9bddb6b Iustin Pop
                                        _GetInstanceInfoText(instance)):
4143 a1578d63 Iustin Pop
        self.cfg.ReleaseDRBDMinors(instance.name)
4144 a9e0c397 Iustin Pop
        raise errors.OpExecError("Failed to create new DRBD on"
4145 a9e0c397 Iustin Pop
                                 " node '%s'" % new_node)
4146 a9e0c397 Iustin Pop
4147 0834c866 Iustin Pop
    for dev in instance.disks:
4148 a9e0c397 Iustin Pop
      # we have new devices, shutdown the drbd on the old secondary
4149 0834c866 Iustin Pop
      info("shutting down drbd for %s on old node" % dev.iv_name)
4150 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, old_node)
4151 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_shutdown(old_node, dev):
4152 0834c866 Iustin Pop
        warning("Failed to shutdown drbd for %s on old node" % dev.iv_name,
4153 79caa9ed Guido Trotter
                hint="Please cleanup this device manually as soon as possible")
4154 a9e0c397 Iustin Pop
4155 642445d9 Iustin Pop
    info("detaching primary drbds from the network (=> standalone)")
4156 642445d9 Iustin Pop
    done = 0
4157 642445d9 Iustin Pop
    for dev in instance.disks:
4158 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4159 f9518d38 Iustin Pop
      # set the network part of the physical (unique in bdev terms) id
4160 f9518d38 Iustin Pop
      # to None, meaning detach from network
4161 f9518d38 Iustin Pop
      dev.physical_id = (None, None, None, None) + dev.physical_id[4:]
4162 642445d9 Iustin Pop
      # and 'find' the device, which will 'fix' it to match the
4163 642445d9 Iustin Pop
      # standalone state
4164 72737a7f Iustin Pop
      if self.rpc.call_blockdev_find(pri_node, dev):
4165 642445d9 Iustin Pop
        done += 1
4166 642445d9 Iustin Pop
      else:
4167 642445d9 Iustin Pop
        warning("Failed to detach drbd %s from network, unusual case" %
4168 642445d9 Iustin Pop
                dev.iv_name)
4169 642445d9 Iustin Pop
4170 642445d9 Iustin Pop
    if not done:
4171 642445d9 Iustin Pop
      # no detaches succeeded (very unlikely)
4172 a1578d63 Iustin Pop
      self.cfg.ReleaseDRBDMinors(instance.name)
4173 642445d9 Iustin Pop
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
4174 642445d9 Iustin Pop
4175 642445d9 Iustin Pop
    # if we managed to detach at least one, we update all the disks of
4176 642445d9 Iustin Pop
    # the instance to point to the new secondary
4177 642445d9 Iustin Pop
    info("updating instance configuration")
4178 468b46f9 Iustin Pop
    for dev, _, new_logical_id in iv_names.itervalues():
4179 468b46f9 Iustin Pop
      dev.logical_id = new_logical_id
4180 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4181 642445d9 Iustin Pop
    cfg.Update(instance)
4182 a1578d63 Iustin Pop
    # we can remove now the temp minors as now the new values are
4183 a1578d63 Iustin Pop
    # written to the config file (and therefore stable)
4184 a1578d63 Iustin Pop
    self.cfg.ReleaseDRBDMinors(instance.name)
4185 a9e0c397 Iustin Pop
4186 642445d9 Iustin Pop
    # and now perform the drbd attach
4187 642445d9 Iustin Pop
    info("attaching primary drbds to new secondary (standalone => connected)")
4188 642445d9 Iustin Pop
    failures = []
4189 642445d9 Iustin Pop
    for dev in instance.disks:
4190 642445d9 Iustin Pop
      info("attaching primary drbd for %s to new secondary node" % dev.iv_name)
4191 642445d9 Iustin Pop
      # since the attach is smart, it's enough to 'find' the device,
4192 642445d9 Iustin Pop
      # it will automatically activate the network, if the physical_id
4193 642445d9 Iustin Pop
      # is correct
4194 642445d9 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4195 ffa1c0dc Iustin Pop
      logging.debug("Disk to attach: %s", dev)
4196 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_find(pri_node, dev):
4197 642445d9 Iustin Pop
        warning("can't attach drbd %s to new secondary!" % dev.iv_name,
4198 642445d9 Iustin Pop
                "please do a gnt-instance info to see the status of disks")
4199 a9e0c397 Iustin Pop
4200 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
4201 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
4202 a9e0c397 Iustin Pop
    # return value
4203 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
4204 b9bddb6b Iustin Pop
    _WaitForSync(self, instance, unlock=True)
4205 a9e0c397 Iustin Pop
4206 a9e0c397 Iustin Pop
    # so check manually all the devices
4207 ffa1c0dc Iustin Pop
    for name, (dev, old_lvs, _) in iv_names.iteritems():
4208 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4209 72737a7f Iustin Pop
      is_degr = self.rpc.call_blockdev_find(pri_node, dev)[5]
4210 a9e0c397 Iustin Pop
      if is_degr:
4211 a9e0c397 Iustin Pop
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4212 a9e0c397 Iustin Pop
4213 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
4214 ffa1c0dc Iustin Pop
    for name, (dev, old_lvs, _) in iv_names.iteritems():
4215 0834c866 Iustin Pop
      info("remove logical volumes for %s" % name)
4216 a9e0c397 Iustin Pop
      for lv in old_lvs:
4217 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, old_node)
4218 72737a7f Iustin Pop
        if not self.rpc.call_blockdev_remove(old_node, lv):
4219 0834c866 Iustin Pop
          warning("Can't remove LV on old secondary",
4220 79caa9ed Guido Trotter
                  hint="Cleanup stale volumes by hand")
4221 a9e0c397 Iustin Pop
4222 a9e0c397 Iustin Pop
  def Exec(self, feedback_fn):
4223 a9e0c397 Iustin Pop
    """Execute disk replacement.
4224 a9e0c397 Iustin Pop

4225 a9e0c397 Iustin Pop
    This dispatches the disk replacement to the appropriate handler.
4226 a9e0c397 Iustin Pop

4227 a9e0c397 Iustin Pop
    """
4228 a9e0c397 Iustin Pop
    instance = self.instance
4229 22985314 Guido Trotter
4230 22985314 Guido Trotter
    # Activate the instance disks if we're replacing them on a down instance
4231 22985314 Guido Trotter
    if instance.status == "down":
4232 b9bddb6b Iustin Pop
      _StartInstanceDisks(self, instance, True)
4233 22985314 Guido Trotter
4234 abdf0113 Iustin Pop
    if instance.disk_template == constants.DT_DRBD8:
4235 a9e0c397 Iustin Pop
      if self.op.remote_node is None:
4236 a9e0c397 Iustin Pop
        fn = self._ExecD8DiskOnly
4237 a9e0c397 Iustin Pop
      else:
4238 a9e0c397 Iustin Pop
        fn = self._ExecD8Secondary
4239 a9e0c397 Iustin Pop
    else:
4240 a9e0c397 Iustin Pop
      raise errors.ProgrammerError("Unhandled disk replacement case")
4241 22985314 Guido Trotter
4242 22985314 Guido Trotter
    ret = fn(feedback_fn)
4243 22985314 Guido Trotter
4244 22985314 Guido Trotter
    # Deactivate the instance disks if we're replacing them on a down instance
4245 22985314 Guido Trotter
    if instance.status == "down":
4246 b9bddb6b Iustin Pop
      _SafeShutdownInstanceDisks(self, instance)
4247 22985314 Guido Trotter
4248 22985314 Guido Trotter
    return ret
4249 a9e0c397 Iustin Pop
4250 a8083063 Iustin Pop
4251 8729e0d7 Iustin Pop
class LUGrowDisk(LogicalUnit):
4252 8729e0d7 Iustin Pop
  """Grow a disk of an instance.
4253 8729e0d7 Iustin Pop

4254 8729e0d7 Iustin Pop
  """
4255 8729e0d7 Iustin Pop
  HPATH = "disk-grow"
4256 8729e0d7 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4257 6605411d Iustin Pop
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
4258 31e63dbf Guido Trotter
  REQ_BGL = False
4259 31e63dbf Guido Trotter
4260 31e63dbf Guido Trotter
  def ExpandNames(self):
4261 31e63dbf Guido Trotter
    self._ExpandAndLockInstance()
4262 31e63dbf Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
4263 f6d9a522 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4264 31e63dbf Guido Trotter
4265 31e63dbf Guido Trotter
  def DeclareLocks(self, level):
4266 31e63dbf Guido Trotter
    if level == locking.LEVEL_NODE:
4267 31e63dbf Guido Trotter
      self._LockInstancesNodes()
4268 8729e0d7 Iustin Pop
4269 8729e0d7 Iustin Pop
  def BuildHooksEnv(self):
4270 8729e0d7 Iustin Pop
    """Build hooks env.
4271 8729e0d7 Iustin Pop

4272 8729e0d7 Iustin Pop
    This runs on the master, the primary and all the secondaries.
4273 8729e0d7 Iustin Pop

4274 8729e0d7 Iustin Pop
    """
4275 8729e0d7 Iustin Pop
    env = {
4276 8729e0d7 Iustin Pop
      "DISK": self.op.disk,
4277 8729e0d7 Iustin Pop
      "AMOUNT": self.op.amount,
4278 8729e0d7 Iustin Pop
      }
4279 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4280 8729e0d7 Iustin Pop
    nl = [
4281 d6a02168 Michael Hanselmann
      self.cfg.GetMasterNode(),
4282 8729e0d7 Iustin Pop
      self.instance.primary_node,
4283 8729e0d7 Iustin Pop
      ]
4284 8729e0d7 Iustin Pop
    return env, nl, nl
4285 8729e0d7 Iustin Pop
4286 8729e0d7 Iustin Pop
  def CheckPrereq(self):
4287 8729e0d7 Iustin Pop
    """Check prerequisites.
4288 8729e0d7 Iustin Pop

4289 8729e0d7 Iustin Pop
    This checks that the instance is in the cluster.
4290 8729e0d7 Iustin Pop

4291 8729e0d7 Iustin Pop
    """
4292 31e63dbf Guido Trotter
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4293 31e63dbf Guido Trotter
    assert instance is not None, \
4294 31e63dbf Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4295 31e63dbf Guido Trotter
4296 8729e0d7 Iustin Pop
    self.instance = instance
4297 8729e0d7 Iustin Pop
4298 8729e0d7 Iustin Pop
    if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8):
4299 8729e0d7 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout does not support"
4300 8729e0d7 Iustin Pop
                                 " growing.")
4301 8729e0d7 Iustin Pop
4302 8729e0d7 Iustin Pop
    if instance.FindDisk(self.op.disk) is None:
4303 8729e0d7 Iustin Pop
      raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
4304 c7cdfc90 Iustin Pop
                                 (self.op.disk, instance.name))
4305 8729e0d7 Iustin Pop
4306 8729e0d7 Iustin Pop
    nodenames = [instance.primary_node] + list(instance.secondary_nodes)
4307 72737a7f Iustin Pop
    nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
4308 72737a7f Iustin Pop
                                       instance.hypervisor)
4309 8729e0d7 Iustin Pop
    for node in nodenames:
4310 8729e0d7 Iustin Pop
      info = nodeinfo.get(node, None)
4311 8729e0d7 Iustin Pop
      if not info:
4312 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Cannot get current information"
4313 8729e0d7 Iustin Pop
                                   " from node '%s'" % node)
4314 8729e0d7 Iustin Pop
      vg_free = info.get('vg_free', None)
4315 8729e0d7 Iustin Pop
      if not isinstance(vg_free, int):
4316 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Can't compute free disk space on"
4317 8729e0d7 Iustin Pop
                                   " node %s" % node)
4318 8729e0d7 Iustin Pop
      if self.op.amount > info['vg_free']:
4319 8729e0d7 Iustin Pop
        raise errors.OpPrereqError("Not enough disk space on target node %s:"
4320 8729e0d7 Iustin Pop
                                   " %d MiB available, %d MiB required" %
4321 8729e0d7 Iustin Pop
                                   (node, info['vg_free'], self.op.amount))
4322 8729e0d7 Iustin Pop
4323 8729e0d7 Iustin Pop
  def Exec(self, feedback_fn):
4324 8729e0d7 Iustin Pop
    """Execute disk grow.
4325 8729e0d7 Iustin Pop

4326 8729e0d7 Iustin Pop
    """
4327 8729e0d7 Iustin Pop
    instance = self.instance
4328 8729e0d7 Iustin Pop
    disk = instance.FindDisk(self.op.disk)
4329 8729e0d7 Iustin Pop
    for node in (instance.secondary_nodes + (instance.primary_node,)):
4330 8729e0d7 Iustin Pop
      self.cfg.SetDiskID(disk, node)
4331 72737a7f Iustin Pop
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
4332 72737a7f Iustin Pop
      if (not result or not isinstance(result, (list, tuple)) or
4333 72737a7f Iustin Pop
          len(result) != 2):
4334 8729e0d7 Iustin Pop
        raise errors.OpExecError("grow request failed to node %s" % node)
4335 8729e0d7 Iustin Pop
      elif not result[0]:
4336 8729e0d7 Iustin Pop
        raise errors.OpExecError("grow request failed to node %s: %s" %
4337 8729e0d7 Iustin Pop
                                 (node, result[1]))
4338 8729e0d7 Iustin Pop
    disk.RecordGrow(self.op.amount)
4339 8729e0d7 Iustin Pop
    self.cfg.Update(instance)
4340 6605411d Iustin Pop
    if self.op.wait_for_sync:
4341 6605411d Iustin Pop
      disk_abort = not _WaitForSync(self.cfg, instance, self.proc)
4342 6605411d Iustin Pop
      if disk_abort:
4343 6605411d Iustin Pop
        logger.Error("Warning: disk sync-ing has not returned a good status.\n"
4344 6605411d Iustin Pop
                     " Please check the instance.")
4345 8729e0d7 Iustin Pop
4346 8729e0d7 Iustin Pop
4347 a8083063 Iustin Pop
class LUQueryInstanceData(NoHooksLU):
4348 a8083063 Iustin Pop
  """Query runtime instance data.
4349 a8083063 Iustin Pop

4350 a8083063 Iustin Pop
  """
4351 57821cac Iustin Pop
  _OP_REQP = ["instances", "static"]
4352 a987fa48 Guido Trotter
  REQ_BGL = False
4353 ae5849b5 Michael Hanselmann
4354 a987fa48 Guido Trotter
  def ExpandNames(self):
4355 a987fa48 Guido Trotter
    self.needed_locks = {}
4356 a987fa48 Guido Trotter
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
4357 a987fa48 Guido Trotter
4358 a987fa48 Guido Trotter
    if not isinstance(self.op.instances, list):
4359 a987fa48 Guido Trotter
      raise errors.OpPrereqError("Invalid argument type 'instances'")
4360 a987fa48 Guido Trotter
4361 a987fa48 Guido Trotter
    if self.op.instances:
4362 a987fa48 Guido Trotter
      self.wanted_names = []
4363 a987fa48 Guido Trotter
      for name in self.op.instances:
4364 a987fa48 Guido Trotter
        full_name = self.cfg.ExpandInstanceName(name)
4365 a987fa48 Guido Trotter
        if full_name is None:
4366 a987fa48 Guido Trotter
          raise errors.OpPrereqError("Instance '%s' not known" %
4367 a987fa48 Guido Trotter
                                     self.op.instance_name)
4368 a987fa48 Guido Trotter
        self.wanted_names.append(full_name)
4369 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
4370 a987fa48 Guido Trotter
    else:
4371 a987fa48 Guido Trotter
      self.wanted_names = None
4372 a987fa48 Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4373 a987fa48 Guido Trotter
4374 a987fa48 Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = []
4375 a987fa48 Guido Trotter
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4376 a987fa48 Guido Trotter
4377 a987fa48 Guido Trotter
  def DeclareLocks(self, level):
4378 a987fa48 Guido Trotter
    if level == locking.LEVEL_NODE:
4379 a987fa48 Guido Trotter
      self._LockInstancesNodes()
4380 a8083063 Iustin Pop
4381 a8083063 Iustin Pop
  def CheckPrereq(self):
4382 a8083063 Iustin Pop
    """Check prerequisites.
4383 a8083063 Iustin Pop

4384 a8083063 Iustin Pop
    This only checks the optional instance list against the existing names.
4385 a8083063 Iustin Pop

4386 a8083063 Iustin Pop
    """
4387 a987fa48 Guido Trotter
    if self.wanted_names is None:
4388 a987fa48 Guido Trotter
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4389 a8083063 Iustin Pop
4390 a987fa48 Guido Trotter
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4391 a987fa48 Guido Trotter
                             in self.wanted_names]
4392 a987fa48 Guido Trotter
    return
4393 a8083063 Iustin Pop
4394 a8083063 Iustin Pop
  def _ComputeDiskStatus(self, instance, snode, dev):
4395 a8083063 Iustin Pop
    """Compute block device status.
4396 a8083063 Iustin Pop

4397 a8083063 Iustin Pop
    """
4398 57821cac Iustin Pop
    static = self.op.static
4399 57821cac Iustin Pop
    if not static:
4400 57821cac Iustin Pop
      self.cfg.SetDiskID(dev, instance.primary_node)
4401 57821cac Iustin Pop
      dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
4402 57821cac Iustin Pop
    else:
4403 57821cac Iustin Pop
      dev_pstatus = None
4404 57821cac Iustin Pop
4405 a1f445d3 Iustin Pop
    if dev.dev_type in constants.LDS_DRBD:
4406 a8083063 Iustin Pop
      # we change the snode then (otherwise we use the one passed in)
4407 a8083063 Iustin Pop
      if dev.logical_id[0] == instance.primary_node:
4408 a8083063 Iustin Pop
        snode = dev.logical_id[1]
4409 a8083063 Iustin Pop
      else:
4410 a8083063 Iustin Pop
        snode = dev.logical_id[0]
4411 a8083063 Iustin Pop
4412 57821cac Iustin Pop
    if snode and not static:
4413 a8083063 Iustin Pop
      self.cfg.SetDiskID(dev, snode)
4414 72737a7f Iustin Pop
      dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
4415 a8083063 Iustin Pop
    else:
4416 a8083063 Iustin Pop
      dev_sstatus = None
4417 a8083063 Iustin Pop
4418 a8083063 Iustin Pop
    if dev.children:
4419 a8083063 Iustin Pop
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4420 a8083063 Iustin Pop
                      for child in dev.children]
4421 a8083063 Iustin Pop
    else:
4422 a8083063 Iustin Pop
      dev_children = []
4423 a8083063 Iustin Pop
4424 a8083063 Iustin Pop
    data = {
4425 a8083063 Iustin Pop
      "iv_name": dev.iv_name,
4426 a8083063 Iustin Pop
      "dev_type": dev.dev_type,
4427 a8083063 Iustin Pop
      "logical_id": dev.logical_id,
4428 a8083063 Iustin Pop
      "physical_id": dev.physical_id,
4429 a8083063 Iustin Pop
      "pstatus": dev_pstatus,
4430 a8083063 Iustin Pop
      "sstatus": dev_sstatus,
4431 a8083063 Iustin Pop
      "children": dev_children,
4432 a8083063 Iustin Pop
      }
4433 a8083063 Iustin Pop
4434 a8083063 Iustin Pop
    return data
4435 a8083063 Iustin Pop
4436 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4437 a8083063 Iustin Pop
    """Gather and return data"""
4438 a8083063 Iustin Pop
    result = {}
4439 338e51e8 Iustin Pop
4440 338e51e8 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
4441 338e51e8 Iustin Pop
4442 a8083063 Iustin Pop
    for instance in self.wanted_instances:
4443 57821cac Iustin Pop
      if not self.op.static:
4444 57821cac Iustin Pop
        remote_info = self.rpc.call_instance_info(instance.primary_node,
4445 57821cac Iustin Pop
                                                  instance.name,
4446 57821cac Iustin Pop
                                                  instance.hypervisor)
4447 57821cac Iustin Pop
        if remote_info and "state" in remote_info:
4448 57821cac Iustin Pop
          remote_state = "up"
4449 57821cac Iustin Pop
        else:
4450 57821cac Iustin Pop
          remote_state = "down"
4451 a8083063 Iustin Pop
      else:
4452 57821cac Iustin Pop
        remote_state = None
4453 a8083063 Iustin Pop
      if instance.status == "down":
4454 a8083063 Iustin Pop
        config_state = "down"
4455 a8083063 Iustin Pop
      else:
4456 a8083063 Iustin Pop
        config_state = "up"
4457 a8083063 Iustin Pop
4458 a8083063 Iustin Pop
      disks = [self._ComputeDiskStatus(instance, None, device)
4459 a8083063 Iustin Pop
               for device in instance.disks]
4460 a8083063 Iustin Pop
4461 a8083063 Iustin Pop
      idict = {
4462 a8083063 Iustin Pop
        "name": instance.name,
4463 a8083063 Iustin Pop
        "config_state": config_state,
4464 a8083063 Iustin Pop
        "run_state": remote_state,
4465 a8083063 Iustin Pop
        "pnode": instance.primary_node,
4466 a8083063 Iustin Pop
        "snodes": instance.secondary_nodes,
4467 a8083063 Iustin Pop
        "os": instance.os,
4468 a8083063 Iustin Pop
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
4469 a8083063 Iustin Pop
        "disks": disks,
4470 e69d05fd Iustin Pop
        "hypervisor": instance.hypervisor,
4471 24838135 Iustin Pop
        "network_port": instance.network_port,
4472 24838135 Iustin Pop
        "hv_instance": instance.hvparams,
4473 338e51e8 Iustin Pop
        "hv_actual": cluster.FillHV(instance),
4474 338e51e8 Iustin Pop
        "be_instance": instance.beparams,
4475 338e51e8 Iustin Pop
        "be_actual": cluster.FillBE(instance),
4476 a8083063 Iustin Pop
        }
4477 a8083063 Iustin Pop
4478 a8083063 Iustin Pop
      result[instance.name] = idict
4479 a8083063 Iustin Pop
4480 a8083063 Iustin Pop
    return result
4481 a8083063 Iustin Pop
4482 a8083063 Iustin Pop
4483 7767bbf5 Manuel Franceschini
class LUSetInstanceParams(LogicalUnit):
4484 a8083063 Iustin Pop
  """Modifies an instances's parameters.
4485 a8083063 Iustin Pop

4486 a8083063 Iustin Pop
  """
4487 a8083063 Iustin Pop
  HPATH = "instance-modify"
4488 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4489 74409b12 Iustin Pop
  _OP_REQP = ["instance_name", "hvparams"]
4490 1a5c7281 Guido Trotter
  REQ_BGL = False
4491 1a5c7281 Guido Trotter
4492 1a5c7281 Guido Trotter
  def ExpandNames(self):
4493 1a5c7281 Guido Trotter
    self._ExpandAndLockInstance()
4494 74409b12 Iustin Pop
    self.needed_locks[locking.LEVEL_NODE] = []
4495 74409b12 Iustin Pop
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4496 74409b12 Iustin Pop
4497 74409b12 Iustin Pop
4498 74409b12 Iustin Pop
  def DeclareLocks(self, level):
4499 74409b12 Iustin Pop
    if level == locking.LEVEL_NODE:
4500 74409b12 Iustin Pop
      self._LockInstancesNodes()
4501 a8083063 Iustin Pop
4502 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4503 a8083063 Iustin Pop
    """Build hooks env.
4504 a8083063 Iustin Pop

4505 a8083063 Iustin Pop
    This runs on the master, primary and secondaries.
4506 a8083063 Iustin Pop

4507 a8083063 Iustin Pop
    """
4508 396e1b78 Michael Hanselmann
    args = dict()
4509 338e51e8 Iustin Pop
    if constants.BE_MEMORY in self.be_new:
4510 338e51e8 Iustin Pop
      args['memory'] = self.be_new[constants.BE_MEMORY]
4511 338e51e8 Iustin Pop
    if constants.BE_VCPUS in self.be_new:
4512 338e51e8 Iustin Pop
      args['vcpus'] = self.be_bnew[constants.BE_VCPUS]
4513 ef756965 Iustin Pop
    if self.do_ip or self.do_bridge or self.mac:
4514 396e1b78 Michael Hanselmann
      if self.do_ip:
4515 396e1b78 Michael Hanselmann
        ip = self.ip
4516 396e1b78 Michael Hanselmann
      else:
4517 396e1b78 Michael Hanselmann
        ip = self.instance.nics[0].ip
4518 396e1b78 Michael Hanselmann
      if self.bridge:
4519 396e1b78 Michael Hanselmann
        bridge = self.bridge
4520 396e1b78 Michael Hanselmann
      else:
4521 396e1b78 Michael Hanselmann
        bridge = self.instance.nics[0].bridge
4522 ef756965 Iustin Pop
      if self.mac:
4523 ef756965 Iustin Pop
        mac = self.mac
4524 ef756965 Iustin Pop
      else:
4525 ef756965 Iustin Pop
        mac = self.instance.nics[0].mac
4526 ef756965 Iustin Pop
      args['nics'] = [(ip, bridge, mac)]
4527 338e51e8 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
4528 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode(),
4529 a8083063 Iustin Pop
          self.instance.primary_node] + list(self.instance.secondary_nodes)
4530 a8083063 Iustin Pop
    return env, nl, nl
4531 a8083063 Iustin Pop
4532 a8083063 Iustin Pop
  def CheckPrereq(self):
4533 a8083063 Iustin Pop
    """Check prerequisites.
4534 a8083063 Iustin Pop

4535 a8083063 Iustin Pop
    This only checks the instance list against the existing names.
4536 a8083063 Iustin Pop

4537 a8083063 Iustin Pop
    """
4538 1a5c7281 Guido Trotter
    # FIXME: all the parameters could be checked before, in ExpandNames, or in
4539 1a5c7281 Guido Trotter
    # a separate CheckArguments function, if we implement one, so the operation
4540 1a5c7281 Guido Trotter
    # can be aborted without waiting for any lock, should it have an error...
4541 a8083063 Iustin Pop
    self.ip = getattr(self.op, "ip", None)
4542 1862d460 Alexander Schreiber
    self.mac = getattr(self.op, "mac", None)
4543 a8083063 Iustin Pop
    self.bridge = getattr(self.op, "bridge", None)
4544 973d7867 Iustin Pop
    self.kernel_path = getattr(self.op, "kernel_path", None)
4545 973d7867 Iustin Pop
    self.initrd_path = getattr(self.op, "initrd_path", None)
4546 4300c4b6 Guido Trotter
    self.force = getattr(self.op, "force", None)
4547 338e51e8 Iustin Pop
    all_parms = [self.ip, self.bridge, self.mac]
4548 338e51e8 Iustin Pop
    if (all_parms.count(None) == len(all_parms) and
4549 338e51e8 Iustin Pop
        not self.op.hvparams and
4550 338e51e8 Iustin Pop
        not self.op.beparams):
4551 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("No changes submitted")
4552 338e51e8 Iustin Pop
    for item in (constants.BE_MEMORY, constants.BE_VCPUS):
4553 338e51e8 Iustin Pop
      val = self.op.beparams.get(item, None)
4554 338e51e8 Iustin Pop
      if val is not None:
4555 338e51e8 Iustin Pop
        try:
4556 338e51e8 Iustin Pop
          val = int(val)
4557 338e51e8 Iustin Pop
        except ValueError, err:
4558 338e51e8 Iustin Pop
          raise errors.OpPrereqError("Invalid %s size: %s" % (item, str(err)))
4559 338e51e8 Iustin Pop
        self.op.beparams[item] = val
4560 a8083063 Iustin Pop
    if self.ip is not None:
4561 a8083063 Iustin Pop
      self.do_ip = True
4562 a8083063 Iustin Pop
      if self.ip.lower() == "none":
4563 a8083063 Iustin Pop
        self.ip = None
4564 a8083063 Iustin Pop
      else:
4565 a8083063 Iustin Pop
        if not utils.IsValidIP(self.ip):
4566 3ecf6786 Iustin Pop
          raise errors.OpPrereqError("Invalid IP address '%s'." % self.ip)
4567 a8083063 Iustin Pop
    else:
4568 a8083063 Iustin Pop
      self.do_ip = False
4569 ecb215b5 Michael Hanselmann
    self.do_bridge = (self.bridge is not None)
4570 1862d460 Alexander Schreiber
    if self.mac is not None:
4571 1862d460 Alexander Schreiber
      if self.cfg.IsMacInUse(self.mac):
4572 1862d460 Alexander Schreiber
        raise errors.OpPrereqError('MAC address %s already in use in cluster' %
4573 1862d460 Alexander Schreiber
                                   self.mac)
4574 1862d460 Alexander Schreiber
      if not utils.IsValidMac(self.mac):
4575 1862d460 Alexander Schreiber
        raise errors.OpPrereqError('Invalid MAC address %s' % self.mac)
4576 a8083063 Iustin Pop
4577 74409b12 Iustin Pop
    # checking the new params on the primary/secondary nodes
4578 31a853d2 Iustin Pop
4579 cfefe007 Guido Trotter
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4580 1a5c7281 Guido Trotter
    assert self.instance is not None, \
4581 1a5c7281 Guido Trotter
      "Cannot retrieve locked instance %s" % self.op.instance_name
4582 74409b12 Iustin Pop
    pnode = self.instance.primary_node
4583 74409b12 Iustin Pop
    nodelist = [pnode]
4584 74409b12 Iustin Pop
    nodelist.extend(instance.secondary_nodes)
4585 74409b12 Iustin Pop
4586 338e51e8 Iustin Pop
    # hvparams processing
4587 74409b12 Iustin Pop
    if self.op.hvparams:
4588 74409b12 Iustin Pop
      i_hvdict = copy.deepcopy(instance.hvparams)
4589 74409b12 Iustin Pop
      for key, val in self.op.hvparams.iteritems():
4590 74409b12 Iustin Pop
        if val is None:
4591 74409b12 Iustin Pop
          try:
4592 74409b12 Iustin Pop
            del i_hvdict[key]
4593 74409b12 Iustin Pop
          except KeyError:
4594 74409b12 Iustin Pop
            pass
4595 74409b12 Iustin Pop
        else:
4596 74409b12 Iustin Pop
          i_hvdict[key] = val
4597 74409b12 Iustin Pop
      cluster = self.cfg.GetClusterInfo()
4598 74409b12 Iustin Pop
      hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor],
4599 74409b12 Iustin Pop
                                i_hvdict)
4600 74409b12 Iustin Pop
      # local check
4601 74409b12 Iustin Pop
      hypervisor.GetHypervisor(
4602 74409b12 Iustin Pop
        instance.hypervisor).CheckParameterSyntax(hv_new)
4603 74409b12 Iustin Pop
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
4604 338e51e8 Iustin Pop
      self.hv_new = hv_new # the new actual values
4605 338e51e8 Iustin Pop
      self.hv_inst = i_hvdict # the new dict (without defaults)
4606 338e51e8 Iustin Pop
    else:
4607 338e51e8 Iustin Pop
      self.hv_new = self.hv_inst = {}
4608 338e51e8 Iustin Pop
4609 338e51e8 Iustin Pop
    # beparams processing
4610 338e51e8 Iustin Pop
    if self.op.beparams:
4611 338e51e8 Iustin Pop
      i_bedict = copy.deepcopy(instance.beparams)
4612 338e51e8 Iustin Pop
      for key, val in self.op.beparams.iteritems():
4613 338e51e8 Iustin Pop
        if val is None:
4614 338e51e8 Iustin Pop
          try:
4615 338e51e8 Iustin Pop
            del i_bedict[key]
4616 338e51e8 Iustin Pop
          except KeyError:
4617 338e51e8 Iustin Pop
            pass
4618 338e51e8 Iustin Pop
        else:
4619 338e51e8 Iustin Pop
          i_bedict[key] = val
4620 338e51e8 Iustin Pop
      cluster = self.cfg.GetClusterInfo()
4621 338e51e8 Iustin Pop
      be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
4622 338e51e8 Iustin Pop
                                i_bedict)
4623 338e51e8 Iustin Pop
      self.be_new = be_new # the new actual values
4624 338e51e8 Iustin Pop
      self.be_inst = i_bedict # the new dict (without defaults)
4625 338e51e8 Iustin Pop
    else:
4626 338e51e8 Iustin Pop
      self.hv_new = self.hv_inst = {}
4627 74409b12 Iustin Pop
4628 cfefe007 Guido Trotter
    self.warn = []
4629 647a5d80 Iustin Pop
4630 338e51e8 Iustin Pop
    if constants.BE_MEMORY in self.op.beparams and not self.force:
4631 647a5d80 Iustin Pop
      mem_check_list = [pnode]
4632 c0f2b229 Iustin Pop
      if be_new[constants.BE_AUTO_BALANCE]:
4633 c0f2b229 Iustin Pop
        # either we changed auto_balance to yes or it was from before
4634 647a5d80 Iustin Pop
        mem_check_list.extend(instance.secondary_nodes)
4635 72737a7f Iustin Pop
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
4636 72737a7f Iustin Pop
                                                  instance.hypervisor)
4637 647a5d80 Iustin Pop
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
4638 72737a7f Iustin Pop
                                         instance.hypervisor)
4639 cfefe007 Guido Trotter
4640 cfefe007 Guido Trotter
      if pnode not in nodeinfo or not isinstance(nodeinfo[pnode], dict):
4641 cfefe007 Guido Trotter
        # Assume the primary node is unreachable and go ahead
4642 cfefe007 Guido Trotter
        self.warn.append("Can't get info from primary node %s" % pnode)
4643 cfefe007 Guido Trotter
      else:
4644 cfefe007 Guido Trotter
        if instance_info:
4645 cfefe007 Guido Trotter
          current_mem = instance_info['memory']
4646 cfefe007 Guido Trotter
        else:
4647 cfefe007 Guido Trotter
          # Assume instance not running
4648 cfefe007 Guido Trotter
          # (there is a slight race condition here, but it's not very probable,
4649 cfefe007 Guido Trotter
          # and we have no other way to check)
4650 cfefe007 Guido Trotter
          current_mem = 0
4651 338e51e8 Iustin Pop
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
4652 338e51e8 Iustin Pop
                    nodeinfo[pnode]['memory_free'])
4653 cfefe007 Guido Trotter
        if miss_mem > 0:
4654 cfefe007 Guido Trotter
          raise errors.OpPrereqError("This change will prevent the instance"
4655 cfefe007 Guido Trotter
                                     " from starting, due to %d MB of memory"
4656 cfefe007 Guido Trotter
                                     " missing on its primary node" % miss_mem)
4657 cfefe007 Guido Trotter
4658 c0f2b229 Iustin Pop
      if be_new[constants.BE_AUTO_BALANCE]:
4659 647a5d80 Iustin Pop
        for node in instance.secondary_nodes:
4660 647a5d80 Iustin Pop
          if node not in nodeinfo or not isinstance(nodeinfo[node], dict):
4661 647a5d80 Iustin Pop
            self.warn.append("Can't get info from secondary node %s" % node)
4662 647a5d80 Iustin Pop
          elif be_new[constants.BE_MEMORY] > nodeinfo[node]['memory_free']:
4663 647a5d80 Iustin Pop
            self.warn.append("Not enough memory to failover instance to"
4664 647a5d80 Iustin Pop
                             " secondary node %s" % node)
4665 5bc84f33 Alexander Schreiber
4666 a8083063 Iustin Pop
    return
4667 a8083063 Iustin Pop
4668 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4669 a8083063 Iustin Pop
    """Modifies an instance.
4670 a8083063 Iustin Pop

4671 a8083063 Iustin Pop
    All parameters take effect only at the next restart of the instance.
4672 a8083063 Iustin Pop
    """
4673 cfefe007 Guido Trotter
    # Process here the warnings from CheckPrereq, as we don't have a
4674 cfefe007 Guido Trotter
    # feedback_fn there.
4675 cfefe007 Guido Trotter
    for warn in self.warn:
4676 cfefe007 Guido Trotter
      feedback_fn("WARNING: %s" % warn)
4677 cfefe007 Guido Trotter
4678 a8083063 Iustin Pop
    result = []
4679 a8083063 Iustin Pop
    instance = self.instance
4680 a8083063 Iustin Pop
    if self.do_ip:
4681 a8083063 Iustin Pop
      instance.nics[0].ip = self.ip
4682 a8083063 Iustin Pop
      result.append(("ip", self.ip))
4683 a8083063 Iustin Pop
    if self.bridge:
4684 a8083063 Iustin Pop
      instance.nics[0].bridge = self.bridge
4685 a8083063 Iustin Pop
      result.append(("bridge", self.bridge))
4686 1862d460 Alexander Schreiber
    if self.mac:
4687 1862d460 Alexander Schreiber
      instance.nics[0].mac = self.mac
4688 1862d460 Alexander Schreiber
      result.append(("mac", self.mac))
4689 74409b12 Iustin Pop
    if self.op.hvparams:
4690 74409b12 Iustin Pop
      instance.hvparams = self.hv_new
4691 74409b12 Iustin Pop
      for key, val in self.op.hvparams.iteritems():
4692 74409b12 Iustin Pop
        result.append(("hv/%s" % key, val))
4693 338e51e8 Iustin Pop
    if self.op.beparams:
4694 338e51e8 Iustin Pop
      instance.beparams = self.be_inst
4695 338e51e8 Iustin Pop
      for key, val in self.op.beparams.iteritems():
4696 338e51e8 Iustin Pop
        result.append(("be/%s" % key, val))
4697 a8083063 Iustin Pop
4698 ea94e1cd Guido Trotter
    self.cfg.Update(instance)
4699 a8083063 Iustin Pop
4700 a8083063 Iustin Pop
    return result
4701 a8083063 Iustin Pop
4702 a8083063 Iustin Pop
4703 a8083063 Iustin Pop
class LUQueryExports(NoHooksLU):
4704 a8083063 Iustin Pop
  """Query the exports list
4705 a8083063 Iustin Pop

4706 a8083063 Iustin Pop
  """
4707 895ecd9c Guido Trotter
  _OP_REQP = ['nodes']
4708 21a15682 Guido Trotter
  REQ_BGL = False
4709 21a15682 Guido Trotter
4710 21a15682 Guido Trotter
  def ExpandNames(self):
4711 21a15682 Guido Trotter
    self.needed_locks = {}
4712 21a15682 Guido Trotter
    self.share_locks[locking.LEVEL_NODE] = 1
4713 21a15682 Guido Trotter
    if not self.op.nodes:
4714 e310b019 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4715 21a15682 Guido Trotter
    else:
4716 21a15682 Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = \
4717 21a15682 Guido Trotter
        _GetWantedNodes(self, self.op.nodes)
4718 a8083063 Iustin Pop
4719 a8083063 Iustin Pop
  def CheckPrereq(self):
4720 21a15682 Guido Trotter
    """Check prerequisites.
4721 a8083063 Iustin Pop

4722 a8083063 Iustin Pop
    """
4723 21a15682 Guido Trotter
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
4724 a8083063 Iustin Pop
4725 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4726 a8083063 Iustin Pop
    """Compute the list of all the exported system images.
4727 a8083063 Iustin Pop

4728 a8083063 Iustin Pop
    Returns:
4729 a8083063 Iustin Pop
      a dictionary with the structure node->(export-list)
4730 a8083063 Iustin Pop
      where export-list is a list of the instances exported on
4731 a8083063 Iustin Pop
      that node.
4732 a8083063 Iustin Pop

4733 a8083063 Iustin Pop
    """
4734 72737a7f Iustin Pop
    return self.rpc.call_export_list(self.nodes)
4735 a8083063 Iustin Pop
4736 a8083063 Iustin Pop
4737 a8083063 Iustin Pop
class LUExportInstance(LogicalUnit):
4738 a8083063 Iustin Pop
  """Export an instance to an image in the cluster.
4739 a8083063 Iustin Pop

4740 a8083063 Iustin Pop
  """
4741 a8083063 Iustin Pop
  HPATH = "instance-export"
4742 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4743 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
4744 6657590e Guido Trotter
  REQ_BGL = False
4745 6657590e Guido Trotter
4746 6657590e Guido Trotter
  def ExpandNames(self):
4747 6657590e Guido Trotter
    self._ExpandAndLockInstance()
4748 6657590e Guido Trotter
    # FIXME: lock only instance primary and destination node
4749 6657590e Guido Trotter
    #
4750 6657590e Guido Trotter
    # Sad but true, for now we have do lock all nodes, as we don't know where
4751 6657590e Guido Trotter
    # the previous export might be, and and in this LU we search for it and
4752 6657590e Guido Trotter
    # remove it from its current node. In the future we could fix this by:
4753 6657590e Guido Trotter
    #  - making a tasklet to search (share-lock all), then create the new one,
4754 6657590e Guido Trotter
    #    then one to remove, after
4755 6657590e Guido Trotter
    #  - removing the removal operation altoghether
4756 6657590e Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4757 6657590e Guido Trotter
4758 6657590e Guido Trotter
  def DeclareLocks(self, level):
4759 6657590e Guido Trotter
    """Last minute lock declaration."""
4760 6657590e Guido Trotter
    # All nodes are locked anyway, so nothing to do here.
4761 a8083063 Iustin Pop
4762 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4763 a8083063 Iustin Pop
    """Build hooks env.
4764 a8083063 Iustin Pop

4765 a8083063 Iustin Pop
    This will run on the master, primary node and target node.
4766 a8083063 Iustin Pop

4767 a8083063 Iustin Pop
    """
4768 a8083063 Iustin Pop
    env = {
4769 a8083063 Iustin Pop
      "EXPORT_NODE": self.op.target_node,
4770 a8083063 Iustin Pop
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
4771 a8083063 Iustin Pop
      }
4772 338e51e8 Iustin Pop
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4773 d6a02168 Michael Hanselmann
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
4774 a8083063 Iustin Pop
          self.op.target_node]
4775 a8083063 Iustin Pop
    return env, nl, nl
4776 a8083063 Iustin Pop
4777 a8083063 Iustin Pop
  def CheckPrereq(self):
4778 a8083063 Iustin Pop
    """Check prerequisites.
4779 a8083063 Iustin Pop

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

4782 a8083063 Iustin Pop
    """
4783 6657590e Guido Trotter
    instance_name = self.op.instance_name
4784 a8083063 Iustin Pop
    self.instance = self.cfg.GetInstanceInfo(instance_name)
4785 6657590e Guido Trotter
    assert self.instance is not None, \
4786 6657590e Guido Trotter
          "Cannot retrieve locked instance %s" % self.op.instance_name
4787 a8083063 Iustin Pop
4788 6657590e Guido Trotter
    self.dst_node = self.cfg.GetNodeInfo(
4789 6657590e Guido Trotter
      self.cfg.ExpandNodeName(self.op.target_node))
4790 a8083063 Iustin Pop
4791 6657590e Guido Trotter
    assert self.dst_node is not None, \
4792 6657590e Guido Trotter
          "Cannot retrieve locked node %s" % self.op.target_node
4793 a8083063 Iustin Pop
4794 b6023d6c Manuel Franceschini
    # instance disk type verification
4795 b6023d6c Manuel Franceschini
    for disk in self.instance.disks:
4796 b6023d6c Manuel Franceschini
      if disk.dev_type == constants.LD_FILE:
4797 b6023d6c Manuel Franceschini
        raise errors.OpPrereqError("Export not supported for instances with"
4798 b6023d6c Manuel Franceschini
                                   " file-based disks")
4799 b6023d6c Manuel Franceschini
4800 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4801 a8083063 Iustin Pop
    """Export an instance to an image in the cluster.
4802 a8083063 Iustin Pop

4803 a8083063 Iustin Pop
    """
4804 a8083063 Iustin Pop
    instance = self.instance
4805 a8083063 Iustin Pop
    dst_node = self.dst_node
4806 a8083063 Iustin Pop
    src_node = instance.primary_node
4807 a8083063 Iustin Pop
    if self.op.shutdown:
4808 fb300fb7 Guido Trotter
      # shutdown the instance, but not the disks
4809 72737a7f Iustin Pop
      if not self.rpc.call_instance_shutdown(src_node, instance):
4810 38206f3c Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
4811 38206f3c Iustin Pop
                                 (instance.name, src_node))
4812 a8083063 Iustin Pop
4813 a8083063 Iustin Pop
    vgname = self.cfg.GetVGName()
4814 a8083063 Iustin Pop
4815 a8083063 Iustin Pop
    snap_disks = []
4816 a8083063 Iustin Pop
4817 a8083063 Iustin Pop
    try:
4818 a8083063 Iustin Pop
      for disk in instance.disks:
4819 a8083063 Iustin Pop
        if disk.iv_name == "sda":
4820 a8083063 Iustin Pop
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
4821 72737a7f Iustin Pop
          new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
4822 a8083063 Iustin Pop
4823 a8083063 Iustin Pop
          if not new_dev_name:
4824 a8083063 Iustin Pop
            logger.Error("could not snapshot block device %s on node %s" %
4825 a8083063 Iustin Pop
                         (disk.logical_id[1], src_node))
4826 a8083063 Iustin Pop
          else:
4827 fe96220b Iustin Pop
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
4828 a8083063 Iustin Pop
                                      logical_id=(vgname, new_dev_name),
4829 a8083063 Iustin Pop
                                      physical_id=(vgname, new_dev_name),
4830 a8083063 Iustin Pop
                                      iv_name=disk.iv_name)
4831 a8083063 Iustin Pop
            snap_disks.append(new_dev)
4832 a8083063 Iustin Pop
4833 a8083063 Iustin Pop
    finally:
4834 fb300fb7 Guido Trotter
      if self.op.shutdown and instance.status == "up":
4835 72737a7f Iustin Pop
        if not self.rpc.call_instance_start(src_node, instance, None):
4836 b9bddb6b Iustin Pop
          _ShutdownInstanceDisks(self, instance)
4837 fb300fb7 Guido Trotter
          raise errors.OpExecError("Could not start instance")
4838 a8083063 Iustin Pop
4839 a8083063 Iustin Pop
    # TODO: check for size
4840 a8083063 Iustin Pop
4841 62c9ec92 Iustin Pop
    cluster_name = self.cfg.GetClusterName()
4842 a8083063 Iustin Pop
    for dev in snap_disks:
4843 72737a7f Iustin Pop
      if not self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
4844 62c9ec92 Iustin Pop
                                      instance, cluster_name):
4845 16687b98 Manuel Franceschini
        logger.Error("could not export block device %s from node %s to node %s"
4846 16687b98 Manuel Franceschini
                     % (dev.logical_id[1], src_node, dst_node.name))
4847 72737a7f Iustin Pop
      if not self.rpc.call_blockdev_remove(src_node, dev):
4848 16687b98 Manuel Franceschini
        logger.Error("could not remove snapshot block device %s from node %s" %
4849 16687b98 Manuel Franceschini
                     (dev.logical_id[1], src_node))
4850 a8083063 Iustin Pop
4851 72737a7f Iustin Pop
    if not self.rpc.call_finalize_export(dst_node.name, instance, snap_disks):
4852 a8083063 Iustin Pop
      logger.Error("could not finalize export for instance %s on node %s" %
4853 a8083063 Iustin Pop
                   (instance.name, dst_node.name))
4854 a8083063 Iustin Pop
4855 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
4856 a8083063 Iustin Pop
    nodelist.remove(dst_node.name)
4857 a8083063 Iustin Pop
4858 a8083063 Iustin Pop
    # on one-node clusters nodelist will be empty after the removal
4859 a8083063 Iustin Pop
    # if we proceed the backup would be removed because OpQueryExports
4860 a8083063 Iustin Pop
    # substitutes an empty list with the full cluster node list.
4861 a8083063 Iustin Pop
    if nodelist:
4862 72737a7f Iustin Pop
      exportlist = self.rpc.call_export_list(nodelist)
4863 a8083063 Iustin Pop
      for node in exportlist:
4864 a8083063 Iustin Pop
        if instance.name in exportlist[node]:
4865 72737a7f Iustin Pop
          if not self.rpc.call_export_remove(node, instance.name):
4866 a8083063 Iustin Pop
            logger.Error("could not remove older export for instance %s"
4867 a8083063 Iustin Pop
                         " on node %s" % (instance.name, node))
4868 5c947f38 Iustin Pop
4869 5c947f38 Iustin Pop
4870 9ac99fda Guido Trotter
class LURemoveExport(NoHooksLU):
4871 9ac99fda Guido Trotter
  """Remove exports related to the named instance.
4872 9ac99fda Guido Trotter

4873 9ac99fda Guido Trotter
  """
4874 9ac99fda Guido Trotter
  _OP_REQP = ["instance_name"]
4875 3656b3af Guido Trotter
  REQ_BGL = False
4876 3656b3af Guido Trotter
4877 3656b3af Guido Trotter
  def ExpandNames(self):
4878 3656b3af Guido Trotter
    self.needed_locks = {}
4879 3656b3af Guido Trotter
    # We need all nodes to be locked in order for RemoveExport to work, but we
4880 3656b3af Guido Trotter
    # don't need to lock the instance itself, as nothing will happen to it (and
4881 3656b3af Guido Trotter
    # we can remove exports also for a removed instance)
4882 3656b3af Guido Trotter
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4883 9ac99fda Guido Trotter
4884 9ac99fda Guido Trotter
  def CheckPrereq(self):
4885 9ac99fda Guido Trotter
    """Check prerequisites.
4886 9ac99fda Guido Trotter
    """
4887 9ac99fda Guido Trotter
    pass
4888 9ac99fda Guido Trotter
4889 9ac99fda Guido Trotter
  def Exec(self, feedback_fn):
4890 9ac99fda Guido Trotter
    """Remove any export.
4891 9ac99fda Guido Trotter

4892 9ac99fda Guido Trotter
    """
4893 9ac99fda Guido Trotter
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4894 9ac99fda Guido Trotter
    # If the instance was not found we'll try with the name that was passed in.
4895 9ac99fda Guido Trotter
    # This will only work if it was an FQDN, though.
4896 9ac99fda Guido Trotter
    fqdn_warn = False
4897 9ac99fda Guido Trotter
    if not instance_name:
4898 9ac99fda Guido Trotter
      fqdn_warn = True
4899 9ac99fda Guido Trotter
      instance_name = self.op.instance_name
4900 9ac99fda Guido Trotter
4901 72737a7f Iustin Pop
    exportlist = self.rpc.call_export_list(self.acquired_locks[
4902 72737a7f Iustin Pop
      locking.LEVEL_NODE])
4903 9ac99fda Guido Trotter
    found = False
4904 9ac99fda Guido Trotter
    for node in exportlist:
4905 9ac99fda Guido Trotter
      if instance_name in exportlist[node]:
4906 9ac99fda Guido Trotter
        found = True
4907 72737a7f Iustin Pop
        if not self.rpc.call_export_remove(node, instance_name):
4908 9ac99fda Guido Trotter
          logger.Error("could not remove export for instance %s"
4909 9ac99fda Guido Trotter
                       " on node %s" % (instance_name, node))
4910 9ac99fda Guido Trotter
4911 9ac99fda Guido Trotter
    if fqdn_warn and not found:
4912 9ac99fda Guido Trotter
      feedback_fn("Export not found. If trying to remove an export belonging"
4913 9ac99fda Guido Trotter
                  " to a deleted instance please use its Fully Qualified"
4914 9ac99fda Guido Trotter
                  " Domain Name.")
4915 9ac99fda Guido Trotter
4916 9ac99fda Guido Trotter
4917 5c947f38 Iustin Pop
class TagsLU(NoHooksLU):
4918 5c947f38 Iustin Pop
  """Generic tags LU.
4919 5c947f38 Iustin Pop

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

4922 5c947f38 Iustin Pop
  """
4923 5c947f38 Iustin Pop
4924 8646adce Guido Trotter
  def ExpandNames(self):
4925 8646adce Guido Trotter
    self.needed_locks = {}
4926 8646adce Guido Trotter
    if self.op.kind == constants.TAG_NODE:
4927 5c947f38 Iustin Pop
      name = self.cfg.ExpandNodeName(self.op.name)
4928 5c947f38 Iustin Pop
      if name is None:
4929 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid node name (%s)" %
4930 3ecf6786 Iustin Pop
                                   (self.op.name,))
4931 5c947f38 Iustin Pop
      self.op.name = name
4932 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = name
4933 5c947f38 Iustin Pop
    elif self.op.kind == constants.TAG_INSTANCE:
4934 8f684e16 Iustin Pop
      name = self.cfg.ExpandInstanceName(self.op.name)
4935 5c947f38 Iustin Pop
      if name is None:
4936 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid instance name (%s)" %
4937 3ecf6786 Iustin Pop
                                   (self.op.name,))
4938 5c947f38 Iustin Pop
      self.op.name = name
4939 8646adce Guido Trotter
      self.needed_locks[locking.LEVEL_INSTANCE] = name
4940 8646adce Guido Trotter
4941 8646adce Guido Trotter
  def CheckPrereq(self):
4942 8646adce Guido Trotter
    """Check prerequisites.
4943 8646adce Guido Trotter

4944 8646adce Guido Trotter
    """
4945 8646adce Guido Trotter
    if self.op.kind == constants.TAG_CLUSTER:
4946 8646adce Guido Trotter
      self.target = self.cfg.GetClusterInfo()
4947 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_NODE:
4948 8646adce Guido Trotter
      self.target = self.cfg.GetNodeInfo(self.op.name)
4949 8646adce Guido Trotter
    elif self.op.kind == constants.TAG_INSTANCE:
4950 8646adce Guido Trotter
      self.target = self.cfg.GetInstanceInfo(self.op.name)
4951 5c947f38 Iustin Pop
    else:
4952 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
4953 3ecf6786 Iustin Pop
                                 str(self.op.kind))
4954 5c947f38 Iustin Pop
4955 5c947f38 Iustin Pop
4956 5c947f38 Iustin Pop
class LUGetTags(TagsLU):
4957 5c947f38 Iustin Pop
  """Returns the tags of a given object.
4958 5c947f38 Iustin Pop

4959 5c947f38 Iustin Pop
  """
4960 5c947f38 Iustin Pop
  _OP_REQP = ["kind", "name"]
4961 8646adce Guido Trotter
  REQ_BGL = False
4962 5c947f38 Iustin Pop
4963 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
4964 5c947f38 Iustin Pop
    """Returns the tag list.
4965 5c947f38 Iustin Pop

4966 5c947f38 Iustin Pop
    """
4967 5d414478 Oleksiy Mishchenko
    return list(self.target.GetTags())
4968 5c947f38 Iustin Pop
4969 5c947f38 Iustin Pop
4970 73415719 Iustin Pop
class LUSearchTags(NoHooksLU):
4971 73415719 Iustin Pop
  """Searches the tags for a given pattern.
4972 73415719 Iustin Pop

4973 73415719 Iustin Pop
  """
4974 73415719 Iustin Pop
  _OP_REQP = ["pattern"]
4975 8646adce Guido Trotter
  REQ_BGL = False
4976 8646adce Guido Trotter
4977 8646adce Guido Trotter
  def ExpandNames(self):
4978 8646adce Guido Trotter
    self.needed_locks = {}
4979 73415719 Iustin Pop
4980 73415719 Iustin Pop
  def CheckPrereq(self):
4981 73415719 Iustin Pop
    """Check prerequisites.
4982 73415719 Iustin Pop

4983 73415719 Iustin Pop
    This checks the pattern passed for validity by compiling it.
4984 73415719 Iustin Pop

4985 73415719 Iustin Pop
    """
4986 73415719 Iustin Pop
    try:
4987 73415719 Iustin Pop
      self.re = re.compile(self.op.pattern)
4988 73415719 Iustin Pop
    except re.error, err:
4989 73415719 Iustin Pop
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
4990 73415719 Iustin Pop
                                 (self.op.pattern, err))
4991 73415719 Iustin Pop
4992 73415719 Iustin Pop
  def Exec(self, feedback_fn):
4993 73415719 Iustin Pop
    """Returns the tag list.
4994 73415719 Iustin Pop

4995 73415719 Iustin Pop
    """
4996 73415719 Iustin Pop
    cfg = self.cfg
4997 73415719 Iustin Pop
    tgts = [("/cluster", cfg.GetClusterInfo())]
4998 8646adce Guido Trotter
    ilist = cfg.GetAllInstancesInfo().values()
4999 73415719 Iustin Pop
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
5000 8646adce Guido Trotter
    nlist = cfg.GetAllNodesInfo().values()
5001 73415719 Iustin Pop
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
5002 73415719 Iustin Pop
    results = []
5003 73415719 Iustin Pop
    for path, target in tgts:
5004 73415719 Iustin Pop
      for tag in target.GetTags():
5005 73415719 Iustin Pop
        if self.re.search(tag):
5006 73415719 Iustin Pop
          results.append((path, tag))
5007 73415719 Iustin Pop
    return results
5008 73415719 Iustin Pop
5009 73415719 Iustin Pop
5010 f27302fa Iustin Pop
class LUAddTags(TagsLU):
5011 5c947f38 Iustin Pop
  """Sets a tag on a given object.
5012 5c947f38 Iustin Pop

5013 5c947f38 Iustin Pop
  """
5014 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
5015 8646adce Guido Trotter
  REQ_BGL = False
5016 5c947f38 Iustin Pop
5017 5c947f38 Iustin Pop
  def CheckPrereq(self):
5018 5c947f38 Iustin Pop
    """Check prerequisites.
5019 5c947f38 Iustin Pop

5020 5c947f38 Iustin Pop
    This checks the type and length of the tag name and value.
5021 5c947f38 Iustin Pop

5022 5c947f38 Iustin Pop
    """
5023 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
5024 f27302fa Iustin Pop
    for tag in self.op.tags:
5025 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
5026 5c947f38 Iustin Pop
5027 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
5028 5c947f38 Iustin Pop
    """Sets the tag.
5029 5c947f38 Iustin Pop

5030 5c947f38 Iustin Pop
    """
5031 5c947f38 Iustin Pop
    try:
5032 f27302fa Iustin Pop
      for tag in self.op.tags:
5033 f27302fa Iustin Pop
        self.target.AddTag(tag)
5034 5c947f38 Iustin Pop
    except errors.TagError, err:
5035 3ecf6786 Iustin Pop
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
5036 5c947f38 Iustin Pop
    try:
5037 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
5038 5c947f38 Iustin Pop
    except errors.ConfigurationError:
5039 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
5040 3ecf6786 Iustin Pop
                                " config file and the operation has been"
5041 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
5042 5c947f38 Iustin Pop
5043 5c947f38 Iustin Pop
5044 f27302fa Iustin Pop
class LUDelTags(TagsLU):
5045 f27302fa Iustin Pop
  """Delete a list of tags from a given object.
5046 5c947f38 Iustin Pop

5047 5c947f38 Iustin Pop
  """
5048 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
5049 8646adce Guido Trotter
  REQ_BGL = False
5050 5c947f38 Iustin Pop
5051 5c947f38 Iustin Pop
  def CheckPrereq(self):
5052 5c947f38 Iustin Pop
    """Check prerequisites.
5053 5c947f38 Iustin Pop

5054 5c947f38 Iustin Pop
    This checks that we have the given tag.
5055 5c947f38 Iustin Pop

5056 5c947f38 Iustin Pop
    """
5057 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
5058 f27302fa Iustin Pop
    for tag in self.op.tags:
5059 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
5060 f27302fa Iustin Pop
    del_tags = frozenset(self.op.tags)
5061 f27302fa Iustin Pop
    cur_tags = self.target.GetTags()
5062 f27302fa Iustin Pop
    if not del_tags <= cur_tags:
5063 f27302fa Iustin Pop
      diff_tags = del_tags - cur_tags
5064 f27302fa Iustin Pop
      diff_names = ["'%s'" % tag for tag in diff_tags]
5065 f27302fa Iustin Pop
      diff_names.sort()
5066 f27302fa Iustin Pop
      raise errors.OpPrereqError("Tag(s) %s not found" %
5067 f27302fa Iustin Pop
                                 (",".join(diff_names)))
5068 5c947f38 Iustin Pop
5069 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
5070 5c947f38 Iustin Pop
    """Remove the tag from the object.
5071 5c947f38 Iustin Pop

5072 5c947f38 Iustin Pop
    """
5073 f27302fa Iustin Pop
    for tag in self.op.tags:
5074 f27302fa Iustin Pop
      self.target.RemoveTag(tag)
5075 5c947f38 Iustin Pop
    try:
5076 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
5077 5c947f38 Iustin Pop
    except errors.ConfigurationError:
5078 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
5079 3ecf6786 Iustin Pop
                                " config file and the operation has been"
5080 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
5081 06009e27 Iustin Pop
5082 0eed6e61 Guido Trotter
5083 06009e27 Iustin Pop
class LUTestDelay(NoHooksLU):
5084 06009e27 Iustin Pop
  """Sleep for a specified amount of time.
5085 06009e27 Iustin Pop

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

5089 06009e27 Iustin Pop
  """
5090 06009e27 Iustin Pop
  _OP_REQP = ["duration", "on_master", "on_nodes"]
5091 fbe9022f Guido Trotter
  REQ_BGL = False
5092 06009e27 Iustin Pop
5093 fbe9022f Guido Trotter
  def ExpandNames(self):
5094 fbe9022f Guido Trotter
    """Expand names and set required locks.
5095 06009e27 Iustin Pop

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

5098 06009e27 Iustin Pop
    """
5099 fbe9022f Guido Trotter
    self.needed_locks = {}
5100 06009e27 Iustin Pop
    if self.op.on_nodes:
5101 fbe9022f Guido Trotter
      # _GetWantedNodes can be used here, but is not always appropriate to use
5102 fbe9022f Guido Trotter
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
5103 fbe9022f Guido Trotter
      # more information.
5104 06009e27 Iustin Pop
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
5105 fbe9022f Guido Trotter
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
5106 fbe9022f Guido Trotter
5107 fbe9022f Guido Trotter
  def CheckPrereq(self):
5108 fbe9022f Guido Trotter
    """Check prerequisites.
5109 fbe9022f Guido Trotter

5110 fbe9022f Guido Trotter
    """
5111 06009e27 Iustin Pop
5112 06009e27 Iustin Pop
  def Exec(self, feedback_fn):
5113 06009e27 Iustin Pop
    """Do the actual sleep.
5114 06009e27 Iustin Pop

5115 06009e27 Iustin Pop
    """
5116 06009e27 Iustin Pop
    if self.op.on_master:
5117 06009e27 Iustin Pop
      if not utils.TestDelay(self.op.duration):
5118 06009e27 Iustin Pop
        raise errors.OpExecError("Error during master delay test")
5119 06009e27 Iustin Pop
    if self.op.on_nodes:
5120 72737a7f Iustin Pop
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
5121 06009e27 Iustin Pop
      if not result:
5122 06009e27 Iustin Pop
        raise errors.OpExecError("Complete failure from rpc call")
5123 06009e27 Iustin Pop
      for node, node_result in result.items():
5124 06009e27 Iustin Pop
        if not node_result:
5125 06009e27 Iustin Pop
          raise errors.OpExecError("Failure during rpc call to node %s,"
5126 06009e27 Iustin Pop
                                   " result: %s" % (node, node_result))
5127 d61df03e Iustin Pop
5128 d61df03e Iustin Pop
5129 d1c2dd75 Iustin Pop
class IAllocator(object):
5130 d1c2dd75 Iustin Pop
  """IAllocator framework.
5131 d61df03e Iustin Pop

5132 d1c2dd75 Iustin Pop
  An IAllocator instance has three sets of attributes:
5133 d6a02168 Michael Hanselmann
    - cfg that is needed to query the cluster
5134 d1c2dd75 Iustin Pop
    - input data (all members of the _KEYS class attribute are required)
5135 d1c2dd75 Iustin Pop
    - four buffer attributes (in|out_data|text), that represent the
5136 d1c2dd75 Iustin Pop
      input (to the external script) in text and data structure format,
5137 d1c2dd75 Iustin Pop
      and the output from it, again in two formats
5138 d1c2dd75 Iustin Pop
    - the result variables from the script (success, info, nodes) for
5139 d1c2dd75 Iustin Pop
      easy usage
5140 d61df03e Iustin Pop

5141 d61df03e Iustin Pop
  """
5142 29859cb7 Iustin Pop
  _ALLO_KEYS = [
5143 d1c2dd75 Iustin Pop
    "mem_size", "disks", "disk_template",
5144 d1c2dd75 Iustin Pop
    "os", "tags", "nics", "vcpus",
5145 d1c2dd75 Iustin Pop
    ]
5146 29859cb7 Iustin Pop
  _RELO_KEYS = [
5147 29859cb7 Iustin Pop
    "relocate_from",
5148 29859cb7 Iustin Pop
    ]
5149 d1c2dd75 Iustin Pop
5150 72737a7f Iustin Pop
  def __init__(self, lu, mode, name, **kwargs):
5151 72737a7f Iustin Pop
    self.lu = lu
5152 d1c2dd75 Iustin Pop
    # init buffer variables
5153 d1c2dd75 Iustin Pop
    self.in_text = self.out_text = self.in_data = self.out_data = None
5154 d1c2dd75 Iustin Pop
    # init all input fields so that pylint is happy
5155 29859cb7 Iustin Pop
    self.mode = mode
5156 29859cb7 Iustin Pop
    self.name = name
5157 d1c2dd75 Iustin Pop
    self.mem_size = self.disks = self.disk_template = None
5158 d1c2dd75 Iustin Pop
    self.os = self.tags = self.nics = self.vcpus = None
5159 29859cb7 Iustin Pop
    self.relocate_from = None
5160 27579978 Iustin Pop
    # computed fields
5161 27579978 Iustin Pop
    self.required_nodes = None
5162 d1c2dd75 Iustin Pop
    # init result fields
5163 d1c2dd75 Iustin Pop
    self.success = self.info = self.nodes = None
5164 29859cb7 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5165 29859cb7 Iustin Pop
      keyset = self._ALLO_KEYS
5166 29859cb7 Iustin Pop
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
5167 29859cb7 Iustin Pop
      keyset = self._RELO_KEYS
5168 29859cb7 Iustin Pop
    else:
5169 29859cb7 Iustin Pop
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
5170 29859cb7 Iustin Pop
                                   " IAllocator" % self.mode)
5171 d1c2dd75 Iustin Pop
    for key in kwargs:
5172 29859cb7 Iustin Pop
      if key not in keyset:
5173 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
5174 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
5175 d1c2dd75 Iustin Pop
      setattr(self, key, kwargs[key])
5176 29859cb7 Iustin Pop
    for key in keyset:
5177 d1c2dd75 Iustin Pop
      if key not in kwargs:
5178 d1c2dd75 Iustin Pop
        raise errors.ProgrammerError("Missing input parameter '%s' to"
5179 d1c2dd75 Iustin Pop
                                     " IAllocator" % key)
5180 d1c2dd75 Iustin Pop
    self._BuildInputData()
5181 d1c2dd75 Iustin Pop
5182 d1c2dd75 Iustin Pop
  def _ComputeClusterData(self):
5183 d1c2dd75 Iustin Pop
    """Compute the generic allocator input data.
5184 d1c2dd75 Iustin Pop

5185 d1c2dd75 Iustin Pop
    This is the data that is independent of the actual operation.
5186 d1c2dd75 Iustin Pop

5187 d1c2dd75 Iustin Pop
    """
5188 72737a7f Iustin Pop
    cfg = self.lu.cfg
5189 e69d05fd Iustin Pop
    cluster_info = cfg.GetClusterInfo()
5190 d1c2dd75 Iustin Pop
    # cluster data
5191 d1c2dd75 Iustin Pop
    data = {
5192 d1c2dd75 Iustin Pop
      "version": 1,
5193 72737a7f Iustin Pop
      "cluster_name": cfg.GetClusterName(),
5194 e69d05fd Iustin Pop
      "cluster_tags": list(cluster_info.GetTags()),
5195 e69d05fd Iustin Pop
      "enable_hypervisors": list(cluster_info.enabled_hypervisors),
5196 d1c2dd75 Iustin Pop
      # we don't have job IDs
5197 d61df03e Iustin Pop
      }
5198 d61df03e Iustin Pop
5199 338e51e8 Iustin Pop
    i_list = []
5200 338e51e8 Iustin Pop
    cluster = self.cfg.GetClusterInfo()
5201 338e51e8 Iustin Pop
    for iname in cfg.GetInstanceList():
5202 338e51e8 Iustin Pop
      i_obj = cfg.GetInstanceInfo(iname)
5203 338e51e8 Iustin Pop
      i_list.append((i_obj, cluster.FillBE(i_obj)))
5204 6286519f Iustin Pop
5205 d1c2dd75 Iustin Pop
    # node data
5206 d1c2dd75 Iustin Pop
    node_results = {}
5207 d1c2dd75 Iustin Pop
    node_list = cfg.GetNodeList()
5208 e69d05fd Iustin Pop
    # FIXME: here we have only one hypervisor information, but
5209 e69d05fd Iustin Pop
    # instance can belong to different hypervisors
5210 72737a7f Iustin Pop
    node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
5211 72737a7f Iustin Pop
                                           cfg.GetHypervisorType())
5212 d1c2dd75 Iustin Pop
    for nname in node_list:
5213 d1c2dd75 Iustin Pop
      ninfo = cfg.GetNodeInfo(nname)
5214 d1c2dd75 Iustin Pop
      if nname not in node_data or not isinstance(node_data[nname], dict):
5215 d1c2dd75 Iustin Pop
        raise errors.OpExecError("Can't get data for node %s" % nname)
5216 d1c2dd75 Iustin Pop
      remote_info = node_data[nname]
5217 b2662e7f Iustin Pop
      for attr in ['memory_total', 'memory_free', 'memory_dom0',
5218 4337cf1b Iustin Pop
                   'vg_size', 'vg_free', 'cpu_total']:
5219 d1c2dd75 Iustin Pop
        if attr not in remote_info:
5220 d1c2dd75 Iustin Pop
          raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
5221 d1c2dd75 Iustin Pop
                                   (nname, attr))
5222 d1c2dd75 Iustin Pop
        try:
5223 b2662e7f Iustin Pop
          remote_info[attr] = int(remote_info[attr])
5224 d1c2dd75 Iustin Pop
        except ValueError, err:
5225 d1c2dd75 Iustin Pop
          raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
5226 d1c2dd75 Iustin Pop
                                   " %s" % (nname, attr, str(err)))
5227 6286519f Iustin Pop
      # compute memory used by primary instances
5228 6286519f Iustin Pop
      i_p_mem = i_p_up_mem = 0
5229 338e51e8 Iustin Pop
      for iinfo, beinfo in i_list:
5230 6286519f Iustin Pop
        if iinfo.primary_node == nname:
5231 338e51e8 Iustin Pop
          i_p_mem += beinfo[constants.BE_MEMORY]
5232 6286519f Iustin Pop
          if iinfo.status == "up":
5233 338e51e8 Iustin Pop
            i_p_up_mem += beinfo[constants.BE_MEMORY]
5234 6286519f Iustin Pop
5235 b2662e7f Iustin Pop
      # compute memory used by instances
5236 d1c2dd75 Iustin Pop
      pnr = {
5237 d1c2dd75 Iustin Pop
        "tags": list(ninfo.GetTags()),
5238 b2662e7f Iustin Pop
        "total_memory": remote_info['memory_total'],
5239 b2662e7f Iustin Pop
        "reserved_memory": remote_info['memory_dom0'],
5240 b2662e7f Iustin Pop
        "free_memory": remote_info['memory_free'],
5241 6286519f Iustin Pop
        "i_pri_memory": i_p_mem,
5242 6286519f Iustin Pop
        "i_pri_up_memory": i_p_up_mem,
5243 b2662e7f Iustin Pop
        "total_disk": remote_info['vg_size'],
5244 b2662e7f Iustin Pop
        "free_disk": remote_info['vg_free'],
5245 d1c2dd75 Iustin Pop
        "primary_ip": ninfo.primary_ip,
5246 d1c2dd75 Iustin Pop
        "secondary_ip": ninfo.secondary_ip,
5247 4337cf1b Iustin Pop
        "total_cpus": remote_info['cpu_total'],
5248 d1c2dd75 Iustin Pop
        }
5249 d1c2dd75 Iustin Pop
      node_results[nname] = pnr
5250 d1c2dd75 Iustin Pop
    data["nodes"] = node_results
5251 d1c2dd75 Iustin Pop
5252 d1c2dd75 Iustin Pop
    # instance data
5253 d1c2dd75 Iustin Pop
    instance_data = {}
5254 338e51e8 Iustin Pop
    for iinfo, beinfo in i_list:
5255 d1c2dd75 Iustin Pop
      nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
5256 d1c2dd75 Iustin Pop
                  for n in iinfo.nics]
5257 d1c2dd75 Iustin Pop
      pir = {
5258 d1c2dd75 Iustin Pop
        "tags": list(iinfo.GetTags()),
5259 d1c2dd75 Iustin Pop
        "should_run": iinfo.status == "up",
5260 338e51e8 Iustin Pop
        "vcpus": beinfo[constants.BE_VCPUS],
5261 338e51e8 Iustin Pop
        "memory": beinfo[constants.BE_MEMORY],
5262 d1c2dd75 Iustin Pop
        "os": iinfo.os,
5263 d1c2dd75 Iustin Pop
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
5264 d1c2dd75 Iustin Pop
        "nics": nic_data,
5265 d1c2dd75 Iustin Pop
        "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
5266 d1c2dd75 Iustin Pop
        "disk_template": iinfo.disk_template,
5267 e69d05fd Iustin Pop
        "hypervisor": iinfo.hypervisor,
5268 d1c2dd75 Iustin Pop
        }
5269 768f0a80 Iustin Pop
      instance_data[iinfo.name] = pir
5270 d61df03e Iustin Pop
5271 d1c2dd75 Iustin Pop
    data["instances"] = instance_data
5272 d61df03e Iustin Pop
5273 d1c2dd75 Iustin Pop
    self.in_data = data
5274 d61df03e Iustin Pop
5275 d1c2dd75 Iustin Pop
  def _AddNewInstance(self):
5276 d1c2dd75 Iustin Pop
    """Add new instance data to allocator structure.
5277 d61df03e Iustin Pop

5278 d1c2dd75 Iustin Pop
    This in combination with _AllocatorGetClusterData will create the
5279 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
5280 d61df03e Iustin Pop

5281 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
5282 d1c2dd75 Iustin Pop
    done.
5283 d61df03e Iustin Pop

5284 d1c2dd75 Iustin Pop
    """
5285 d1c2dd75 Iustin Pop
    data = self.in_data
5286 d1c2dd75 Iustin Pop
    if len(self.disks) != 2:
5287 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Only two-disk configurations supported")
5288 d1c2dd75 Iustin Pop
5289 d1c2dd75 Iustin Pop
    disk_space = _ComputeDiskSize(self.disk_template,
5290 d1c2dd75 Iustin Pop
                                  self.disks[0]["size"], self.disks[1]["size"])
5291 d1c2dd75 Iustin Pop
5292 27579978 Iustin Pop
    if self.disk_template in constants.DTS_NET_MIRROR:
5293 27579978 Iustin Pop
      self.required_nodes = 2
5294 27579978 Iustin Pop
    else:
5295 27579978 Iustin Pop
      self.required_nodes = 1
5296 d1c2dd75 Iustin Pop
    request = {
5297 d1c2dd75 Iustin Pop
      "type": "allocate",
5298 d1c2dd75 Iustin Pop
      "name": self.name,
5299 d1c2dd75 Iustin Pop
      "disk_template": self.disk_template,
5300 d1c2dd75 Iustin Pop
      "tags": self.tags,
5301 d1c2dd75 Iustin Pop
      "os": self.os,
5302 d1c2dd75 Iustin Pop
      "vcpus": self.vcpus,
5303 d1c2dd75 Iustin Pop
      "memory": self.mem_size,
5304 d1c2dd75 Iustin Pop
      "disks": self.disks,
5305 d1c2dd75 Iustin Pop
      "disk_space_total": disk_space,
5306 d1c2dd75 Iustin Pop
      "nics": self.nics,
5307 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
5308 d1c2dd75 Iustin Pop
      }
5309 d1c2dd75 Iustin Pop
    data["request"] = request
5310 298fe380 Iustin Pop
5311 d1c2dd75 Iustin Pop
  def _AddRelocateInstance(self):
5312 d1c2dd75 Iustin Pop
    """Add relocate instance data to allocator structure.
5313 298fe380 Iustin Pop

5314 d1c2dd75 Iustin Pop
    This in combination with _IAllocatorGetClusterData will create the
5315 d1c2dd75 Iustin Pop
    correct structure needed as input for the allocator.
5316 d61df03e Iustin Pop

5317 d1c2dd75 Iustin Pop
    The checks for the completeness of the opcode must have already been
5318 d1c2dd75 Iustin Pop
    done.
5319 d61df03e Iustin Pop

5320 d1c2dd75 Iustin Pop
    """
5321 72737a7f Iustin Pop
    instance = self.lu.cfg.GetInstanceInfo(self.name)
5322 27579978 Iustin Pop
    if instance is None:
5323 27579978 Iustin Pop
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
5324 27579978 Iustin Pop
                                   " IAllocator" % self.name)
5325 27579978 Iustin Pop
5326 27579978 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5327 27579978 Iustin Pop
      raise errors.OpPrereqError("Can't relocate non-mirrored instances")
5328 27579978 Iustin Pop
5329 2a139bb0 Iustin Pop
    if len(instance.secondary_nodes) != 1:
5330 2a139bb0 Iustin Pop
      raise errors.OpPrereqError("Instance has not exactly one secondary node")
5331 2a139bb0 Iustin Pop
5332 27579978 Iustin Pop
    self.required_nodes = 1
5333 27579978 Iustin Pop
5334 27579978 Iustin Pop
    disk_space = _ComputeDiskSize(instance.disk_template,
5335 27579978 Iustin Pop
                                  instance.disks[0].size,
5336 27579978 Iustin Pop
                                  instance.disks[1].size)
5337 27579978 Iustin Pop
5338 d1c2dd75 Iustin Pop
    request = {
5339 2a139bb0 Iustin Pop
      "type": "relocate",
5340 d1c2dd75 Iustin Pop
      "name": self.name,
5341 27579978 Iustin Pop
      "disk_space_total": disk_space,
5342 27579978 Iustin Pop
      "required_nodes": self.required_nodes,
5343 29859cb7 Iustin Pop
      "relocate_from": self.relocate_from,
5344 d1c2dd75 Iustin Pop
      }
5345 27579978 Iustin Pop
    self.in_data["request"] = request
5346 d61df03e Iustin Pop
5347 d1c2dd75 Iustin Pop
  def _BuildInputData(self):
5348 d1c2dd75 Iustin Pop
    """Build input data structures.
5349 d61df03e Iustin Pop

5350 d1c2dd75 Iustin Pop
    """
5351 d1c2dd75 Iustin Pop
    self._ComputeClusterData()
5352 d61df03e Iustin Pop
5353 d1c2dd75 Iustin Pop
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
5354 d1c2dd75 Iustin Pop
      self._AddNewInstance()
5355 d1c2dd75 Iustin Pop
    else:
5356 d1c2dd75 Iustin Pop
      self._AddRelocateInstance()
5357 d61df03e Iustin Pop
5358 d1c2dd75 Iustin Pop
    self.in_text = serializer.Dump(self.in_data)
5359 d61df03e Iustin Pop
5360 72737a7f Iustin Pop
  def Run(self, name, validate=True, call_fn=None):
5361 d1c2dd75 Iustin Pop
    """Run an instance allocator and return the results.
5362 298fe380 Iustin Pop

5363 d1c2dd75 Iustin Pop
    """
5364 72737a7f Iustin Pop
    if call_fn is None:
5365 72737a7f Iustin Pop
      call_fn = self.lu.rpc.call_iallocator_runner
5366 d1c2dd75 Iustin Pop
    data = self.in_text
5367 298fe380 Iustin Pop
5368 72737a7f Iustin Pop
    result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text)
5369 298fe380 Iustin Pop
5370 43f5ea7a Guido Trotter
    if not isinstance(result, (list, tuple)) or len(result) != 4:
5371 8d528b7c Iustin Pop
      raise errors.OpExecError("Invalid result from master iallocator runner")
5372 8d528b7c Iustin Pop
5373 8d528b7c Iustin Pop
    rcode, stdout, stderr, fail = result
5374 8d528b7c Iustin Pop
5375 8d528b7c Iustin Pop
    if rcode == constants.IARUN_NOTFOUND:
5376 8d528b7c Iustin Pop
      raise errors.OpExecError("Can't find allocator '%s'" % name)
5377 8d528b7c Iustin Pop
    elif rcode == constants.IARUN_FAILURE:
5378 38206f3c Iustin Pop
      raise errors.OpExecError("Instance allocator call failed: %s,"
5379 38206f3c Iustin Pop
                               " output: %s" % (fail, stdout+stderr))
5380 8d528b7c Iustin Pop
    self.out_text = stdout
5381 d1c2dd75 Iustin Pop
    if validate:
5382 d1c2dd75 Iustin Pop
      self._ValidateResult()
5383 298fe380 Iustin Pop
5384 d1c2dd75 Iustin Pop
  def _ValidateResult(self):
5385 d1c2dd75 Iustin Pop
    """Process the allocator results.
5386 538475ca Iustin Pop

5387 d1c2dd75 Iustin Pop
    This will process and if successful save the result in
5388 d1c2dd75 Iustin Pop
    self.out_data and the other parameters.
5389 538475ca Iustin Pop

5390 d1c2dd75 Iustin Pop
    """
5391 d1c2dd75 Iustin Pop
    try:
5392 d1c2dd75 Iustin Pop
      rdict = serializer.Load(self.out_text)
5393 d1c2dd75 Iustin Pop
    except Exception, err:
5394 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
5395 d1c2dd75 Iustin Pop
5396 d1c2dd75 Iustin Pop
    if not isinstance(rdict, dict):
5397 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
5398 538475ca Iustin Pop
5399 d1c2dd75 Iustin Pop
    for key in "success", "info", "nodes":
5400 d1c2dd75 Iustin Pop
      if key not in rdict:
5401 d1c2dd75 Iustin Pop
        raise errors.OpExecError("Can't parse iallocator results:"
5402 d1c2dd75 Iustin Pop
                                 " missing key '%s'" % key)
5403 d1c2dd75 Iustin Pop
      setattr(self, key, rdict[key])
5404 538475ca Iustin Pop
5405 d1c2dd75 Iustin Pop
    if not isinstance(rdict["nodes"], list):
5406 d1c2dd75 Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
5407 d1c2dd75 Iustin Pop
                               " is not a list")
5408 d1c2dd75 Iustin Pop
    self.out_data = rdict
5409 538475ca Iustin Pop
5410 538475ca Iustin Pop
5411 d61df03e Iustin Pop
class LUTestAllocator(NoHooksLU):
5412 d61df03e Iustin Pop
  """Run allocator tests.
5413 d61df03e Iustin Pop

5414 d61df03e Iustin Pop
  This LU runs the allocator tests
5415 d61df03e Iustin Pop

5416 d61df03e Iustin Pop
  """
5417 d61df03e Iustin Pop
  _OP_REQP = ["direction", "mode", "name"]
5418 d61df03e Iustin Pop
5419 d61df03e Iustin Pop
  def CheckPrereq(self):
5420 d61df03e Iustin Pop
    """Check prerequisites.
5421 d61df03e Iustin Pop

5422 d61df03e Iustin Pop
    This checks the opcode parameters depending on the director and mode test.
5423 d61df03e Iustin Pop

5424 d61df03e Iustin Pop
    """
5425 298fe380 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5426 d61df03e Iustin Pop
      for attr in ["name", "mem_size", "disks", "disk_template",
5427 d61df03e Iustin Pop
                   "os", "tags", "nics", "vcpus"]:
5428 d61df03e Iustin Pop
        if not hasattr(self.op, attr):
5429 d61df03e Iustin Pop
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
5430 d61df03e Iustin Pop
                                     attr)
5431 d61df03e Iustin Pop
      iname = self.cfg.ExpandInstanceName(self.op.name)
5432 d61df03e Iustin Pop
      if iname is not None:
5433 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
5434 d61df03e Iustin Pop
                                   iname)
5435 d61df03e Iustin Pop
      if not isinstance(self.op.nics, list):
5436 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'nics'")
5437 d61df03e Iustin Pop
      for row in self.op.nics:
5438 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
5439 d61df03e Iustin Pop
            "mac" not in row or
5440 d61df03e Iustin Pop
            "ip" not in row or
5441 d61df03e Iustin Pop
            "bridge" not in row):
5442 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
5443 d61df03e Iustin Pop
                                     " 'nics' parameter")
5444 d61df03e Iustin Pop
      if not isinstance(self.op.disks, list):
5445 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'disks'")
5446 298fe380 Iustin Pop
      if len(self.op.disks) != 2:
5447 298fe380 Iustin Pop
        raise errors.OpPrereqError("Only two-disk configurations supported")
5448 d61df03e Iustin Pop
      for row in self.op.disks:
5449 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
5450 d61df03e Iustin Pop
            "size" not in row or
5451 d61df03e Iustin Pop
            not isinstance(row["size"], int) or
5452 d61df03e Iustin Pop
            "mode" not in row or
5453 d61df03e Iustin Pop
            row["mode"] not in ['r', 'w']):
5454 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
5455 d61df03e Iustin Pop
                                     " 'disks' parameter")
5456 298fe380 Iustin Pop
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
5457 d61df03e Iustin Pop
      if not hasattr(self.op, "name"):
5458 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
5459 d61df03e Iustin Pop
      fname = self.cfg.ExpandInstanceName(self.op.name)
5460 d61df03e Iustin Pop
      if fname is None:
5461 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
5462 d61df03e Iustin Pop
                                   self.op.name)
5463 d61df03e Iustin Pop
      self.op.name = fname
5464 29859cb7 Iustin Pop
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
5465 d61df03e Iustin Pop
    else:
5466 d61df03e Iustin Pop
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
5467 d61df03e Iustin Pop
                                 self.op.mode)
5468 d61df03e Iustin Pop
5469 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
5470 298fe380 Iustin Pop
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
5471 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing allocator name")
5472 298fe380 Iustin Pop
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
5473 d61df03e Iustin Pop
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
5474 d61df03e Iustin Pop
                                 self.op.direction)
5475 d61df03e Iustin Pop
5476 d61df03e Iustin Pop
  def Exec(self, feedback_fn):
5477 d61df03e Iustin Pop
    """Run the allocator test.
5478 d61df03e Iustin Pop

5479 d61df03e Iustin Pop
    """
5480 29859cb7 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
5481 72737a7f Iustin Pop
      ial = IAllocator(self,
5482 29859cb7 Iustin Pop
                       mode=self.op.mode,
5483 29859cb7 Iustin Pop
                       name=self.op.name,
5484 29859cb7 Iustin Pop
                       mem_size=self.op.mem_size,
5485 29859cb7 Iustin Pop
                       disks=self.op.disks,
5486 29859cb7 Iustin Pop
                       disk_template=self.op.disk_template,
5487 29859cb7 Iustin Pop
                       os=self.op.os,
5488 29859cb7 Iustin Pop
                       tags=self.op.tags,
5489 29859cb7 Iustin Pop
                       nics=self.op.nics,
5490 29859cb7 Iustin Pop
                       vcpus=self.op.vcpus,
5491 29859cb7 Iustin Pop
                       )
5492 29859cb7 Iustin Pop
    else:
5493 72737a7f Iustin Pop
      ial = IAllocator(self,
5494 29859cb7 Iustin Pop
                       mode=self.op.mode,
5495 29859cb7 Iustin Pop
                       name=self.op.name,
5496 29859cb7 Iustin Pop
                       relocate_from=list(self.relocate_from),
5497 29859cb7 Iustin Pop
                       )
5498 d61df03e Iustin Pop
5499 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
5500 d1c2dd75 Iustin Pop
      result = ial.in_text
5501 298fe380 Iustin Pop
    else:
5502 d1c2dd75 Iustin Pop
      ial.Run(self.op.allocator, validate=False)
5503 d1c2dd75 Iustin Pop
      result = ial.out_text
5504 298fe380 Iustin Pop
    return result