root / lib / cmdlib.py @ 0a66c968
History | View | Annotate | Download (216.8 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Module implementing the master-side code."""
|
23 |
|
24 |
# pylint: disable-msg=W0613,W0201
|
25 |
|
26 |
import os |
27 |
import os.path |
28 |
import sha |
29 |
import time |
30 |
import tempfile |
31 |
import re |
32 |
import platform |
33 |
import logging |
34 |
import copy |
35 |
import random |
36 |
|
37 |
from ganeti import ssh |
38 |
from ganeti import utils |
39 |
from ganeti import errors |
40 |
from ganeti import hypervisor |
41 |
from ganeti import locking |
42 |
from ganeti import constants |
43 |
from ganeti import objects |
44 |
from ganeti import opcodes |
45 |
from ganeti import serializer |
46 |
from ganeti import ssconf |
47 |
|
48 |
|
49 |
class LogicalUnit(object): |
50 |
"""Logical Unit base class.
|
51 |
|
52 |
Subclasses must follow these rules:
|
53 |
- implement ExpandNames
|
54 |
- implement CheckPrereq
|
55 |
- implement Exec
|
56 |
- implement BuildHooksEnv
|
57 |
- redefine HPATH and HTYPE
|
58 |
- optionally redefine their run requirements:
|
59 |
REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
|
60 |
|
61 |
Note that all commands require root permissions.
|
62 |
|
63 |
"""
|
64 |
HPATH = None
|
65 |
HTYPE = None
|
66 |
_OP_REQP = [] |
67 |
REQ_BGL = True
|
68 |
|
69 |
def __init__(self, processor, op, context, rpc): |
70 |
"""Constructor for LogicalUnit.
|
71 |
|
72 |
This needs to be overriden in derived classes in order to check op
|
73 |
validity.
|
74 |
|
75 |
"""
|
76 |
self.proc = processor
|
77 |
self.op = op
|
78 |
self.cfg = context.cfg
|
79 |
self.context = context
|
80 |
self.rpc = rpc
|
81 |
# Dicts used to declare locking needs to mcpu
|
82 |
self.needed_locks = None |
83 |
self.acquired_locks = {}
|
84 |
self.share_locks = dict(((i, 0) for i in locking.LEVELS)) |
85 |
self.add_locks = {}
|
86 |
self.remove_locks = {}
|
87 |
# Used to force good behavior when calling helper functions
|
88 |
self.recalculate_locks = {}
|
89 |
self.__ssh = None |
90 |
# logging
|
91 |
self.LogWarning = processor.LogWarning
|
92 |
self.LogInfo = processor.LogInfo
|
93 |
|
94 |
for attr_name in self._OP_REQP: |
95 |
attr_val = getattr(op, attr_name, None) |
96 |
if attr_val is None: |
97 |
raise errors.OpPrereqError("Required parameter '%s' missing" % |
98 |
attr_name) |
99 |
self.CheckArguments()
|
100 |
|
101 |
def __GetSSH(self): |
102 |
"""Returns the SshRunner object
|
103 |
|
104 |
"""
|
105 |
if not self.__ssh: |
106 |
self.__ssh = ssh.SshRunner(self.cfg.GetClusterName()) |
107 |
return self.__ssh |
108 |
|
109 |
ssh = property(fget=__GetSSH)
|
110 |
|
111 |
def CheckArguments(self): |
112 |
"""Check syntactic validity for the opcode arguments.
|
113 |
|
114 |
This method is for doing a simple syntactic check and ensure
|
115 |
validity of opcode parameters, without any cluster-related
|
116 |
checks. While the same can be accomplished in ExpandNames and/or
|
117 |
CheckPrereq, doing these separate is better because:
|
118 |
|
119 |
- ExpandNames is left as as purely a lock-related function
|
120 |
- CheckPrereq is run after we have aquired locks (and possible
|
121 |
waited for them)
|
122 |
|
123 |
The function is allowed to change the self.op attribute so that
|
124 |
later methods can no longer worry about missing parameters.
|
125 |
|
126 |
"""
|
127 |
pass
|
128 |
|
129 |
def ExpandNames(self): |
130 |
"""Expand names for this LU.
|
131 |
|
132 |
This method is called before starting to execute the opcode, and it should
|
133 |
update all the parameters of the opcode to their canonical form (e.g. a
|
134 |
short node name must be fully expanded after this method has successfully
|
135 |
completed). This way locking, hooks, logging, ecc. can work correctly.
|
136 |
|
137 |
LUs which implement this method must also populate the self.needed_locks
|
138 |
member, as a dict with lock levels as keys, and a list of needed lock names
|
139 |
as values. Rules:
|
140 |
|
141 |
- use an empty dict if you don't need any lock
|
142 |
- if you don't need any lock at a particular level omit that level
|
143 |
- don't put anything for the BGL level
|
144 |
- if you want all locks at a level use locking.ALL_SET as a value
|
145 |
|
146 |
If you need to share locks (rather than acquire them exclusively) at one
|
147 |
level you can modify self.share_locks, setting a true value (usually 1) for
|
148 |
that level. By default locks are not shared.
|
149 |
|
150 |
Examples::
|
151 |
|
152 |
# Acquire all nodes and one instance
|
153 |
self.needed_locks = {
|
154 |
locking.LEVEL_NODE: locking.ALL_SET,
|
155 |
locking.LEVEL_INSTANCE: ['instance1.example.tld'],
|
156 |
}
|
157 |
# Acquire just two nodes
|
158 |
self.needed_locks = {
|
159 |
locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
|
160 |
}
|
161 |
# Acquire no locks
|
162 |
self.needed_locks = {} # No, you can't leave it to the default value None
|
163 |
|
164 |
"""
|
165 |
# The implementation of this method is mandatory only if the new LU is
|
166 |
# concurrent, so that old LUs don't need to be changed all at the same
|
167 |
# time.
|
168 |
if self.REQ_BGL: |
169 |
self.needed_locks = {} # Exclusive LUs don't need locks. |
170 |
else:
|
171 |
raise NotImplementedError |
172 |
|
173 |
def DeclareLocks(self, level): |
174 |
"""Declare LU locking needs for a level
|
175 |
|
176 |
While most LUs can just declare their locking needs at ExpandNames time,
|
177 |
sometimes there's the need to calculate some locks after having acquired
|
178 |
the ones before. This function is called just before acquiring locks at a
|
179 |
particular level, but after acquiring the ones at lower levels, and permits
|
180 |
such calculations. It can be used to modify self.needed_locks, and by
|
181 |
default it does nothing.
|
182 |
|
183 |
This function is only called if you have something already set in
|
184 |
self.needed_locks for the level.
|
185 |
|
186 |
@param level: Locking level which is going to be locked
|
187 |
@type level: member of ganeti.locking.LEVELS
|
188 |
|
189 |
"""
|
190 |
|
191 |
def CheckPrereq(self): |
192 |
"""Check prerequisites for this LU.
|
193 |
|
194 |
This method should check that the prerequisites for the execution
|
195 |
of this LU are fulfilled. It can do internode communication, but
|
196 |
it should be idempotent - no cluster or system changes are
|
197 |
allowed.
|
198 |
|
199 |
The method should raise errors.OpPrereqError in case something is
|
200 |
not fulfilled. Its return value is ignored.
|
201 |
|
202 |
This method should also update all the parameters of the opcode to
|
203 |
their canonical form if it hasn't been done by ExpandNames before.
|
204 |
|
205 |
"""
|
206 |
raise NotImplementedError |
207 |
|
208 |
def Exec(self, feedback_fn): |
209 |
"""Execute the LU.
|
210 |
|
211 |
This method should implement the actual work. It should raise
|
212 |
errors.OpExecError for failures that are somewhat dealt with in
|
213 |
code, or expected.
|
214 |
|
215 |
"""
|
216 |
raise NotImplementedError |
217 |
|
218 |
def BuildHooksEnv(self): |
219 |
"""Build hooks environment for this LU.
|
220 |
|
221 |
This method should return a three-node tuple consisting of: a dict
|
222 |
containing the environment that will be used for running the
|
223 |
specific hook for this LU, a list of node names on which the hook
|
224 |
should run before the execution, and a list of node names on which
|
225 |
the hook should run after the execution.
|
226 |
|
227 |
The keys of the dict must not have 'GANETI_' prefixed as this will
|
228 |
be handled in the hooks runner. Also note additional keys will be
|
229 |
added by the hooks runner. If the LU doesn't define any
|
230 |
environment, an empty dict (and not None) should be returned.
|
231 |
|
232 |
No nodes should be returned as an empty list (and not None).
|
233 |
|
234 |
Note that if the HPATH for a LU class is None, this function will
|
235 |
not be called.
|
236 |
|
237 |
"""
|
238 |
raise NotImplementedError |
239 |
|
240 |
def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result): |
241 |
"""Notify the LU about the results of its hooks.
|
242 |
|
243 |
This method is called every time a hooks phase is executed, and notifies
|
244 |
the Logical Unit about the hooks' result. The LU can then use it to alter
|
245 |
its result based on the hooks. By default the method does nothing and the
|
246 |
previous result is passed back unchanged but any LU can define it if it
|
247 |
wants to use the local cluster hook-scripts somehow.
|
248 |
|
249 |
@param phase: one of L{constants.HOOKS_PHASE_POST} or
|
250 |
L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
|
251 |
@param hook_results: the results of the multi-node hooks rpc call
|
252 |
@param feedback_fn: function used send feedback back to the caller
|
253 |
@param lu_result: the previous Exec result this LU had, or None
|
254 |
in the PRE phase
|
255 |
@return: the new Exec result, based on the previous result
|
256 |
and hook results
|
257 |
|
258 |
"""
|
259 |
return lu_result
|
260 |
|
261 |
def _ExpandAndLockInstance(self): |
262 |
"""Helper function to expand and lock an instance.
|
263 |
|
264 |
Many LUs that work on an instance take its name in self.op.instance_name
|
265 |
and need to expand it and then declare the expanded name for locking. This
|
266 |
function does it, and then updates self.op.instance_name to the expanded
|
267 |
name. It also initializes needed_locks as a dict, if this hasn't been done
|
268 |
before.
|
269 |
|
270 |
"""
|
271 |
if self.needed_locks is None: |
272 |
self.needed_locks = {}
|
273 |
else:
|
274 |
assert locking.LEVEL_INSTANCE not in self.needed_locks, \ |
275 |
"_ExpandAndLockInstance called with instance-level locks set"
|
276 |
expanded_name = self.cfg.ExpandInstanceName(self.op.instance_name) |
277 |
if expanded_name is None: |
278 |
raise errors.OpPrereqError("Instance '%s' not known" % |
279 |
self.op.instance_name)
|
280 |
self.needed_locks[locking.LEVEL_INSTANCE] = expanded_name
|
281 |
self.op.instance_name = expanded_name
|
282 |
|
283 |
def _LockInstancesNodes(self, primary_only=False): |
284 |
"""Helper function to declare instances' nodes for locking.
|
285 |
|
286 |
This function should be called after locking one or more instances to lock
|
287 |
their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
|
288 |
with all primary or secondary nodes for instances already locked and
|
289 |
present in self.needed_locks[locking.LEVEL_INSTANCE].
|
290 |
|
291 |
It should be called from DeclareLocks, and for safety only works if
|
292 |
self.recalculate_locks[locking.LEVEL_NODE] is set.
|
293 |
|
294 |
In the future it may grow parameters to just lock some instance's nodes, or
|
295 |
to just lock primaries or secondary nodes, if needed.
|
296 |
|
297 |
If should be called in DeclareLocks in a way similar to::
|
298 |
|
299 |
if level == locking.LEVEL_NODE:
|
300 |
self._LockInstancesNodes()
|
301 |
|
302 |
@type primary_only: boolean
|
303 |
@param primary_only: only lock primary nodes of locked instances
|
304 |
|
305 |
"""
|
306 |
assert locking.LEVEL_NODE in self.recalculate_locks, \ |
307 |
"_LockInstancesNodes helper function called with no nodes to recalculate"
|
308 |
|
309 |
# TODO: check if we're really been called with the instance locks held
|
310 |
|
311 |
# For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
|
312 |
# future we might want to have different behaviors depending on the value
|
313 |
# of self.recalculate_locks[locking.LEVEL_NODE]
|
314 |
wanted_nodes = [] |
315 |
for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]: |
316 |
instance = self.context.cfg.GetInstanceInfo(instance_name)
|
317 |
wanted_nodes.append(instance.primary_node) |
318 |
if not primary_only: |
319 |
wanted_nodes.extend(instance.secondary_nodes) |
320 |
|
321 |
if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE: |
322 |
self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
|
323 |
elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND: |
324 |
self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
|
325 |
|
326 |
del self.recalculate_locks[locking.LEVEL_NODE] |
327 |
|
328 |
|
329 |
class NoHooksLU(LogicalUnit): |
330 |
"""Simple LU which runs no hooks.
|
331 |
|
332 |
This LU is intended as a parent for other LogicalUnits which will
|
333 |
run no hooks, in order to reduce duplicate code.
|
334 |
|
335 |
"""
|
336 |
HPATH = None
|
337 |
HTYPE = None
|
338 |
|
339 |
|
340 |
def _GetWantedNodes(lu, nodes): |
341 |
"""Returns list of checked and expanded node names.
|
342 |
|
343 |
@type lu: L{LogicalUnit}
|
344 |
@param lu: the logical unit on whose behalf we execute
|
345 |
@type nodes: list
|
346 |
@param nodes: list of node names or None for all nodes
|
347 |
@rtype: list
|
348 |
@return: the list of nodes, sorted
|
349 |
@raise errors.OpProgrammerError: if the nodes parameter is wrong type
|
350 |
|
351 |
"""
|
352 |
if not isinstance(nodes, list): |
353 |
raise errors.OpPrereqError("Invalid argument type 'nodes'") |
354 |
|
355 |
if not nodes: |
356 |
raise errors.ProgrammerError("_GetWantedNodes should only be called with a" |
357 |
" non-empty list of nodes whose name is to be expanded.")
|
358 |
|
359 |
wanted = [] |
360 |
for name in nodes: |
361 |
node = lu.cfg.ExpandNodeName(name) |
362 |
if node is None: |
363 |
raise errors.OpPrereqError("No such node name '%s'" % name) |
364 |
wanted.append(node) |
365 |
|
366 |
return utils.NiceSort(wanted)
|
367 |
|
368 |
|
369 |
def _GetWantedInstances(lu, instances): |
370 |
"""Returns list of checked and expanded instance names.
|
371 |
|
372 |
@type lu: L{LogicalUnit}
|
373 |
@param lu: the logical unit on whose behalf we execute
|
374 |
@type instances: list
|
375 |
@param instances: list of instance names or None for all instances
|
376 |
@rtype: list
|
377 |
@return: the list of instances, sorted
|
378 |
@raise errors.OpPrereqError: if the instances parameter is wrong type
|
379 |
@raise errors.OpPrereqError: if any of the passed instances is not found
|
380 |
|
381 |
"""
|
382 |
if not isinstance(instances, list): |
383 |
raise errors.OpPrereqError("Invalid argument type 'instances'") |
384 |
|
385 |
if instances:
|
386 |
wanted = [] |
387 |
|
388 |
for name in instances: |
389 |
instance = lu.cfg.ExpandInstanceName(name) |
390 |
if instance is None: |
391 |
raise errors.OpPrereqError("No such instance name '%s'" % name) |
392 |
wanted.append(instance) |
393 |
|
394 |
else:
|
395 |
wanted = lu.cfg.GetInstanceList() |
396 |
return utils.NiceSort(wanted)
|
397 |
|
398 |
|
399 |
def _CheckOutputFields(static, dynamic, selected): |
400 |
"""Checks whether all selected fields are valid.
|
401 |
|
402 |
@type static: L{utils.FieldSet}
|
403 |
@param static: static fields set
|
404 |
@type dynamic: L{utils.FieldSet}
|
405 |
@param dynamic: dynamic fields set
|
406 |
|
407 |
"""
|
408 |
f = utils.FieldSet() |
409 |
f.Extend(static) |
410 |
f.Extend(dynamic) |
411 |
|
412 |
delta = f.NonMatching(selected) |
413 |
if delta:
|
414 |
raise errors.OpPrereqError("Unknown output fields selected: %s" |
415 |
% ",".join(delta))
|
416 |
|
417 |
|
418 |
def _CheckBooleanOpField(op, name): |
419 |
"""Validates boolean opcode parameters.
|
420 |
|
421 |
This will ensure that an opcode parameter is either a boolean value,
|
422 |
or None (but that it always exists).
|
423 |
|
424 |
"""
|
425 |
val = getattr(op, name, None) |
426 |
if not (val is None or isinstance(val, bool)): |
427 |
raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" % |
428 |
(name, str(val)))
|
429 |
setattr(op, name, val)
|
430 |
|
431 |
|
432 |
def _CheckNodeOnline(lu, node): |
433 |
"""Ensure that a given node is online.
|
434 |
|
435 |
@param lu: the LU on behalf of which we make the check
|
436 |
@param node: the node to check
|
437 |
@raise errors.OpPrereqError: if the nodes is offline
|
438 |
|
439 |
"""
|
440 |
if lu.cfg.GetNodeInfo(node).offline:
|
441 |
raise errors.OpPrereqError("Can't use offline node %s" % node) |
442 |
|
443 |
|
444 |
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status, |
445 |
memory, vcpus, nics): |
446 |
"""Builds instance related env variables for hooks
|
447 |
|
448 |
This builds the hook environment from individual variables.
|
449 |
|
450 |
@type name: string
|
451 |
@param name: the name of the instance
|
452 |
@type primary_node: string
|
453 |
@param primary_node: the name of the instance's primary node
|
454 |
@type secondary_nodes: list
|
455 |
@param secondary_nodes: list of secondary nodes as strings
|
456 |
@type os_type: string
|
457 |
@param os_type: the name of the instance's OS
|
458 |
@type status: string
|
459 |
@param status: the desired status of the instances
|
460 |
@type memory: string
|
461 |
@param memory: the memory size of the instance
|
462 |
@type vcpus: string
|
463 |
@param vcpus: the count of VCPUs the instance has
|
464 |
@type nics: list
|
465 |
@param nics: list of tuples (ip, bridge, mac) representing
|
466 |
the NICs the instance has
|
467 |
@rtype: dict
|
468 |
@return: the hook environment for this instance
|
469 |
|
470 |
"""
|
471 |
env = { |
472 |
"OP_TARGET": name,
|
473 |
"INSTANCE_NAME": name,
|
474 |
"INSTANCE_PRIMARY": primary_node,
|
475 |
"INSTANCE_SECONDARIES": " ".join(secondary_nodes), |
476 |
"INSTANCE_OS_TYPE": os_type,
|
477 |
"INSTANCE_STATUS": status,
|
478 |
"INSTANCE_MEMORY": memory,
|
479 |
"INSTANCE_VCPUS": vcpus,
|
480 |
} |
481 |
|
482 |
if nics:
|
483 |
nic_count = len(nics)
|
484 |
for idx, (ip, bridge, mac) in enumerate(nics): |
485 |
if ip is None: |
486 |
ip = ""
|
487 |
env["INSTANCE_NIC%d_IP" % idx] = ip
|
488 |
env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
|
489 |
env["INSTANCE_NIC%d_HWADDR" % idx] = mac
|
490 |
else:
|
491 |
nic_count = 0
|
492 |
|
493 |
env["INSTANCE_NIC_COUNT"] = nic_count
|
494 |
|
495 |
return env
|
496 |
|
497 |
|
498 |
def _BuildInstanceHookEnvByObject(lu, instance, override=None): |
499 |
"""Builds instance related env variables for hooks from an object.
|
500 |
|
501 |
@type lu: L{LogicalUnit}
|
502 |
@param lu: the logical unit on whose behalf we execute
|
503 |
@type instance: L{objects.Instance}
|
504 |
@param instance: the instance for which we should build the
|
505 |
environment
|
506 |
@type override: dict
|
507 |
@param override: dictionary with key/values that will override
|
508 |
our values
|
509 |
@rtype: dict
|
510 |
@return: the hook environment dictionary
|
511 |
|
512 |
"""
|
513 |
bep = lu.cfg.GetClusterInfo().FillBE(instance) |
514 |
args = { |
515 |
'name': instance.name,
|
516 |
'primary_node': instance.primary_node,
|
517 |
'secondary_nodes': instance.secondary_nodes,
|
518 |
'os_type': instance.os,
|
519 |
'status': instance.os,
|
520 |
'memory': bep[constants.BE_MEMORY],
|
521 |
'vcpus': bep[constants.BE_VCPUS],
|
522 |
'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics], |
523 |
} |
524 |
if override:
|
525 |
args.update(override) |
526 |
return _BuildInstanceHookEnv(**args)
|
527 |
|
528 |
|
529 |
def _AdjustCandidatePool(lu): |
530 |
"""Adjust the candidate pool after node operations.
|
531 |
|
532 |
"""
|
533 |
mod_list = lu.cfg.MaintainCandidatePool() |
534 |
if mod_list:
|
535 |
lu.LogInfo("Promoted nodes to master candidate role: %s",
|
536 |
", ".join(mod_list))
|
537 |
for name in mod_list: |
538 |
lu.context.ReaddNode(name) |
539 |
mc_now, mc_max = lu.cfg.GetMasterCandidateStats() |
540 |
if mc_now > mc_max:
|
541 |
lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
|
542 |
(mc_now, mc_max)) |
543 |
|
544 |
|
545 |
def _CheckInstanceBridgesExist(lu, instance): |
546 |
"""Check that the brigdes needed by an instance exist.
|
547 |
|
548 |
"""
|
549 |
# check bridges existance
|
550 |
brlist = [nic.bridge for nic in instance.nics] |
551 |
result = lu.rpc.call_bridges_exist(instance.primary_node, brlist) |
552 |
result.Raise() |
553 |
if not result.data: |
554 |
raise errors.OpPrereqError("One or more target bridges %s does not" |
555 |
" exist on destination node '%s'" %
|
556 |
(brlist, instance.primary_node)) |
557 |
|
558 |
|
559 |
class LUDestroyCluster(NoHooksLU): |
560 |
"""Logical unit for destroying the cluster.
|
561 |
|
562 |
"""
|
563 |
_OP_REQP = [] |
564 |
|
565 |
def CheckPrereq(self): |
566 |
"""Check prerequisites.
|
567 |
|
568 |
This checks whether the cluster is empty.
|
569 |
|
570 |
Any errors are signalled by raising errors.OpPrereqError.
|
571 |
|
572 |
"""
|
573 |
master = self.cfg.GetMasterNode()
|
574 |
|
575 |
nodelist = self.cfg.GetNodeList()
|
576 |
if len(nodelist) != 1 or nodelist[0] != master: |
577 |
raise errors.OpPrereqError("There are still %d node(s) in" |
578 |
" this cluster." % (len(nodelist) - 1)) |
579 |
instancelist = self.cfg.GetInstanceList()
|
580 |
if instancelist:
|
581 |
raise errors.OpPrereqError("There are still %d instance(s) in" |
582 |
" this cluster." % len(instancelist)) |
583 |
|
584 |
def Exec(self, feedback_fn): |
585 |
"""Destroys the cluster.
|
586 |
|
587 |
"""
|
588 |
master = self.cfg.GetMasterNode()
|
589 |
result = self.rpc.call_node_stop_master(master, False) |
590 |
result.Raise() |
591 |
if not result.data: |
592 |
raise errors.OpExecError("Could not disable the master role") |
593 |
priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS) |
594 |
utils.CreateBackup(priv_key) |
595 |
utils.CreateBackup(pub_key) |
596 |
return master
|
597 |
|
598 |
|
599 |
class LUVerifyCluster(LogicalUnit): |
600 |
"""Verifies the cluster status.
|
601 |
|
602 |
"""
|
603 |
HPATH = "cluster-verify"
|
604 |
HTYPE = constants.HTYPE_CLUSTER |
605 |
_OP_REQP = ["skip_checks"]
|
606 |
REQ_BGL = False
|
607 |
|
608 |
def ExpandNames(self): |
609 |
self.needed_locks = {
|
610 |
locking.LEVEL_NODE: locking.ALL_SET, |
611 |
locking.LEVEL_INSTANCE: locking.ALL_SET, |
612 |
} |
613 |
self.share_locks = dict(((i, 1) for i in locking.LEVELS)) |
614 |
|
615 |
def _VerifyNode(self, nodeinfo, file_list, local_cksum, |
616 |
node_result, feedback_fn, master_files): |
617 |
"""Run multiple tests against a node.
|
618 |
|
619 |
Test list:
|
620 |
|
621 |
- compares ganeti version
|
622 |
- checks vg existance and size > 20G
|
623 |
- checks config file checksum
|
624 |
- checks ssh to other nodes
|
625 |
|
626 |
@type nodeinfo: L{objects.Node}
|
627 |
@param nodeinfo: the node to check
|
628 |
@param file_list: required list of files
|
629 |
@param local_cksum: dictionary of local files and their checksums
|
630 |
@param node_result: the results from the node
|
631 |
@param feedback_fn: function used to accumulate results
|
632 |
@param master_files: list of files that only masters should have
|
633 |
|
634 |
"""
|
635 |
node = nodeinfo.name |
636 |
|
637 |
# main result, node_result should be a non-empty dict
|
638 |
if not node_result or not isinstance(node_result, dict): |
639 |
feedback_fn(" - ERROR: unable to verify node %s." % (node,))
|
640 |
return True |
641 |
|
642 |
# compares ganeti version
|
643 |
local_version = constants.PROTOCOL_VERSION |
644 |
remote_version = node_result.get('version', None) |
645 |
if not remote_version: |
646 |
feedback_fn(" - ERROR: connection to %s failed" % (node))
|
647 |
return True |
648 |
|
649 |
if local_version != remote_version:
|
650 |
feedback_fn(" - ERROR: sw version mismatch: master %s, node(%s) %s" %
|
651 |
(local_version, node, remote_version)) |
652 |
return True |
653 |
|
654 |
# checks vg existance and size > 20G
|
655 |
|
656 |
bad = False
|
657 |
vglist = node_result.get(constants.NV_VGLIST, None)
|
658 |
if not vglist: |
659 |
feedback_fn(" - ERROR: unable to check volume groups on node %s." %
|
660 |
(node,)) |
661 |
bad = True
|
662 |
else:
|
663 |
vgstatus = utils.CheckVolumeGroupSize(vglist, self.cfg.GetVGName(),
|
664 |
constants.MIN_VG_SIZE) |
665 |
if vgstatus:
|
666 |
feedback_fn(" - ERROR: %s on node %s" % (vgstatus, node))
|
667 |
bad = True
|
668 |
|
669 |
# checks config file checksum
|
670 |
|
671 |
remote_cksum = node_result.get(constants.NV_FILELIST, None)
|
672 |
if not isinstance(remote_cksum, dict): |
673 |
bad = True
|
674 |
feedback_fn(" - ERROR: node hasn't returned file checksum data")
|
675 |
else:
|
676 |
for file_name in file_list: |
677 |
node_is_mc = nodeinfo.master_candidate |
678 |
must_have_file = file_name not in master_files |
679 |
if file_name not in remote_cksum: |
680 |
if node_is_mc or must_have_file: |
681 |
bad = True
|
682 |
feedback_fn(" - ERROR: file '%s' missing" % file_name)
|
683 |
elif remote_cksum[file_name] != local_cksum[file_name]:
|
684 |
if node_is_mc or must_have_file: |
685 |
bad = True
|
686 |
feedback_fn(" - ERROR: file '%s' has wrong checksum" % file_name)
|
687 |
else:
|
688 |
# not candidate and this is not a must-have file
|
689 |
bad = True
|
690 |
feedback_fn(" - ERROR: non master-candidate has old/wrong file"
|
691 |
" '%s'" % file_name)
|
692 |
else:
|
693 |
# all good, except non-master/non-must have combination
|
694 |
if not node_is_mc and not must_have_file: |
695 |
feedback_fn(" - ERROR: file '%s' should not exist on non master"
|
696 |
" candidates" % file_name)
|
697 |
|
698 |
# checks ssh to any
|
699 |
|
700 |
if constants.NV_NODELIST not in node_result: |
701 |
bad = True
|
702 |
feedback_fn(" - ERROR: node hasn't returned node ssh connectivity data")
|
703 |
else:
|
704 |
if node_result[constants.NV_NODELIST]:
|
705 |
bad = True
|
706 |
for node in node_result[constants.NV_NODELIST]: |
707 |
feedback_fn(" - ERROR: ssh communication with node '%s': %s" %
|
708 |
(node, node_result[constants.NV_NODELIST][node])) |
709 |
|
710 |
if constants.NV_NODENETTEST not in node_result: |
711 |
bad = True
|
712 |
feedback_fn(" - ERROR: node hasn't returned node tcp connectivity data")
|
713 |
else:
|
714 |
if node_result[constants.NV_NODENETTEST]:
|
715 |
bad = True
|
716 |
nlist = utils.NiceSort(node_result[constants.NV_NODENETTEST].keys()) |
717 |
for node in nlist: |
718 |
feedback_fn(" - ERROR: tcp communication with node '%s': %s" %
|
719 |
(node, node_result[constants.NV_NODENETTEST][node])) |
720 |
|
721 |
hyp_result = node_result.get(constants.NV_HYPERVISOR, None)
|
722 |
if isinstance(hyp_result, dict): |
723 |
for hv_name, hv_result in hyp_result.iteritems(): |
724 |
if hv_result is not None: |
725 |
feedback_fn(" - ERROR: hypervisor %s verify failure: '%s'" %
|
726 |
(hv_name, hv_result)) |
727 |
return bad
|
728 |
|
729 |
def _VerifyInstance(self, instance, instanceconfig, node_vol_is, |
730 |
node_instance, feedback_fn, n_offline): |
731 |
"""Verify an instance.
|
732 |
|
733 |
This function checks to see if the required block devices are
|
734 |
available on the instance's node.
|
735 |
|
736 |
"""
|
737 |
bad = False
|
738 |
|
739 |
node_current = instanceconfig.primary_node |
740 |
|
741 |
node_vol_should = {} |
742 |
instanceconfig.MapLVsByNode(node_vol_should) |
743 |
|
744 |
for node in node_vol_should: |
745 |
if node in n_offline: |
746 |
# ignore missing volumes on offline nodes
|
747 |
continue
|
748 |
for volume in node_vol_should[node]: |
749 |
if node not in node_vol_is or volume not in node_vol_is[node]: |
750 |
feedback_fn(" - ERROR: volume %s missing on node %s" %
|
751 |
(volume, node)) |
752 |
bad = True
|
753 |
|
754 |
if not instanceconfig.status == 'down': |
755 |
if ((node_current not in node_instance or |
756 |
not instance in node_instance[node_current]) and |
757 |
node_current not in n_offline): |
758 |
feedback_fn(" - ERROR: instance %s not running on node %s" %
|
759 |
(instance, node_current)) |
760 |
bad = True
|
761 |
|
762 |
for node in node_instance: |
763 |
if (not node == node_current): |
764 |
if instance in node_instance[node]: |
765 |
feedback_fn(" - ERROR: instance %s should not run on node %s" %
|
766 |
(instance, node)) |
767 |
bad = True
|
768 |
|
769 |
return bad
|
770 |
|
771 |
def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn): |
772 |
"""Verify if there are any unknown volumes in the cluster.
|
773 |
|
774 |
The .os, .swap and backup volumes are ignored. All other volumes are
|
775 |
reported as unknown.
|
776 |
|
777 |
"""
|
778 |
bad = False
|
779 |
|
780 |
for node in node_vol_is: |
781 |
for volume in node_vol_is[node]: |
782 |
if node not in node_vol_should or volume not in node_vol_should[node]: |
783 |
feedback_fn(" - ERROR: volume %s on node %s should not exist" %
|
784 |
(volume, node)) |
785 |
bad = True
|
786 |
return bad
|
787 |
|
788 |
def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn): |
789 |
"""Verify the list of running instances.
|
790 |
|
791 |
This checks what instances are running but unknown to the cluster.
|
792 |
|
793 |
"""
|
794 |
bad = False
|
795 |
for node in node_instance: |
796 |
for runninginstance in node_instance[node]: |
797 |
if runninginstance not in instancelist: |
798 |
feedback_fn(" - ERROR: instance %s on node %s should not exist" %
|
799 |
(runninginstance, node)) |
800 |
bad = True
|
801 |
return bad
|
802 |
|
803 |
def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn): |
804 |
"""Verify N+1 Memory Resilience.
|
805 |
|
806 |
Check that if one single node dies we can still start all the instances it
|
807 |
was primary for.
|
808 |
|
809 |
"""
|
810 |
bad = False
|
811 |
|
812 |
for node, nodeinfo in node_info.iteritems(): |
813 |
# This code checks that every node which is now listed as secondary has
|
814 |
# enough memory to host all instances it is supposed to should a single
|
815 |
# other node in the cluster fail.
|
816 |
# FIXME: not ready for failover to an arbitrary node
|
817 |
# FIXME: does not support file-backed instances
|
818 |
# WARNING: we currently take into account down instances as well as up
|
819 |
# ones, considering that even if they're down someone might want to start
|
820 |
# them even in the event of a node failure.
|
821 |
for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems(): |
822 |
needed_mem = 0
|
823 |
for instance in instances: |
824 |
bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
|
825 |
if bep[constants.BE_AUTO_BALANCE]:
|
826 |
needed_mem += bep[constants.BE_MEMORY] |
827 |
if nodeinfo['mfree'] < needed_mem: |
828 |
feedback_fn(" - ERROR: not enough memory on node %s to accomodate"
|
829 |
" failovers should node %s fail" % (node, prinode))
|
830 |
bad = True
|
831 |
return bad
|
832 |
|
833 |
def CheckPrereq(self): |
834 |
"""Check prerequisites.
|
835 |
|
836 |
Transform the list of checks we're going to skip into a set and check that
|
837 |
all its members are valid.
|
838 |
|
839 |
"""
|
840 |
self.skip_set = frozenset(self.op.skip_checks) |
841 |
if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set): |
842 |
raise errors.OpPrereqError("Invalid checks to be skipped specified") |
843 |
|
844 |
def BuildHooksEnv(self): |
845 |
"""Build hooks env.
|
846 |
|
847 |
Cluster-Verify hooks just rone in the post phase and their failure makes
|
848 |
the output be logged in the verify output and the verification to fail.
|
849 |
|
850 |
"""
|
851 |
all_nodes = self.cfg.GetNodeList()
|
852 |
# TODO: populate the environment with useful information for verify hooks
|
853 |
env = {} |
854 |
return env, [], all_nodes
|
855 |
|
856 |
def Exec(self, feedback_fn): |
857 |
"""Verify integrity of cluster, performing various test on nodes.
|
858 |
|
859 |
"""
|
860 |
bad = False
|
861 |
feedback_fn("* Verifying global settings")
|
862 |
for msg in self.cfg.VerifyConfig(): |
863 |
feedback_fn(" - ERROR: %s" % msg)
|
864 |
|
865 |
vg_name = self.cfg.GetVGName()
|
866 |
hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
|
867 |
nodelist = utils.NiceSort(self.cfg.GetNodeList())
|
868 |
nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist] |
869 |
instancelist = utils.NiceSort(self.cfg.GetInstanceList())
|
870 |
i_non_redundant = [] # Non redundant instances
|
871 |
i_non_a_balanced = [] # Non auto-balanced instances
|
872 |
n_offline = [] # List of offline nodes
|
873 |
node_volume = {} |
874 |
node_instance = {} |
875 |
node_info = {} |
876 |
instance_cfg = {} |
877 |
|
878 |
# FIXME: verify OS list
|
879 |
# do local checksums
|
880 |
master_files = [constants.CLUSTER_CONF_FILE] |
881 |
|
882 |
file_names = ssconf.SimpleStore().GetFileList() |
883 |
file_names.append(constants.SSL_CERT_FILE) |
884 |
file_names.extend(master_files) |
885 |
|
886 |
local_checksums = utils.FingerprintFiles(file_names) |
887 |
|
888 |
feedback_fn("* Gathering data (%d nodes)" % len(nodelist)) |
889 |
node_verify_param = { |
890 |
constants.NV_FILELIST: file_names, |
891 |
constants.NV_NODELIST: nodelist, |
892 |
constants.NV_HYPERVISOR: hypervisors, |
893 |
constants.NV_NODENETTEST: [(node.name, node.primary_ip, |
894 |
node.secondary_ip) for node in nodeinfo], |
895 |
constants.NV_LVLIST: vg_name, |
896 |
constants.NV_INSTANCELIST: hypervisors, |
897 |
constants.NV_VGLIST: None,
|
898 |
constants.NV_VERSION: None,
|
899 |
constants.NV_HVINFO: self.cfg.GetHypervisorType(),
|
900 |
} |
901 |
all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
|
902 |
self.cfg.GetClusterName())
|
903 |
|
904 |
cluster = self.cfg.GetClusterInfo()
|
905 |
master_node = self.cfg.GetMasterNode()
|
906 |
for node_i in nodeinfo: |
907 |
node = node_i.name |
908 |
nresult = all_nvinfo[node].data |
909 |
|
910 |
if node_i.offline:
|
911 |
feedback_fn("* Skipping offline node %s" % (node,))
|
912 |
n_offline.append(node) |
913 |
continue
|
914 |
|
915 |
if node == master_node:
|
916 |
ntype = "master"
|
917 |
elif node_i.master_candidate:
|
918 |
ntype = "master candidate"
|
919 |
else:
|
920 |
ntype = "regular"
|
921 |
feedback_fn("* Verifying node %s (%s)" % (node, ntype))
|
922 |
|
923 |
if all_nvinfo[node].failed or not isinstance(nresult, dict): |
924 |
feedback_fn(" - ERROR: connection to %s failed" % (node,))
|
925 |
bad = True
|
926 |
continue
|
927 |
|
928 |
result = self._VerifyNode(node_i, file_names, local_checksums,
|
929 |
nresult, feedback_fn, master_files) |
930 |
bad = bad or result
|
931 |
|
932 |
lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
|
933 |
if isinstance(lvdata, basestring): |
934 |
feedback_fn(" - ERROR: LVM problem on node %s: %s" %
|
935 |
(node, lvdata.encode('string_escape')))
|
936 |
bad = True
|
937 |
node_volume[node] = {} |
938 |
elif not isinstance(lvdata, dict): |
939 |
feedback_fn(" - ERROR: connection to %s failed (lvlist)" % (node,))
|
940 |
bad = True
|
941 |
continue
|
942 |
else:
|
943 |
node_volume[node] = lvdata |
944 |
|
945 |
# node_instance
|
946 |
idata = nresult.get(constants.NV_INSTANCELIST, None)
|
947 |
if not isinstance(idata, list): |
948 |
feedback_fn(" - ERROR: connection to %s failed (instancelist)" %
|
949 |
(node,)) |
950 |
bad = True
|
951 |
continue
|
952 |
|
953 |
node_instance[node] = idata |
954 |
|
955 |
# node_info
|
956 |
nodeinfo = nresult.get(constants.NV_HVINFO, None)
|
957 |
if not isinstance(nodeinfo, dict): |
958 |
feedback_fn(" - ERROR: connection to %s failed (hvinfo)" % (node,))
|
959 |
bad = True
|
960 |
continue
|
961 |
|
962 |
try:
|
963 |
node_info[node] = { |
964 |
"mfree": int(nodeinfo['memory_free']), |
965 |
"dfree": int(nresult[constants.NV_VGLIST][vg_name]), |
966 |
"pinst": [],
|
967 |
"sinst": [],
|
968 |
# dictionary holding all instances this node is secondary for,
|
969 |
# grouped by their primary node. Each key is a cluster node, and each
|
970 |
# value is a list of instances which have the key as primary and the
|
971 |
# current node as secondary. this is handy to calculate N+1 memory
|
972 |
# availability if you can only failover from a primary to its
|
973 |
# secondary.
|
974 |
"sinst-by-pnode": {},
|
975 |
} |
976 |
except ValueError: |
977 |
feedback_fn(" - ERROR: invalid value returned from node %s" % (node,))
|
978 |
bad = True
|
979 |
continue
|
980 |
|
981 |
node_vol_should = {} |
982 |
|
983 |
for instance in instancelist: |
984 |
feedback_fn("* Verifying instance %s" % instance)
|
985 |
inst_config = self.cfg.GetInstanceInfo(instance)
|
986 |
result = self._VerifyInstance(instance, inst_config, node_volume,
|
987 |
node_instance, feedback_fn, n_offline) |
988 |
bad = bad or result
|
989 |
|
990 |
inst_config.MapLVsByNode(node_vol_should) |
991 |
|
992 |
instance_cfg[instance] = inst_config |
993 |
|
994 |
pnode = inst_config.primary_node |
995 |
if pnode in node_info: |
996 |
node_info[pnode]['pinst'].append(instance)
|
997 |
elif pnode not in n_offline: |
998 |
feedback_fn(" - ERROR: instance %s, connection to primary node"
|
999 |
" %s failed" % (instance, pnode))
|
1000 |
bad = True
|
1001 |
|
1002 |
# If the instance is non-redundant we cannot survive losing its primary
|
1003 |
# node, so we are not N+1 compliant. On the other hand we have no disk
|
1004 |
# templates with more than one secondary so that situation is not well
|
1005 |
# supported either.
|
1006 |
# FIXME: does not support file-backed instances
|
1007 |
if len(inst_config.secondary_nodes) == 0: |
1008 |
i_non_redundant.append(instance) |
1009 |
elif len(inst_config.secondary_nodes) > 1: |
1010 |
feedback_fn(" - WARNING: multiple secondaries for instance %s"
|
1011 |
% instance) |
1012 |
|
1013 |
if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]: |
1014 |
i_non_a_balanced.append(instance) |
1015 |
|
1016 |
for snode in inst_config.secondary_nodes: |
1017 |
if snode in node_info: |
1018 |
node_info[snode]['sinst'].append(instance)
|
1019 |
if pnode not in node_info[snode]['sinst-by-pnode']: |
1020 |
node_info[snode]['sinst-by-pnode'][pnode] = []
|
1021 |
node_info[snode]['sinst-by-pnode'][pnode].append(instance)
|
1022 |
elif snode not in n_offline: |
1023 |
feedback_fn(" - ERROR: instance %s, connection to secondary node"
|
1024 |
" %s failed" % (instance, snode))
|
1025 |
|
1026 |
feedback_fn("* Verifying orphan volumes")
|
1027 |
result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
|
1028 |
feedback_fn) |
1029 |
bad = bad or result
|
1030 |
|
1031 |
feedback_fn("* Verifying remaining instances")
|
1032 |
result = self._VerifyOrphanInstances(instancelist, node_instance,
|
1033 |
feedback_fn) |
1034 |
bad = bad or result
|
1035 |
|
1036 |
if constants.VERIFY_NPLUSONE_MEM not in self.skip_set: |
1037 |
feedback_fn("* Verifying N+1 Memory redundancy")
|
1038 |
result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
|
1039 |
bad = bad or result
|
1040 |
|
1041 |
feedback_fn("* Other Notes")
|
1042 |
if i_non_redundant:
|
1043 |
feedback_fn(" - NOTICE: %d non-redundant instance(s) found."
|
1044 |
% len(i_non_redundant))
|
1045 |
|
1046 |
if i_non_a_balanced:
|
1047 |
feedback_fn(" - NOTICE: %d non-auto-balanced instance(s) found."
|
1048 |
% len(i_non_a_balanced))
|
1049 |
|
1050 |
if n_offline:
|
1051 |
feedback_fn(" - NOTICE: %d offline node(s) found." % len(n_offline)) |
1052 |
|
1053 |
return not bad |
1054 |
|
1055 |
def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result): |
1056 |
"""Analize the post-hooks' result
|
1057 |
|
1058 |
This method analyses the hook result, handles it, and sends some
|
1059 |
nicely-formatted feedback back to the user.
|
1060 |
|
1061 |
@param phase: one of L{constants.HOOKS_PHASE_POST} or
|
1062 |
L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
|
1063 |
@param hooks_results: the results of the multi-node hooks rpc call
|
1064 |
@param feedback_fn: function used send feedback back to the caller
|
1065 |
@param lu_result: previous Exec result
|
1066 |
@return: the new Exec result, based on the previous result
|
1067 |
and hook results
|
1068 |
|
1069 |
"""
|
1070 |
# We only really run POST phase hooks, and are only interested in
|
1071 |
# their results
|
1072 |
if phase == constants.HOOKS_PHASE_POST:
|
1073 |
# Used to change hooks' output to proper indentation
|
1074 |
indent_re = re.compile('^', re.M)
|
1075 |
feedback_fn("* Hooks Results")
|
1076 |
if not hooks_results: |
1077 |
feedback_fn(" - ERROR: general communication failure")
|
1078 |
lu_result = 1
|
1079 |
else:
|
1080 |
for node_name in hooks_results: |
1081 |
show_node_header = True
|
1082 |
res = hooks_results[node_name] |
1083 |
if res.failed or res.data is False or not isinstance(res.data, list): |
1084 |
if res.offline:
|
1085 |
# no need to warn or set fail return value
|
1086 |
continue
|
1087 |
feedback_fn(" Communication failure in hooks execution")
|
1088 |
lu_result = 1
|
1089 |
continue
|
1090 |
for script, hkr, output in res.data: |
1091 |
if hkr == constants.HKR_FAIL:
|
1092 |
# The node header is only shown once, if there are
|
1093 |
# failing hooks on that node
|
1094 |
if show_node_header:
|
1095 |
feedback_fn(" Node %s:" % node_name)
|
1096 |
show_node_header = False
|
1097 |
feedback_fn(" ERROR: Script %s failed, output:" % script)
|
1098 |
output = indent_re.sub(' ', output)
|
1099 |
feedback_fn("%s" % output)
|
1100 |
lu_result = 1
|
1101 |
|
1102 |
return lu_result
|
1103 |
|
1104 |
|
1105 |
class LUVerifyDisks(NoHooksLU): |
1106 |
"""Verifies the cluster disks status.
|
1107 |
|
1108 |
"""
|
1109 |
_OP_REQP = [] |
1110 |
REQ_BGL = False
|
1111 |
|
1112 |
def ExpandNames(self): |
1113 |
self.needed_locks = {
|
1114 |
locking.LEVEL_NODE: locking.ALL_SET, |
1115 |
locking.LEVEL_INSTANCE: locking.ALL_SET, |
1116 |
} |
1117 |
self.share_locks = dict(((i, 1) for i in locking.LEVELS)) |
1118 |
|
1119 |
def CheckPrereq(self): |
1120 |
"""Check prerequisites.
|
1121 |
|
1122 |
This has no prerequisites.
|
1123 |
|
1124 |
"""
|
1125 |
pass
|
1126 |
|
1127 |
def Exec(self, feedback_fn): |
1128 |
"""Verify integrity of cluster disks.
|
1129 |
|
1130 |
"""
|
1131 |
result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {} |
1132 |
|
1133 |
vg_name = self.cfg.GetVGName()
|
1134 |
nodes = utils.NiceSort(self.cfg.GetNodeList())
|
1135 |
instances = [self.cfg.GetInstanceInfo(name)
|
1136 |
for name in self.cfg.GetInstanceList()] |
1137 |
|
1138 |
nv_dict = {} |
1139 |
for inst in instances: |
1140 |
inst_lvs = {} |
1141 |
if (inst.status != "up" or |
1142 |
inst.disk_template not in constants.DTS_NET_MIRROR): |
1143 |
continue
|
1144 |
inst.MapLVsByNode(inst_lvs) |
1145 |
# transform { iname: {node: [vol,],},} to {(node, vol): iname}
|
1146 |
for node, vol_list in inst_lvs.iteritems(): |
1147 |
for vol in vol_list: |
1148 |
nv_dict[(node, vol)] = inst |
1149 |
|
1150 |
if not nv_dict: |
1151 |
return result
|
1152 |
|
1153 |
node_lvs = self.rpc.call_volume_list(nodes, vg_name)
|
1154 |
|
1155 |
to_act = set()
|
1156 |
for node in nodes: |
1157 |
# node_volume
|
1158 |
lvs = node_lvs[node] |
1159 |
if lvs.failed:
|
1160 |
if not lvs.offline: |
1161 |
self.LogWarning("Connection to node %s failed: %s" % |
1162 |
(node, lvs.data)) |
1163 |
continue
|
1164 |
lvs = lvs.data |
1165 |
if isinstance(lvs, basestring): |
1166 |
logging.warning("Error enumerating LVs on node %s: %s", node, lvs)
|
1167 |
res_nlvm[node] = lvs |
1168 |
elif not isinstance(lvs, dict): |
1169 |
logging.warning("Connection to node %s failed or invalid data"
|
1170 |
" returned", node)
|
1171 |
res_nodes.append(node) |
1172 |
continue
|
1173 |
|
1174 |
for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems(): |
1175 |
inst = nv_dict.pop((node, lv_name), None)
|
1176 |
if (not lv_online and inst is not None |
1177 |
and inst.name not in res_instances): |
1178 |
res_instances.append(inst.name) |
1179 |
|
1180 |
# any leftover items in nv_dict are missing LVs, let's arrange the
|
1181 |
# data better
|
1182 |
for key, inst in nv_dict.iteritems(): |
1183 |
if inst.name not in res_missing: |
1184 |
res_missing[inst.name] = [] |
1185 |
res_missing[inst.name].append(key) |
1186 |
|
1187 |
return result
|
1188 |
|
1189 |
|
1190 |
class LURenameCluster(LogicalUnit): |
1191 |
"""Rename the cluster.
|
1192 |
|
1193 |
"""
|
1194 |
HPATH = "cluster-rename"
|
1195 |
HTYPE = constants.HTYPE_CLUSTER |
1196 |
_OP_REQP = ["name"]
|
1197 |
|
1198 |
def BuildHooksEnv(self): |
1199 |
"""Build hooks env.
|
1200 |
|
1201 |
"""
|
1202 |
env = { |
1203 |
"OP_TARGET": self.cfg.GetClusterName(), |
1204 |
"NEW_NAME": self.op.name, |
1205 |
} |
1206 |
mn = self.cfg.GetMasterNode()
|
1207 |
return env, [mn], [mn]
|
1208 |
|
1209 |
def CheckPrereq(self): |
1210 |
"""Verify that the passed name is a valid one.
|
1211 |
|
1212 |
"""
|
1213 |
hostname = utils.HostInfo(self.op.name)
|
1214 |
|
1215 |
new_name = hostname.name |
1216 |
self.ip = new_ip = hostname.ip
|
1217 |
old_name = self.cfg.GetClusterName()
|
1218 |
old_ip = self.cfg.GetMasterIP()
|
1219 |
if new_name == old_name and new_ip == old_ip: |
1220 |
raise errors.OpPrereqError("Neither the name nor the IP address of the" |
1221 |
" cluster has changed")
|
1222 |
if new_ip != old_ip:
|
1223 |
if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
|
1224 |
raise errors.OpPrereqError("The given cluster IP address (%s) is" |
1225 |
" reachable on the network. Aborting." %
|
1226 |
new_ip) |
1227 |
|
1228 |
self.op.name = new_name
|
1229 |
|
1230 |
def Exec(self, feedback_fn): |
1231 |
"""Rename the cluster.
|
1232 |
|
1233 |
"""
|
1234 |
clustername = self.op.name
|
1235 |
ip = self.ip
|
1236 |
|
1237 |
# shutdown the master IP
|
1238 |
master = self.cfg.GetMasterNode()
|
1239 |
result = self.rpc.call_node_stop_master(master, False) |
1240 |
if result.failed or not result.data: |
1241 |
raise errors.OpExecError("Could not disable the master role") |
1242 |
|
1243 |
try:
|
1244 |
cluster = self.cfg.GetClusterInfo()
|
1245 |
cluster.cluster_name = clustername |
1246 |
cluster.master_ip = ip |
1247 |
self.cfg.Update(cluster)
|
1248 |
|
1249 |
# update the known hosts file
|
1250 |
ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
|
1251 |
node_list = self.cfg.GetNodeList()
|
1252 |
try:
|
1253 |
node_list.remove(master) |
1254 |
except ValueError: |
1255 |
pass
|
1256 |
result = self.rpc.call_upload_file(node_list,
|
1257 |
constants.SSH_KNOWN_HOSTS_FILE) |
1258 |
for to_node, to_result in result.iteritems(): |
1259 |
if to_result.failed or not to_result.data: |
1260 |
logging.error("Copy of file %s to node %s failed", fname, to_node)
|
1261 |
|
1262 |
finally:
|
1263 |
result = self.rpc.call_node_start_master(master, False) |
1264 |
if result.failed or not result.data: |
1265 |
self.LogWarning("Could not re-enable the master role on" |
1266 |
" the master, please restart manually.")
|
1267 |
|
1268 |
|
1269 |
def _RecursiveCheckIfLVMBased(disk): |
1270 |
"""Check if the given disk or its children are lvm-based.
|
1271 |
|
1272 |
@type disk: L{objects.Disk}
|
1273 |
@param disk: the disk to check
|
1274 |
@rtype: booleean
|
1275 |
@return: boolean indicating whether a LD_LV dev_type was found or not
|
1276 |
|
1277 |
"""
|
1278 |
if disk.children:
|
1279 |
for chdisk in disk.children: |
1280 |
if _RecursiveCheckIfLVMBased(chdisk):
|
1281 |
return True |
1282 |
return disk.dev_type == constants.LD_LV
|
1283 |
|
1284 |
|
1285 |
class LUSetClusterParams(LogicalUnit): |
1286 |
"""Change the parameters of the cluster.
|
1287 |
|
1288 |
"""
|
1289 |
HPATH = "cluster-modify"
|
1290 |
HTYPE = constants.HTYPE_CLUSTER |
1291 |
_OP_REQP = [] |
1292 |
REQ_BGL = False
|
1293 |
|
1294 |
def CheckParameters(self): |
1295 |
"""Check parameters
|
1296 |
|
1297 |
"""
|
1298 |
if not hasattr(self.op, "candidate_pool_size"): |
1299 |
self.op.candidate_pool_size = None |
1300 |
if self.op.candidate_pool_size is not None: |
1301 |
try:
|
1302 |
self.op.candidate_pool_size = int(self.op.candidate_pool_size) |
1303 |
except ValueError, err: |
1304 |
raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" % |
1305 |
str(err))
|
1306 |
if self.op.candidate_pool_size < 1: |
1307 |
raise errors.OpPrereqError("At least one master candidate needed") |
1308 |
|
1309 |
def ExpandNames(self): |
1310 |
# FIXME: in the future maybe other cluster params won't require checking on
|
1311 |
# all nodes to be modified.
|
1312 |
self.needed_locks = {
|
1313 |
locking.LEVEL_NODE: locking.ALL_SET, |
1314 |
} |
1315 |
self.share_locks[locking.LEVEL_NODE] = 1 |
1316 |
|
1317 |
def BuildHooksEnv(self): |
1318 |
"""Build hooks env.
|
1319 |
|
1320 |
"""
|
1321 |
env = { |
1322 |
"OP_TARGET": self.cfg.GetClusterName(), |
1323 |
"NEW_VG_NAME": self.op.vg_name, |
1324 |
} |
1325 |
mn = self.cfg.GetMasterNode()
|
1326 |
return env, [mn], [mn]
|
1327 |
|
1328 |
def CheckPrereq(self): |
1329 |
"""Check prerequisites.
|
1330 |
|
1331 |
This checks whether the given params don't conflict and
|
1332 |
if the given volume group is valid.
|
1333 |
|
1334 |
"""
|
1335 |
# FIXME: This only works because there is only one parameter that can be
|
1336 |
# changed or removed.
|
1337 |
if self.op.vg_name is not None and not self.op.vg_name: |
1338 |
instances = self.cfg.GetAllInstancesInfo().values()
|
1339 |
for inst in instances: |
1340 |
for disk in inst.disks: |
1341 |
if _RecursiveCheckIfLVMBased(disk):
|
1342 |
raise errors.OpPrereqError("Cannot disable lvm storage while" |
1343 |
" lvm-based instances exist")
|
1344 |
|
1345 |
node_list = self.acquired_locks[locking.LEVEL_NODE]
|
1346 |
|
1347 |
# if vg_name not None, checks given volume group on all nodes
|
1348 |
if self.op.vg_name: |
1349 |
vglist = self.rpc.call_vg_list(node_list)
|
1350 |
for node in node_list: |
1351 |
if vglist[node].failed:
|
1352 |
# ignoring down node
|
1353 |
self.LogWarning("Node %s unreachable/error, ignoring" % node) |
1354 |
continue
|
1355 |
vgstatus = utils.CheckVolumeGroupSize(vglist[node].data, |
1356 |
self.op.vg_name,
|
1357 |
constants.MIN_VG_SIZE) |
1358 |
if vgstatus:
|
1359 |
raise errors.OpPrereqError("Error on node '%s': %s" % |
1360 |
(node, vgstatus)) |
1361 |
|
1362 |
self.cluster = cluster = self.cfg.GetClusterInfo() |
1363 |
# validate beparams changes
|
1364 |
if self.op.beparams: |
1365 |
utils.CheckBEParams(self.op.beparams)
|
1366 |
self.new_beparams = cluster.FillDict(
|
1367 |
cluster.beparams[constants.BEGR_DEFAULT], self.op.beparams)
|
1368 |
|
1369 |
# hypervisor list/parameters
|
1370 |
self.new_hvparams = cluster.FillDict(cluster.hvparams, {})
|
1371 |
if self.op.hvparams: |
1372 |
if not isinstance(self.op.hvparams, dict): |
1373 |
raise errors.OpPrereqError("Invalid 'hvparams' parameter on input") |
1374 |
for hv_name, hv_dict in self.op.hvparams.items(): |
1375 |
if hv_name not in self.new_hvparams: |
1376 |
self.new_hvparams[hv_name] = hv_dict
|
1377 |
else:
|
1378 |
self.new_hvparams[hv_name].update(hv_dict)
|
1379 |
|
1380 |
if self.op.enabled_hypervisors is not None: |
1381 |
self.hv_list = self.op.enabled_hypervisors |
1382 |
else:
|
1383 |
self.hv_list = cluster.enabled_hypervisors
|
1384 |
|
1385 |
if self.op.hvparams or self.op.enabled_hypervisors is not None: |
1386 |
# either the enabled list has changed, or the parameters have, validate
|
1387 |
for hv_name, hv_params in self.new_hvparams.items(): |
1388 |
if ((self.op.hvparams and hv_name in self.op.hvparams) or |
1389 |
(self.op.enabled_hypervisors and |
1390 |
hv_name in self.op.enabled_hypervisors)): |
1391 |
# either this is a new hypervisor, or its parameters have changed
|
1392 |
hv_class = hypervisor.GetHypervisor(hv_name) |
1393 |
hv_class.CheckParameterSyntax(hv_params) |
1394 |
_CheckHVParams(self, node_list, hv_name, hv_params)
|
1395 |
|
1396 |
def Exec(self, feedback_fn): |
1397 |
"""Change the parameters of the cluster.
|
1398 |
|
1399 |
"""
|
1400 |
if self.op.vg_name is not None: |
1401 |
if self.op.vg_name != self.cfg.GetVGName(): |
1402 |
self.cfg.SetVGName(self.op.vg_name) |
1403 |
else:
|
1404 |
feedback_fn("Cluster LVM configuration already in desired"
|
1405 |
" state, not changing")
|
1406 |
if self.op.hvparams: |
1407 |
self.cluster.hvparams = self.new_hvparams |
1408 |
if self.op.enabled_hypervisors is not None: |
1409 |
self.cluster.enabled_hypervisors = self.op.enabled_hypervisors |
1410 |
if self.op.beparams: |
1411 |
self.cluster.beparams[constants.BEGR_DEFAULT] = self.new_beparams |
1412 |
if self.op.candidate_pool_size is not None: |
1413 |
self.cluster.candidate_pool_size = self.op.candidate_pool_size |
1414 |
|
1415 |
self.cfg.Update(self.cluster) |
1416 |
|
1417 |
# we want to update nodes after the cluster so that if any errors
|
1418 |
# happen, we have recorded and saved the cluster info
|
1419 |
if self.op.candidate_pool_size is not None: |
1420 |
_AdjustCandidatePool(self)
|
1421 |
|
1422 |
|
1423 |
def _WaitForSync(lu, instance, oneshot=False, unlock=False): |
1424 |
"""Sleep and poll for an instance's disk to sync.
|
1425 |
|
1426 |
"""
|
1427 |
if not instance.disks: |
1428 |
return True |
1429 |
|
1430 |
if not oneshot: |
1431 |
lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
|
1432 |
|
1433 |
node = instance.primary_node |
1434 |
|
1435 |
for dev in instance.disks: |
1436 |
lu.cfg.SetDiskID(dev, node) |
1437 |
|
1438 |
retries = 0
|
1439 |
while True: |
1440 |
max_time = 0
|
1441 |
done = True
|
1442 |
cumul_degraded = False
|
1443 |
rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks) |
1444 |
if rstats.failed or not rstats.data: |
1445 |
lu.LogWarning("Can't get any data from node %s", node)
|
1446 |
retries += 1
|
1447 |
if retries >= 10: |
1448 |
raise errors.RemoteError("Can't contact node %s for mirror data," |
1449 |
" aborting." % node)
|
1450 |
time.sleep(6)
|
1451 |
continue
|
1452 |
rstats = rstats.data |
1453 |
retries = 0
|
1454 |
for i in range(len(rstats)): |
1455 |
mstat = rstats[i] |
1456 |
if mstat is None: |
1457 |
lu.LogWarning("Can't compute data for node %s/%s",
|
1458 |
node, instance.disks[i].iv_name) |
1459 |
continue
|
1460 |
# we ignore the ldisk parameter
|
1461 |
perc_done, est_time, is_degraded, _ = mstat |
1462 |
cumul_degraded = cumul_degraded or (is_degraded and perc_done is None) |
1463 |
if perc_done is not None: |
1464 |
done = False
|
1465 |
if est_time is not None: |
1466 |
rem_time = "%d estimated seconds remaining" % est_time
|
1467 |
max_time = est_time |
1468 |
else:
|
1469 |
rem_time = "no time estimate"
|
1470 |
lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
|
1471 |
(instance.disks[i].iv_name, perc_done, rem_time)) |
1472 |
if done or oneshot: |
1473 |
break
|
1474 |
|
1475 |
time.sleep(min(60, max_time)) |
1476 |
|
1477 |
if done:
|
1478 |
lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
|
1479 |
return not cumul_degraded |
1480 |
|
1481 |
|
1482 |
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False): |
1483 |
"""Check that mirrors are not degraded.
|
1484 |
|
1485 |
The ldisk parameter, if True, will change the test from the
|
1486 |
is_degraded attribute (which represents overall non-ok status for
|
1487 |
the device(s)) to the ldisk (representing the local storage status).
|
1488 |
|
1489 |
"""
|
1490 |
lu.cfg.SetDiskID(dev, node) |
1491 |
if ldisk:
|
1492 |
idx = 6
|
1493 |
else:
|
1494 |
idx = 5
|
1495 |
|
1496 |
result = True
|
1497 |
if on_primary or dev.AssembleOnSecondary(): |
1498 |
rstats = lu.rpc.call_blockdev_find(node, dev) |
1499 |
if rstats.failed or not rstats.data: |
1500 |
logging.warning("Node %s: disk degraded, not found or node down", node)
|
1501 |
result = False
|
1502 |
else:
|
1503 |
result = result and (not rstats.data[idx]) |
1504 |
if dev.children:
|
1505 |
for child in dev.children: |
1506 |
result = result and _CheckDiskConsistency(lu, child, node, on_primary)
|
1507 |
|
1508 |
return result
|
1509 |
|
1510 |
|
1511 |
class LUDiagnoseOS(NoHooksLU): |
1512 |
"""Logical unit for OS diagnose/query.
|
1513 |
|
1514 |
"""
|
1515 |
_OP_REQP = ["output_fields", "names"] |
1516 |
REQ_BGL = False
|
1517 |
_FIELDS_STATIC = utils.FieldSet() |
1518 |
_FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status") |
1519 |
|
1520 |
def ExpandNames(self): |
1521 |
if self.op.names: |
1522 |
raise errors.OpPrereqError("Selective OS query not supported") |
1523 |
|
1524 |
_CheckOutputFields(static=self._FIELDS_STATIC,
|
1525 |
dynamic=self._FIELDS_DYNAMIC,
|
1526 |
selected=self.op.output_fields)
|
1527 |
|
1528 |
# Lock all nodes, in shared mode
|
1529 |
self.needed_locks = {}
|
1530 |
self.share_locks[locking.LEVEL_NODE] = 1 |
1531 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
1532 |
|
1533 |
def CheckPrereq(self): |
1534 |
"""Check prerequisites.
|
1535 |
|
1536 |
"""
|
1537 |
|
1538 |
@staticmethod
|
1539 |
def _DiagnoseByOS(node_list, rlist): |
1540 |
"""Remaps a per-node return list into an a per-os per-node dictionary
|
1541 |
|
1542 |
@param node_list: a list with the names of all nodes
|
1543 |
@param rlist: a map with node names as keys and OS objects as values
|
1544 |
|
1545 |
@rtype: dict
|
1546 |
@returns: a dictionary with osnames as keys and as value another map, with
|
1547 |
nodes as keys and list of OS objects as values, eg::
|
1548 |
|
1549 |
{"debian-etch": {"node1": [<object>,...],
|
1550 |
"node2": [<object>,]}
|
1551 |
}
|
1552 |
|
1553 |
"""
|
1554 |
all_os = {} |
1555 |
for node_name, nr in rlist.iteritems(): |
1556 |
if nr.failed or not nr.data: |
1557 |
continue
|
1558 |
for os_obj in nr.data: |
1559 |
if os_obj.name not in all_os: |
1560 |
# build a list of nodes for this os containing empty lists
|
1561 |
# for each node in node_list
|
1562 |
all_os[os_obj.name] = {} |
1563 |
for nname in node_list: |
1564 |
all_os[os_obj.name][nname] = [] |
1565 |
all_os[os_obj.name][node_name].append(os_obj) |
1566 |
return all_os
|
1567 |
|
1568 |
def Exec(self, feedback_fn): |
1569 |
"""Compute the list of OSes.
|
1570 |
|
1571 |
"""
|
1572 |
node_list = self.acquired_locks[locking.LEVEL_NODE]
|
1573 |
node_data = self.rpc.call_os_diagnose(node_list)
|
1574 |
if node_data == False: |
1575 |
raise errors.OpExecError("Can't gather the list of OSes") |
1576 |
pol = self._DiagnoseByOS(node_list, node_data)
|
1577 |
output = [] |
1578 |
for os_name, os_data in pol.iteritems(): |
1579 |
row = [] |
1580 |
for field in self.op.output_fields: |
1581 |
if field == "name": |
1582 |
val = os_name |
1583 |
elif field == "valid": |
1584 |
val = utils.all([osl and osl[0] for osl in os_data.values()]) |
1585 |
elif field == "node_status": |
1586 |
val = {} |
1587 |
for node_name, nos_list in os_data.iteritems(): |
1588 |
val[node_name] = [(v.status, v.path) for v in nos_list] |
1589 |
else:
|
1590 |
raise errors.ParameterError(field)
|
1591 |
row.append(val) |
1592 |
output.append(row) |
1593 |
|
1594 |
return output
|
1595 |
|
1596 |
|
1597 |
class LURemoveNode(LogicalUnit): |
1598 |
"""Logical unit for removing a node.
|
1599 |
|
1600 |
"""
|
1601 |
HPATH = "node-remove"
|
1602 |
HTYPE = constants.HTYPE_NODE |
1603 |
_OP_REQP = ["node_name"]
|
1604 |
|
1605 |
def BuildHooksEnv(self): |
1606 |
"""Build hooks env.
|
1607 |
|
1608 |
This doesn't run on the target node in the pre phase as a failed
|
1609 |
node would then be impossible to remove.
|
1610 |
|
1611 |
"""
|
1612 |
env = { |
1613 |
"OP_TARGET": self.op.node_name, |
1614 |
"NODE_NAME": self.op.node_name, |
1615 |
} |
1616 |
all_nodes = self.cfg.GetNodeList()
|
1617 |
all_nodes.remove(self.op.node_name)
|
1618 |
return env, all_nodes, all_nodes
|
1619 |
|
1620 |
def CheckPrereq(self): |
1621 |
"""Check prerequisites.
|
1622 |
|
1623 |
This checks:
|
1624 |
- the node exists in the configuration
|
1625 |
- it does not have primary or secondary instances
|
1626 |
- it's not the master
|
1627 |
|
1628 |
Any errors are signalled by raising errors.OpPrereqError.
|
1629 |
|
1630 |
"""
|
1631 |
node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name)) |
1632 |
if node is None: |
1633 |
raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name) |
1634 |
|
1635 |
instance_list = self.cfg.GetInstanceList()
|
1636 |
|
1637 |
masternode = self.cfg.GetMasterNode()
|
1638 |
if node.name == masternode:
|
1639 |
raise errors.OpPrereqError("Node is the master node," |
1640 |
" you need to failover first.")
|
1641 |
|
1642 |
for instance_name in instance_list: |
1643 |
instance = self.cfg.GetInstanceInfo(instance_name)
|
1644 |
if node.name == instance.primary_node:
|
1645 |
raise errors.OpPrereqError("Instance %s still running on the node," |
1646 |
" please remove first." % instance_name)
|
1647 |
if node.name in instance.secondary_nodes: |
1648 |
raise errors.OpPrereqError("Instance %s has node as a secondary," |
1649 |
" please remove first." % instance_name)
|
1650 |
self.op.node_name = node.name
|
1651 |
self.node = node
|
1652 |
|
1653 |
def Exec(self, feedback_fn): |
1654 |
"""Removes the node from the cluster.
|
1655 |
|
1656 |
"""
|
1657 |
node = self.node
|
1658 |
logging.info("Stopping the node daemon and removing configs from node %s",
|
1659 |
node.name) |
1660 |
|
1661 |
self.context.RemoveNode(node.name)
|
1662 |
|
1663 |
self.rpc.call_node_leave_cluster(node.name)
|
1664 |
|
1665 |
# Promote nodes to master candidate as needed
|
1666 |
_AdjustCandidatePool(self)
|
1667 |
|
1668 |
|
1669 |
class LUQueryNodes(NoHooksLU): |
1670 |
"""Logical unit for querying nodes.
|
1671 |
|
1672 |
"""
|
1673 |
_OP_REQP = ["output_fields", "names"] |
1674 |
REQ_BGL = False
|
1675 |
_FIELDS_DYNAMIC = utils.FieldSet( |
1676 |
"dtotal", "dfree", |
1677 |
"mtotal", "mnode", "mfree", |
1678 |
"bootid",
|
1679 |
"ctotal",
|
1680 |
) |
1681 |
|
1682 |
_FIELDS_STATIC = utils.FieldSet( |
1683 |
"name", "pinst_cnt", "sinst_cnt", |
1684 |
"pinst_list", "sinst_list", |
1685 |
"pip", "sip", "tags", |
1686 |
"serial_no",
|
1687 |
"master_candidate",
|
1688 |
"master",
|
1689 |
"offline",
|
1690 |
) |
1691 |
|
1692 |
def ExpandNames(self): |
1693 |
_CheckOutputFields(static=self._FIELDS_STATIC,
|
1694 |
dynamic=self._FIELDS_DYNAMIC,
|
1695 |
selected=self.op.output_fields)
|
1696 |
|
1697 |
self.needed_locks = {}
|
1698 |
self.share_locks[locking.LEVEL_NODE] = 1 |
1699 |
|
1700 |
if self.op.names: |
1701 |
self.wanted = _GetWantedNodes(self, self.op.names) |
1702 |
else:
|
1703 |
self.wanted = locking.ALL_SET
|
1704 |
|
1705 |
self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields) |
1706 |
if self.do_locking: |
1707 |
# if we don't request only static fields, we need to lock the nodes
|
1708 |
self.needed_locks[locking.LEVEL_NODE] = self.wanted |
1709 |
|
1710 |
|
1711 |
def CheckPrereq(self): |
1712 |
"""Check prerequisites.
|
1713 |
|
1714 |
"""
|
1715 |
# The validation of the node list is done in the _GetWantedNodes,
|
1716 |
# if non empty, and if empty, there's no validation to do
|
1717 |
pass
|
1718 |
|
1719 |
def Exec(self, feedback_fn): |
1720 |
"""Computes the list of nodes and their attributes.
|
1721 |
|
1722 |
"""
|
1723 |
all_info = self.cfg.GetAllNodesInfo()
|
1724 |
if self.do_locking: |
1725 |
nodenames = self.acquired_locks[locking.LEVEL_NODE]
|
1726 |
elif self.wanted != locking.ALL_SET: |
1727 |
nodenames = self.wanted
|
1728 |
missing = set(nodenames).difference(all_info.keys())
|
1729 |
if missing:
|
1730 |
raise errors.OpExecError(
|
1731 |
"Some nodes were removed before retrieving their data: %s" % missing)
|
1732 |
else:
|
1733 |
nodenames = all_info.keys() |
1734 |
|
1735 |
nodenames = utils.NiceSort(nodenames) |
1736 |
nodelist = [all_info[name] for name in nodenames] |
1737 |
|
1738 |
# begin data gathering
|
1739 |
|
1740 |
if self.do_locking: |
1741 |
live_data = {} |
1742 |
node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(), |
1743 |
self.cfg.GetHypervisorType())
|
1744 |
for name in nodenames: |
1745 |
nodeinfo = node_data[name] |
1746 |
if not nodeinfo.failed and nodeinfo.data: |
1747 |
nodeinfo = nodeinfo.data |
1748 |
fn = utils.TryConvert |
1749 |
live_data[name] = { |
1750 |
"mtotal": fn(int, nodeinfo.get('memory_total', None)), |
1751 |
"mnode": fn(int, nodeinfo.get('memory_dom0', None)), |
1752 |
"mfree": fn(int, nodeinfo.get('memory_free', None)), |
1753 |
"dtotal": fn(int, nodeinfo.get('vg_size', None)), |
1754 |
"dfree": fn(int, nodeinfo.get('vg_free', None)), |
1755 |
"ctotal": fn(int, nodeinfo.get('cpu_total', None)), |
1756 |
"bootid": nodeinfo.get('bootid', None), |
1757 |
} |
1758 |
else:
|
1759 |
live_data[name] = {} |
1760 |
else:
|
1761 |
live_data = dict.fromkeys(nodenames, {})
|
1762 |
|
1763 |
node_to_primary = dict([(name, set()) for name in nodenames]) |
1764 |
node_to_secondary = dict([(name, set()) for name in nodenames]) |
1765 |
|
1766 |
inst_fields = frozenset(("pinst_cnt", "pinst_list", |
1767 |
"sinst_cnt", "sinst_list")) |
1768 |
if inst_fields & frozenset(self.op.output_fields): |
1769 |
instancelist = self.cfg.GetInstanceList()
|
1770 |
|
1771 |
for instance_name in instancelist: |
1772 |
inst = self.cfg.GetInstanceInfo(instance_name)
|
1773 |
if inst.primary_node in node_to_primary: |
1774 |
node_to_primary[inst.primary_node].add(inst.name) |
1775 |
for secnode in inst.secondary_nodes: |
1776 |
if secnode in node_to_secondary: |
1777 |
node_to_secondary[secnode].add(inst.name) |
1778 |
|
1779 |
master_node = self.cfg.GetMasterNode()
|
1780 |
|
1781 |
# end data gathering
|
1782 |
|
1783 |
output = [] |
1784 |
for node in nodelist: |
1785 |
node_output = [] |
1786 |
for field in self.op.output_fields: |
1787 |
if field == "name": |
1788 |
val = node.name |
1789 |
elif field == "pinst_list": |
1790 |
val = list(node_to_primary[node.name])
|
1791 |
elif field == "sinst_list": |
1792 |
val = list(node_to_secondary[node.name])
|
1793 |
elif field == "pinst_cnt": |
1794 |
val = len(node_to_primary[node.name])
|
1795 |
elif field == "sinst_cnt": |
1796 |
val = len(node_to_secondary[node.name])
|
1797 |
elif field == "pip": |
1798 |
val = node.primary_ip |
1799 |
elif field == "sip": |
1800 |
val = node.secondary_ip |
1801 |
elif field == "tags": |
1802 |
val = list(node.GetTags())
|
1803 |
elif field == "serial_no": |
1804 |
val = node.serial_no |
1805 |
elif field == "master_candidate": |
1806 |
val = node.master_candidate |
1807 |
elif field == "master": |
1808 |
val = node.name == master_node |
1809 |
elif field == "offline": |
1810 |
val = node.offline |
1811 |
elif self._FIELDS_DYNAMIC.Matches(field): |
1812 |
val = live_data[node.name].get(field, None)
|
1813 |
else:
|
1814 |
raise errors.ParameterError(field)
|
1815 |
node_output.append(val) |
1816 |
output.append(node_output) |
1817 |
|
1818 |
return output
|
1819 |
|
1820 |
|
1821 |
class LUQueryNodeVolumes(NoHooksLU): |
1822 |
"""Logical unit for getting volumes on node(s).
|
1823 |
|
1824 |
"""
|
1825 |
_OP_REQP = ["nodes", "output_fields"] |
1826 |
REQ_BGL = False
|
1827 |
_FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance") |
1828 |
_FIELDS_STATIC = utils.FieldSet("node")
|
1829 |
|
1830 |
def ExpandNames(self): |
1831 |
_CheckOutputFields(static=self._FIELDS_STATIC,
|
1832 |
dynamic=self._FIELDS_DYNAMIC,
|
1833 |
selected=self.op.output_fields)
|
1834 |
|
1835 |
self.needed_locks = {}
|
1836 |
self.share_locks[locking.LEVEL_NODE] = 1 |
1837 |
if not self.op.nodes: |
1838 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
1839 |
else:
|
1840 |
self.needed_locks[locking.LEVEL_NODE] = \
|
1841 |
_GetWantedNodes(self, self.op.nodes) |
1842 |
|
1843 |
def CheckPrereq(self): |
1844 |
"""Check prerequisites.
|
1845 |
|
1846 |
This checks that the fields required are valid output fields.
|
1847 |
|
1848 |
"""
|
1849 |
self.nodes = self.acquired_locks[locking.LEVEL_NODE] |
1850 |
|
1851 |
def Exec(self, feedback_fn): |
1852 |
"""Computes the list of nodes and their attributes.
|
1853 |
|
1854 |
"""
|
1855 |
nodenames = self.nodes
|
1856 |
volumes = self.rpc.call_node_volumes(nodenames)
|
1857 |
|
1858 |
ilist = [self.cfg.GetInstanceInfo(iname) for iname |
1859 |
in self.cfg.GetInstanceList()] |
1860 |
|
1861 |
lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist]) |
1862 |
|
1863 |
output = [] |
1864 |
for node in nodenames: |
1865 |
if node not in volumes or volumes[node].failed or not volumes[node].data: |
1866 |
continue
|
1867 |
|
1868 |
node_vols = volumes[node].data[:] |
1869 |
node_vols.sort(key=lambda vol: vol['dev']) |
1870 |
|
1871 |
for vol in node_vols: |
1872 |
node_output = [] |
1873 |
for field in self.op.output_fields: |
1874 |
if field == "node": |
1875 |
val = node |
1876 |
elif field == "phys": |
1877 |
val = vol['dev']
|
1878 |
elif field == "vg": |
1879 |
val = vol['vg']
|
1880 |
elif field == "name": |
1881 |
val = vol['name']
|
1882 |
elif field == "size": |
1883 |
val = int(float(vol['size'])) |
1884 |
elif field == "instance": |
1885 |
for inst in ilist: |
1886 |
if node not in lv_by_node[inst]: |
1887 |
continue
|
1888 |
if vol['name'] in lv_by_node[inst][node]: |
1889 |
val = inst.name |
1890 |
break
|
1891 |
else:
|
1892 |
val = '-'
|
1893 |
else:
|
1894 |
raise errors.ParameterError(field)
|
1895 |
node_output.append(str(val))
|
1896 |
|
1897 |
output.append(node_output) |
1898 |
|
1899 |
return output
|
1900 |
|
1901 |
|
1902 |
class LUAddNode(LogicalUnit): |
1903 |
"""Logical unit for adding node to the cluster.
|
1904 |
|
1905 |
"""
|
1906 |
HPATH = "node-add"
|
1907 |
HTYPE = constants.HTYPE_NODE |
1908 |
_OP_REQP = ["node_name"]
|
1909 |
|
1910 |
def BuildHooksEnv(self): |
1911 |
"""Build hooks env.
|
1912 |
|
1913 |
This will run on all nodes before, and on all nodes + the new node after.
|
1914 |
|
1915 |
"""
|
1916 |
env = { |
1917 |
"OP_TARGET": self.op.node_name, |
1918 |
"NODE_NAME": self.op.node_name, |
1919 |
"NODE_PIP": self.op.primary_ip, |
1920 |
"NODE_SIP": self.op.secondary_ip, |
1921 |
} |
1922 |
nodes_0 = self.cfg.GetNodeList()
|
1923 |
nodes_1 = nodes_0 + [self.op.node_name, ]
|
1924 |
return env, nodes_0, nodes_1
|
1925 |
|
1926 |
def CheckPrereq(self): |
1927 |
"""Check prerequisites.
|
1928 |
|
1929 |
This checks:
|
1930 |
- the new node is not already in the config
|
1931 |
- it is resolvable
|
1932 |
- its parameters (single/dual homed) matches the cluster
|
1933 |
|
1934 |
Any errors are signalled by raising errors.OpPrereqError.
|
1935 |
|
1936 |
"""
|
1937 |
node_name = self.op.node_name
|
1938 |
cfg = self.cfg
|
1939 |
|
1940 |
dns_data = utils.HostInfo(node_name) |
1941 |
|
1942 |
node = dns_data.name |
1943 |
primary_ip = self.op.primary_ip = dns_data.ip
|
1944 |
secondary_ip = getattr(self.op, "secondary_ip", None) |
1945 |
if secondary_ip is None: |
1946 |
secondary_ip = primary_ip |
1947 |
if not utils.IsValidIP(secondary_ip): |
1948 |
raise errors.OpPrereqError("Invalid secondary IP given") |
1949 |
self.op.secondary_ip = secondary_ip
|
1950 |
|
1951 |
node_list = cfg.GetNodeList() |
1952 |
if not self.op.readd and node in node_list: |
1953 |
raise errors.OpPrereqError("Node %s is already in the configuration" % |
1954 |
node) |
1955 |
elif self.op.readd and node not in node_list: |
1956 |
raise errors.OpPrereqError("Node %s is not in the configuration" % node) |
1957 |
|
1958 |
for existing_node_name in node_list: |
1959 |
existing_node = cfg.GetNodeInfo(existing_node_name) |
1960 |
|
1961 |
if self.op.readd and node == existing_node_name: |
1962 |
if (existing_node.primary_ip != primary_ip or |
1963 |
existing_node.secondary_ip != secondary_ip): |
1964 |
raise errors.OpPrereqError("Readded node doesn't have the same IP" |
1965 |
" address configuration as before")
|
1966 |
continue
|
1967 |
|
1968 |
if (existing_node.primary_ip == primary_ip or |
1969 |
existing_node.secondary_ip == primary_ip or
|
1970 |
existing_node.primary_ip == secondary_ip or
|
1971 |
existing_node.secondary_ip == secondary_ip): |
1972 |
raise errors.OpPrereqError("New node ip address(es) conflict with" |
1973 |
" existing node %s" % existing_node.name)
|
1974 |
|
1975 |
# check that the type of the node (single versus dual homed) is the
|
1976 |
# same as for the master
|
1977 |
myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
|
1978 |
master_singlehomed = myself.secondary_ip == myself.primary_ip |
1979 |
newbie_singlehomed = secondary_ip == primary_ip |
1980 |
if master_singlehomed != newbie_singlehomed:
|
1981 |
if master_singlehomed:
|
1982 |
raise errors.OpPrereqError("The master has no private ip but the" |
1983 |
" new node has one")
|
1984 |
else:
|
1985 |
raise errors.OpPrereqError("The master has a private ip but the" |
1986 |
" new node doesn't have one")
|
1987 |
|
1988 |
# checks reachablity
|
1989 |
if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT): |
1990 |
raise errors.OpPrereqError("Node not reachable by ping") |
1991 |
|
1992 |
if not newbie_singlehomed: |
1993 |
# check reachability from my secondary ip to newbie's secondary ip
|
1994 |
if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT, |
1995 |
source=myself.secondary_ip): |
1996 |
raise errors.OpPrereqError("Node secondary ip not reachable by TCP" |
1997 |
" based ping to noded port")
|
1998 |
|
1999 |
cp_size = self.cfg.GetClusterInfo().candidate_pool_size
|
2000 |
node_info = self.cfg.GetAllNodesInfo().values()
|
2001 |
mc_now, _ = self.cfg.GetMasterCandidateStats()
|
2002 |
master_candidate = mc_now < cp_size |
2003 |
|
2004 |
self.new_node = objects.Node(name=node,
|
2005 |
primary_ip=primary_ip, |
2006 |
secondary_ip=secondary_ip, |
2007 |
master_candidate=master_candidate, |
2008 |
offline=False)
|
2009 |
|
2010 |
def Exec(self, feedback_fn): |
2011 |
"""Adds the new node to the cluster.
|
2012 |
|
2013 |
"""
|
2014 |
new_node = self.new_node
|
2015 |
node = new_node.name |
2016 |
|
2017 |
# check connectivity
|
2018 |
result = self.rpc.call_version([node])[node]
|
2019 |
result.Raise() |
2020 |
if result.data:
|
2021 |
if constants.PROTOCOL_VERSION == result.data:
|
2022 |
logging.info("Communication to node %s fine, sw version %s match",
|
2023 |
node, result.data) |
2024 |
else:
|
2025 |
raise errors.OpExecError("Version mismatch master version %s," |
2026 |
" node version %s" %
|
2027 |
(constants.PROTOCOL_VERSION, result.data)) |
2028 |
else:
|
2029 |
raise errors.OpExecError("Cannot get version from the new node") |
2030 |
|
2031 |
# setup ssh on node
|
2032 |
logging.info("Copy ssh key to node %s", node)
|
2033 |
priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS) |
2034 |
keyarray = [] |
2035 |
keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB, |
2036 |
constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB, |
2037 |
priv_key, pub_key] |
2038 |
|
2039 |
for i in keyfiles: |
2040 |
f = open(i, 'r') |
2041 |
try:
|
2042 |
keyarray.append(f.read()) |
2043 |
finally:
|
2044 |
f.close() |
2045 |
|
2046 |
result = self.rpc.call_node_add(node, keyarray[0], keyarray[1], |
2047 |
keyarray[2],
|
2048 |
keyarray[3], keyarray[4], keyarray[5]) |
2049 |
|
2050 |
if result.failed or not result.data: |
2051 |
raise errors.OpExecError("Cannot transfer ssh keys to the new node") |
2052 |
|
2053 |
# Add node to our /etc/hosts, and add key to known_hosts
|
2054 |
utils.AddHostToEtcHosts(new_node.name) |
2055 |
|
2056 |
if new_node.secondary_ip != new_node.primary_ip:
|
2057 |
result = self.rpc.call_node_has_ip_address(new_node.name,
|
2058 |
new_node.secondary_ip) |
2059 |
if result.failed or not result.data: |
2060 |
raise errors.OpExecError("Node claims it doesn't have the secondary ip" |
2061 |
" you gave (%s). Please fix and re-run this"
|
2062 |
" command." % new_node.secondary_ip)
|
2063 |
|
2064 |
node_verify_list = [self.cfg.GetMasterNode()]
|
2065 |
node_verify_param = { |
2066 |
'nodelist': [node],
|
2067 |
# TODO: do a node-net-test as well?
|
2068 |
} |
2069 |
|
2070 |
result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
|
2071 |
self.cfg.GetClusterName())
|
2072 |
for verifier in node_verify_list: |
2073 |
if result[verifier].failed or not result[verifier].data: |
2074 |
raise errors.OpExecError("Cannot communicate with %s's node daemon" |
2075 |
" for remote verification" % verifier)
|
2076 |
if result[verifier].data['nodelist']: |
2077 |
for failed in result[verifier].data['nodelist']: |
2078 |
feedback_fn("ssh/hostname verification failed %s -> %s" %
|
2079 |
(verifier, result[verifier]['nodelist'][failed]))
|
2080 |
raise errors.OpExecError("ssh/hostname verification failed.") |
2081 |
|
2082 |
# Distribute updated /etc/hosts and known_hosts to all nodes,
|
2083 |
# including the node just added
|
2084 |
myself = self.cfg.GetNodeInfo(self.cfg.GetMasterNode()) |
2085 |
dist_nodes = self.cfg.GetNodeList()
|
2086 |
if not self.op.readd: |
2087 |
dist_nodes.append(node) |
2088 |
if myself.name in dist_nodes: |
2089 |
dist_nodes.remove(myself.name) |
2090 |
|
2091 |
logging.debug("Copying hosts and known_hosts to all nodes")
|
2092 |
for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE): |
2093 |
result = self.rpc.call_upload_file(dist_nodes, fname)
|
2094 |
for to_node, to_result in result.iteritems(): |
2095 |
if to_result.failed or not to_result.data: |
2096 |
logging.error("Copy of file %s to node %s failed", fname, to_node)
|
2097 |
|
2098 |
to_copy = [] |
2099 |
if constants.HT_XEN_HVM in self.cfg.GetClusterInfo().enabled_hypervisors: |
2100 |
to_copy.append(constants.VNC_PASSWORD_FILE) |
2101 |
for fname in to_copy: |
2102 |
result = self.rpc.call_upload_file([node], fname)
|
2103 |
if result[node].failed or not result[node]: |
2104 |
logging.error("Could not copy file %s to node %s", fname, node)
|
2105 |
|
2106 |
if self.op.readd: |
2107 |
self.context.ReaddNode(new_node)
|
2108 |
else:
|
2109 |
self.context.AddNode(new_node)
|
2110 |
|
2111 |
|
2112 |
class LUSetNodeParams(LogicalUnit): |
2113 |
"""Modifies the parameters of a node.
|
2114 |
|
2115 |
"""
|
2116 |
HPATH = "node-modify"
|
2117 |
HTYPE = constants.HTYPE_NODE |
2118 |
_OP_REQP = ["node_name"]
|
2119 |
REQ_BGL = False
|
2120 |
|
2121 |
def CheckArguments(self): |
2122 |
node_name = self.cfg.ExpandNodeName(self.op.node_name) |
2123 |
if node_name is None: |
2124 |
raise errors.OpPrereqError("Invalid node name '%s'" % self.op.node_name) |
2125 |
self.op.node_name = node_name
|
2126 |
if not hasattr(self.op, 'master_candidate'): |
2127 |
raise errors.OpPrereqError("Please pass at least one modification") |
2128 |
self.op.master_candidate = bool(self.op.master_candidate) |
2129 |
|
2130 |
def ExpandNames(self): |
2131 |
self.needed_locks = {locking.LEVEL_NODE: self.op.node_name} |
2132 |
|
2133 |
def BuildHooksEnv(self): |
2134 |
"""Build hooks env.
|
2135 |
|
2136 |
This runs on the master node.
|
2137 |
|
2138 |
"""
|
2139 |
env = { |
2140 |
"OP_TARGET": self.op.node_name, |
2141 |
"MASTER_CANDIDATE": str(self.op.master_candidate), |
2142 |
} |
2143 |
nl = [self.cfg.GetMasterNode(),
|
2144 |
self.op.node_name]
|
2145 |
return env, nl, nl
|
2146 |
|
2147 |
def CheckPrereq(self): |
2148 |
"""Check prerequisites.
|
2149 |
|
2150 |
This only checks the instance list against the existing names.
|
2151 |
|
2152 |
"""
|
2153 |
force = self.force = self.op.force |
2154 |
|
2155 |
if self.op.master_candidate == False: |
2156 |
if self.op.node_name == self.cfg.GetMasterNode(): |
2157 |
raise errors.OpPrereqError("The master node has to be a" |
2158 |
" master candidate")
|
2159 |
cp_size = self.cfg.GetClusterInfo().candidate_pool_size
|
2160 |
node_info = self.cfg.GetAllNodesInfo().values()
|
2161 |
num_candidates = len([node for node in node_info |
2162 |
if node.master_candidate])
|
2163 |
if num_candidates <= cp_size:
|
2164 |
msg = ("Not enough master candidates (desired"
|
2165 |
" %d, new value will be %d)" % (cp_size, num_candidates-1)) |
2166 |
if force:
|
2167 |
self.LogWarning(msg)
|
2168 |
else:
|
2169 |
raise errors.OpPrereqError(msg)
|
2170 |
|
2171 |
return
|
2172 |
|
2173 |
def Exec(self, feedback_fn): |
2174 |
"""Modifies a node.
|
2175 |
|
2176 |
"""
|
2177 |
node = self.cfg.GetNodeInfo(self.op.node_name) |
2178 |
|
2179 |
result = [] |
2180 |
|
2181 |
if self.op.master_candidate is not None: |
2182 |
node.master_candidate = self.op.master_candidate
|
2183 |
result.append(("master_candidate", str(self.op.master_candidate))) |
2184 |
if self.op.master_candidate == False: |
2185 |
rrc = self.rpc.call_node_demote_from_mc(node.name)
|
2186 |
if (rrc.failed or not isinstance(rrc.data, (tuple, list)) |
2187 |
or len(rrc.data) != 2): |
2188 |
self.LogWarning("Node rpc error: %s" % rrc.error) |
2189 |
elif not rrc.data[0]: |
2190 |
self.LogWarning("Node failed to demote itself: %s" % rrc.data[1]) |
2191 |
|
2192 |
# this will trigger configuration file update, if needed
|
2193 |
self.cfg.Update(node)
|
2194 |
# this will trigger job queue propagation or cleanup
|
2195 |
if self.op.node_name != self.cfg.GetMasterNode(): |
2196 |
self.context.ReaddNode(node)
|
2197 |
|
2198 |
return result
|
2199 |
|
2200 |
|
2201 |
class LUQueryClusterInfo(NoHooksLU): |
2202 |
"""Query cluster configuration.
|
2203 |
|
2204 |
"""
|
2205 |
_OP_REQP = [] |
2206 |
REQ_BGL = False
|
2207 |
|
2208 |
def ExpandNames(self): |
2209 |
self.needed_locks = {}
|
2210 |
|
2211 |
def CheckPrereq(self): |
2212 |
"""No prerequsites needed for this LU.
|
2213 |
|
2214 |
"""
|
2215 |
pass
|
2216 |
|
2217 |
def Exec(self, feedback_fn): |
2218 |
"""Return cluster config.
|
2219 |
|
2220 |
"""
|
2221 |
cluster = self.cfg.GetClusterInfo()
|
2222 |
result = { |
2223 |
"software_version": constants.RELEASE_VERSION,
|
2224 |
"protocol_version": constants.PROTOCOL_VERSION,
|
2225 |
"config_version": constants.CONFIG_VERSION,
|
2226 |
"os_api_version": constants.OS_API_VERSION,
|
2227 |
"export_version": constants.EXPORT_VERSION,
|
2228 |
"architecture": (platform.architecture()[0], platform.machine()), |
2229 |
"name": cluster.cluster_name,
|
2230 |
"master": cluster.master_node,
|
2231 |
"default_hypervisor": cluster.default_hypervisor,
|
2232 |
"enabled_hypervisors": cluster.enabled_hypervisors,
|
2233 |
"hvparams": cluster.hvparams,
|
2234 |
"beparams": cluster.beparams,
|
2235 |
"candidate_pool_size": cluster.candidate_pool_size,
|
2236 |
} |
2237 |
|
2238 |
return result
|
2239 |
|
2240 |
|
2241 |
class LUQueryConfigValues(NoHooksLU): |
2242 |
"""Return configuration values.
|
2243 |
|
2244 |
"""
|
2245 |
_OP_REQP = [] |
2246 |
REQ_BGL = False
|
2247 |
_FIELDS_DYNAMIC = utils.FieldSet() |
2248 |
_FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag") |
2249 |
|
2250 |
def ExpandNames(self): |
2251 |
self.needed_locks = {}
|
2252 |
|
2253 |
_CheckOutputFields(static=self._FIELDS_STATIC,
|
2254 |
dynamic=self._FIELDS_DYNAMIC,
|
2255 |
selected=self.op.output_fields)
|
2256 |
|
2257 |
def CheckPrereq(self): |
2258 |
"""No prerequisites.
|
2259 |
|
2260 |
"""
|
2261 |
pass
|
2262 |
|
2263 |
def Exec(self, feedback_fn): |
2264 |
"""Dump a representation of the cluster config to the standard output.
|
2265 |
|
2266 |
"""
|
2267 |
values = [] |
2268 |
for field in self.op.output_fields: |
2269 |
if field == "cluster_name": |
2270 |
entry = self.cfg.GetClusterName()
|
2271 |
elif field == "master_node": |
2272 |
entry = self.cfg.GetMasterNode()
|
2273 |
elif field == "drain_flag": |
2274 |
entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE) |
2275 |
else:
|
2276 |
raise errors.ParameterError(field)
|
2277 |
values.append(entry) |
2278 |
return values
|
2279 |
|
2280 |
|
2281 |
class LUActivateInstanceDisks(NoHooksLU): |
2282 |
"""Bring up an instance's disks.
|
2283 |
|
2284 |
"""
|
2285 |
_OP_REQP = ["instance_name"]
|
2286 |
REQ_BGL = False
|
2287 |
|
2288 |
def ExpandNames(self): |
2289 |
self._ExpandAndLockInstance()
|
2290 |
self.needed_locks[locking.LEVEL_NODE] = []
|
2291 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
2292 |
|
2293 |
def DeclareLocks(self, level): |
2294 |
if level == locking.LEVEL_NODE:
|
2295 |
self._LockInstancesNodes()
|
2296 |
|
2297 |
def CheckPrereq(self): |
2298 |
"""Check prerequisites.
|
2299 |
|
2300 |
This checks that the instance is in the cluster.
|
2301 |
|
2302 |
"""
|
2303 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
2304 |
assert self.instance is not None, \ |
2305 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2306 |
_CheckNodeOnline(self, instance.primary_node)
|
2307 |
|
2308 |
def Exec(self, feedback_fn): |
2309 |
"""Activate the disks.
|
2310 |
|
2311 |
"""
|
2312 |
disks_ok, disks_info = _AssembleInstanceDisks(self, self.instance) |
2313 |
if not disks_ok: |
2314 |
raise errors.OpExecError("Cannot activate block devices") |
2315 |
|
2316 |
return disks_info
|
2317 |
|
2318 |
|
2319 |
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False): |
2320 |
"""Prepare the block devices for an instance.
|
2321 |
|
2322 |
This sets up the block devices on all nodes.
|
2323 |
|
2324 |
@type lu: L{LogicalUnit}
|
2325 |
@param lu: the logical unit on whose behalf we execute
|
2326 |
@type instance: L{objects.Instance}
|
2327 |
@param instance: the instance for whose disks we assemble
|
2328 |
@type ignore_secondaries: boolean
|
2329 |
@param ignore_secondaries: if true, errors on secondary nodes
|
2330 |
won't result in an error return from the function
|
2331 |
@return: False if the operation failed, otherwise a list of
|
2332 |
(host, instance_visible_name, node_visible_name)
|
2333 |
with the mapping from node devices to instance devices
|
2334 |
|
2335 |
"""
|
2336 |
device_info = [] |
2337 |
disks_ok = True
|
2338 |
iname = instance.name |
2339 |
# With the two passes mechanism we try to reduce the window of
|
2340 |
# opportunity for the race condition of switching DRBD to primary
|
2341 |
# before handshaking occured, but we do not eliminate it
|
2342 |
|
2343 |
# The proper fix would be to wait (with some limits) until the
|
2344 |
# connection has been made and drbd transitions from WFConnection
|
2345 |
# into any other network-connected state (Connected, SyncTarget,
|
2346 |
# SyncSource, etc.)
|
2347 |
|
2348 |
# 1st pass, assemble on all nodes in secondary mode
|
2349 |
for inst_disk in instance.disks: |
2350 |
for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node): |
2351 |
lu.cfg.SetDiskID(node_disk, node) |
2352 |
result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
|
2353 |
if result.failed or not result: |
2354 |
lu.proc.LogWarning("Could not prepare block device %s on node %s"
|
2355 |
" (is_primary=False, pass=1)",
|
2356 |
inst_disk.iv_name, node) |
2357 |
if not ignore_secondaries: |
2358 |
disks_ok = False
|
2359 |
|
2360 |
# FIXME: race condition on drbd migration to primary
|
2361 |
|
2362 |
# 2nd pass, do only the primary node
|
2363 |
for inst_disk in instance.disks: |
2364 |
for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node): |
2365 |
if node != instance.primary_node:
|
2366 |
continue
|
2367 |
lu.cfg.SetDiskID(node_disk, node) |
2368 |
result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
|
2369 |
if result.failed or not result: |
2370 |
lu.proc.LogWarning("Could not prepare block device %s on node %s"
|
2371 |
" (is_primary=True, pass=2)",
|
2372 |
inst_disk.iv_name, node) |
2373 |
disks_ok = False
|
2374 |
device_info.append((instance.primary_node, inst_disk.iv_name, result)) |
2375 |
|
2376 |
# leave the disks configured for the primary node
|
2377 |
# this is a workaround that would be fixed better by
|
2378 |
# improving the logical/physical id handling
|
2379 |
for disk in instance.disks: |
2380 |
lu.cfg.SetDiskID(disk, instance.primary_node) |
2381 |
|
2382 |
return disks_ok, device_info
|
2383 |
|
2384 |
|
2385 |
def _StartInstanceDisks(lu, instance, force): |
2386 |
"""Start the disks of an instance.
|
2387 |
|
2388 |
"""
|
2389 |
disks_ok, dummy = _AssembleInstanceDisks(lu, instance, |
2390 |
ignore_secondaries=force) |
2391 |
if not disks_ok: |
2392 |
_ShutdownInstanceDisks(lu, instance) |
2393 |
if force is not None and not force: |
2394 |
lu.proc.LogWarning("", hint="If the message above refers to a" |
2395 |
" secondary node,"
|
2396 |
" you can retry the operation using '--force'.")
|
2397 |
raise errors.OpExecError("Disk consistency error") |
2398 |
|
2399 |
|
2400 |
class LUDeactivateInstanceDisks(NoHooksLU): |
2401 |
"""Shutdown an instance's disks.
|
2402 |
|
2403 |
"""
|
2404 |
_OP_REQP = ["instance_name"]
|
2405 |
REQ_BGL = False
|
2406 |
|
2407 |
def ExpandNames(self): |
2408 |
self._ExpandAndLockInstance()
|
2409 |
self.needed_locks[locking.LEVEL_NODE] = []
|
2410 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
2411 |
|
2412 |
def DeclareLocks(self, level): |
2413 |
if level == locking.LEVEL_NODE:
|
2414 |
self._LockInstancesNodes()
|
2415 |
|
2416 |
def CheckPrereq(self): |
2417 |
"""Check prerequisites.
|
2418 |
|
2419 |
This checks that the instance is in the cluster.
|
2420 |
|
2421 |
"""
|
2422 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
2423 |
assert self.instance is not None, \ |
2424 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2425 |
|
2426 |
def Exec(self, feedback_fn): |
2427 |
"""Deactivate the disks
|
2428 |
|
2429 |
"""
|
2430 |
instance = self.instance
|
2431 |
_SafeShutdownInstanceDisks(self, instance)
|
2432 |
|
2433 |
|
2434 |
def _SafeShutdownInstanceDisks(lu, instance): |
2435 |
"""Shutdown block devices of an instance.
|
2436 |
|
2437 |
This function checks if an instance is running, before calling
|
2438 |
_ShutdownInstanceDisks.
|
2439 |
|
2440 |
"""
|
2441 |
ins_l = lu.rpc.call_instance_list([instance.primary_node], |
2442 |
[instance.hypervisor]) |
2443 |
ins_l = ins_l[instance.primary_node] |
2444 |
if ins_l.failed or not isinstance(ins_l.data, list): |
2445 |
raise errors.OpExecError("Can't contact node '%s'" % |
2446 |
instance.primary_node) |
2447 |
|
2448 |
if instance.name in ins_l.data: |
2449 |
raise errors.OpExecError("Instance is running, can't shutdown" |
2450 |
" block devices.")
|
2451 |
|
2452 |
_ShutdownInstanceDisks(lu, instance) |
2453 |
|
2454 |
|
2455 |
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False): |
2456 |
"""Shutdown block devices of an instance.
|
2457 |
|
2458 |
This does the shutdown on all nodes of the instance.
|
2459 |
|
2460 |
If the ignore_primary is false, errors on the primary node are
|
2461 |
ignored.
|
2462 |
|
2463 |
"""
|
2464 |
result = True
|
2465 |
for disk in instance.disks: |
2466 |
for node, top_disk in disk.ComputeNodeTree(instance.primary_node): |
2467 |
lu.cfg.SetDiskID(top_disk, node) |
2468 |
result = lu.rpc.call_blockdev_shutdown(node, top_disk) |
2469 |
if result.failed or not result.data: |
2470 |
logging.error("Could not shutdown block device %s on node %s",
|
2471 |
disk.iv_name, node) |
2472 |
if not ignore_primary or node != instance.primary_node: |
2473 |
result = False
|
2474 |
return result
|
2475 |
|
2476 |
|
2477 |
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor): |
2478 |
"""Checks if a node has enough free memory.
|
2479 |
|
2480 |
This function check if a given node has the needed amount of free
|
2481 |
memory. In case the node has less memory or we cannot get the
|
2482 |
information from the node, this function raise an OpPrereqError
|
2483 |
exception.
|
2484 |
|
2485 |
@type lu: C{LogicalUnit}
|
2486 |
@param lu: a logical unit from which we get configuration data
|
2487 |
@type node: C{str}
|
2488 |
@param node: the node to check
|
2489 |
@type reason: C{str}
|
2490 |
@param reason: string to use in the error message
|
2491 |
@type requested: C{int}
|
2492 |
@param requested: the amount of memory in MiB to check for
|
2493 |
@type hypervisor: C{str}
|
2494 |
@param hypervisor: the hypervisor to ask for memory stats
|
2495 |
@raise errors.OpPrereqError: if the node doesn't have enough memory, or
|
2496 |
we cannot check the node
|
2497 |
|
2498 |
"""
|
2499 |
nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor) |
2500 |
nodeinfo[node].Raise() |
2501 |
free_mem = nodeinfo[node].data.get('memory_free')
|
2502 |
if not isinstance(free_mem, int): |
2503 |
raise errors.OpPrereqError("Can't compute free memory on node %s, result" |
2504 |
" was '%s'" % (node, free_mem))
|
2505 |
if requested > free_mem:
|
2506 |
raise errors.OpPrereqError("Not enough memory on node %s for %s:" |
2507 |
" needed %s MiB, available %s MiB" %
|
2508 |
(node, reason, requested, free_mem)) |
2509 |
|
2510 |
|
2511 |
class LUStartupInstance(LogicalUnit): |
2512 |
"""Starts an instance.
|
2513 |
|
2514 |
"""
|
2515 |
HPATH = "instance-start"
|
2516 |
HTYPE = constants.HTYPE_INSTANCE |
2517 |
_OP_REQP = ["instance_name", "force"] |
2518 |
REQ_BGL = False
|
2519 |
|
2520 |
def ExpandNames(self): |
2521 |
self._ExpandAndLockInstance()
|
2522 |
|
2523 |
def BuildHooksEnv(self): |
2524 |
"""Build hooks env.
|
2525 |
|
2526 |
This runs on master, primary and secondary nodes of the instance.
|
2527 |
|
2528 |
"""
|
2529 |
env = { |
2530 |
"FORCE": self.op.force, |
2531 |
} |
2532 |
env.update(_BuildInstanceHookEnvByObject(self, self.instance)) |
2533 |
nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] + |
2534 |
list(self.instance.secondary_nodes)) |
2535 |
return env, nl, nl
|
2536 |
|
2537 |
def CheckPrereq(self): |
2538 |
"""Check prerequisites.
|
2539 |
|
2540 |
This checks that the instance is in the cluster.
|
2541 |
|
2542 |
"""
|
2543 |
self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
2544 |
assert self.instance is not None, \ |
2545 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2546 |
|
2547 |
_CheckNodeOnline(self, instance.primary_node)
|
2548 |
|
2549 |
bep = self.cfg.GetClusterInfo().FillBE(instance)
|
2550 |
# check bridges existance
|
2551 |
_CheckInstanceBridgesExist(self, instance)
|
2552 |
|
2553 |
_CheckNodeFreeMemory(self, instance.primary_node,
|
2554 |
"starting instance %s" % instance.name,
|
2555 |
bep[constants.BE_MEMORY], instance.hypervisor) |
2556 |
|
2557 |
def Exec(self, feedback_fn): |
2558 |
"""Start the instance.
|
2559 |
|
2560 |
"""
|
2561 |
instance = self.instance
|
2562 |
force = self.op.force
|
2563 |
extra_args = getattr(self.op, "extra_args", "") |
2564 |
|
2565 |
self.cfg.MarkInstanceUp(instance.name)
|
2566 |
|
2567 |
node_current = instance.primary_node |
2568 |
|
2569 |
_StartInstanceDisks(self, instance, force)
|
2570 |
|
2571 |
result = self.rpc.call_instance_start(node_current, instance, extra_args)
|
2572 |
if result.failed or not result.data: |
2573 |
_ShutdownInstanceDisks(self, instance)
|
2574 |
raise errors.OpExecError("Could not start instance") |
2575 |
|
2576 |
|
2577 |
class LURebootInstance(LogicalUnit): |
2578 |
"""Reboot an instance.
|
2579 |
|
2580 |
"""
|
2581 |
HPATH = "instance-reboot"
|
2582 |
HTYPE = constants.HTYPE_INSTANCE |
2583 |
_OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"] |
2584 |
REQ_BGL = False
|
2585 |
|
2586 |
def ExpandNames(self): |
2587 |
if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT, |
2588 |
constants.INSTANCE_REBOOT_HARD, |
2589 |
constants.INSTANCE_REBOOT_FULL]: |
2590 |
raise errors.ParameterError("reboot type not in [%s, %s, %s]" % |
2591 |
(constants.INSTANCE_REBOOT_SOFT, |
2592 |
constants.INSTANCE_REBOOT_HARD, |
2593 |
constants.INSTANCE_REBOOT_FULL)) |
2594 |
self._ExpandAndLockInstance()
|
2595 |
|
2596 |
def BuildHooksEnv(self): |
2597 |
"""Build hooks env.
|
2598 |
|
2599 |
This runs on master, primary and secondary nodes of the instance.
|
2600 |
|
2601 |
"""
|
2602 |
env = { |
2603 |
"IGNORE_SECONDARIES": self.op.ignore_secondaries, |
2604 |
} |
2605 |
env.update(_BuildInstanceHookEnvByObject(self, self.instance)) |
2606 |
nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] + |
2607 |
list(self.instance.secondary_nodes)) |
2608 |
return env, nl, nl
|
2609 |
|
2610 |
def CheckPrereq(self): |
2611 |
"""Check prerequisites.
|
2612 |
|
2613 |
This checks that the instance is in the cluster.
|
2614 |
|
2615 |
"""
|
2616 |
self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
2617 |
assert self.instance is not None, \ |
2618 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2619 |
|
2620 |
_CheckNodeOnline(self, instance.primary_node)
|
2621 |
|
2622 |
# check bridges existance
|
2623 |
_CheckInstanceBridgesExist(self, instance)
|
2624 |
|
2625 |
def Exec(self, feedback_fn): |
2626 |
"""Reboot the instance.
|
2627 |
|
2628 |
"""
|
2629 |
instance = self.instance
|
2630 |
ignore_secondaries = self.op.ignore_secondaries
|
2631 |
reboot_type = self.op.reboot_type
|
2632 |
extra_args = getattr(self.op, "extra_args", "") |
2633 |
|
2634 |
node_current = instance.primary_node |
2635 |
|
2636 |
if reboot_type in [constants.INSTANCE_REBOOT_SOFT, |
2637 |
constants.INSTANCE_REBOOT_HARD]: |
2638 |
result = self.rpc.call_instance_reboot(node_current, instance,
|
2639 |
reboot_type, extra_args) |
2640 |
if result.failed or not result.data: |
2641 |
raise errors.OpExecError("Could not reboot instance") |
2642 |
else:
|
2643 |
if not self.rpc.call_instance_shutdown(node_current, instance): |
2644 |
raise errors.OpExecError("could not shutdown instance for full reboot") |
2645 |
_ShutdownInstanceDisks(self, instance)
|
2646 |
_StartInstanceDisks(self, instance, ignore_secondaries)
|
2647 |
result = self.rpc.call_instance_start(node_current, instance, extra_args)
|
2648 |
if result.failed or not result.data: |
2649 |
_ShutdownInstanceDisks(self, instance)
|
2650 |
raise errors.OpExecError("Could not start instance for full reboot") |
2651 |
|
2652 |
self.cfg.MarkInstanceUp(instance.name)
|
2653 |
|
2654 |
|
2655 |
class LUShutdownInstance(LogicalUnit): |
2656 |
"""Shutdown an instance.
|
2657 |
|
2658 |
"""
|
2659 |
HPATH = "instance-stop"
|
2660 |
HTYPE = constants.HTYPE_INSTANCE |
2661 |
_OP_REQP = ["instance_name"]
|
2662 |
REQ_BGL = False
|
2663 |
|
2664 |
def ExpandNames(self): |
2665 |
self._ExpandAndLockInstance()
|
2666 |
|
2667 |
def BuildHooksEnv(self): |
2668 |
"""Build hooks env.
|
2669 |
|
2670 |
This runs on master, primary and secondary nodes of the instance.
|
2671 |
|
2672 |
"""
|
2673 |
env = _BuildInstanceHookEnvByObject(self, self.instance) |
2674 |
nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] + |
2675 |
list(self.instance.secondary_nodes)) |
2676 |
return env, nl, nl
|
2677 |
|
2678 |
def CheckPrereq(self): |
2679 |
"""Check prerequisites.
|
2680 |
|
2681 |
This checks that the instance is in the cluster.
|
2682 |
|
2683 |
"""
|
2684 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
2685 |
assert self.instance is not None, \ |
2686 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2687 |
_CheckNodeOnline(self, instance.primary_node)
|
2688 |
|
2689 |
def Exec(self, feedback_fn): |
2690 |
"""Shutdown the instance.
|
2691 |
|
2692 |
"""
|
2693 |
instance = self.instance
|
2694 |
node_current = instance.primary_node |
2695 |
self.cfg.MarkInstanceDown(instance.name)
|
2696 |
result = self.rpc.call_instance_shutdown(node_current, instance)
|
2697 |
if result.failed or not result.data: |
2698 |
self.proc.LogWarning("Could not shutdown instance") |
2699 |
|
2700 |
_ShutdownInstanceDisks(self, instance)
|
2701 |
|
2702 |
|
2703 |
class LUReinstallInstance(LogicalUnit): |
2704 |
"""Reinstall an instance.
|
2705 |
|
2706 |
"""
|
2707 |
HPATH = "instance-reinstall"
|
2708 |
HTYPE = constants.HTYPE_INSTANCE |
2709 |
_OP_REQP = ["instance_name"]
|
2710 |
REQ_BGL = False
|
2711 |
|
2712 |
def ExpandNames(self): |
2713 |
self._ExpandAndLockInstance()
|
2714 |
|
2715 |
def BuildHooksEnv(self): |
2716 |
"""Build hooks env.
|
2717 |
|
2718 |
This runs on master, primary and secondary nodes of the instance.
|
2719 |
|
2720 |
"""
|
2721 |
env = _BuildInstanceHookEnvByObject(self, self.instance) |
2722 |
nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] + |
2723 |
list(self.instance.secondary_nodes)) |
2724 |
return env, nl, nl
|
2725 |
|
2726 |
def CheckPrereq(self): |
2727 |
"""Check prerequisites.
|
2728 |
|
2729 |
This checks that the instance is in the cluster and is not running.
|
2730 |
|
2731 |
"""
|
2732 |
instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
2733 |
assert instance is not None, \ |
2734 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2735 |
_CheckNodeOnline(self, instance.primary_node)
|
2736 |
|
2737 |
if instance.disk_template == constants.DT_DISKLESS:
|
2738 |
raise errors.OpPrereqError("Instance '%s' has no disks" % |
2739 |
self.op.instance_name)
|
2740 |
if instance.status != "down": |
2741 |
raise errors.OpPrereqError("Instance '%s' is marked to be up" % |
2742 |
self.op.instance_name)
|
2743 |
remote_info = self.rpc.call_instance_info(instance.primary_node,
|
2744 |
instance.name, |
2745 |
instance.hypervisor) |
2746 |
if remote_info.failed or remote_info.data: |
2747 |
raise errors.OpPrereqError("Instance '%s' is running on the node %s" % |
2748 |
(self.op.instance_name,
|
2749 |
instance.primary_node)) |
2750 |
|
2751 |
self.op.os_type = getattr(self.op, "os_type", None) |
2752 |
if self.op.os_type is not None: |
2753 |
# OS verification
|
2754 |
pnode = self.cfg.GetNodeInfo(
|
2755 |
self.cfg.ExpandNodeName(instance.primary_node))
|
2756 |
if pnode is None: |
2757 |
raise errors.OpPrereqError("Primary node '%s' is unknown" % |
2758 |
self.op.pnode)
|
2759 |
result = self.rpc.call_os_get(pnode.name, self.op.os_type) |
2760 |
result.Raise() |
2761 |
if not isinstance(result.data, objects.OS): |
2762 |
raise errors.OpPrereqError("OS '%s' not in supported OS list for" |
2763 |
" primary node" % self.op.os_type) |
2764 |
|
2765 |
self.instance = instance
|
2766 |
|
2767 |
def Exec(self, feedback_fn): |
2768 |
"""Reinstall the instance.
|
2769 |
|
2770 |
"""
|
2771 |
inst = self.instance
|
2772 |
|
2773 |
if self.op.os_type is not None: |
2774 |
feedback_fn("Changing OS to '%s'..." % self.op.os_type) |
2775 |
inst.os = self.op.os_type
|
2776 |
self.cfg.Update(inst)
|
2777 |
|
2778 |
_StartInstanceDisks(self, inst, None) |
2779 |
try:
|
2780 |
feedback_fn("Running the instance OS create scripts...")
|
2781 |
result = self.rpc.call_instance_os_add(inst.primary_node, inst)
|
2782 |
result.Raise() |
2783 |
if not result.data: |
2784 |
raise errors.OpExecError("Could not install OS for instance %s" |
2785 |
" on node %s" %
|
2786 |
(inst.name, inst.primary_node)) |
2787 |
finally:
|
2788 |
_ShutdownInstanceDisks(self, inst)
|
2789 |
|
2790 |
|
2791 |
class LURenameInstance(LogicalUnit): |
2792 |
"""Rename an instance.
|
2793 |
|
2794 |
"""
|
2795 |
HPATH = "instance-rename"
|
2796 |
HTYPE = constants.HTYPE_INSTANCE |
2797 |
_OP_REQP = ["instance_name", "new_name"] |
2798 |
|
2799 |
def BuildHooksEnv(self): |
2800 |
"""Build hooks env.
|
2801 |
|
2802 |
This runs on master, primary and secondary nodes of the instance.
|
2803 |
|
2804 |
"""
|
2805 |
env = _BuildInstanceHookEnvByObject(self, self.instance) |
2806 |
env["INSTANCE_NEW_NAME"] = self.op.new_name |
2807 |
nl = ([self.cfg.GetMasterNode(), self.instance.primary_node] + |
2808 |
list(self.instance.secondary_nodes)) |
2809 |
return env, nl, nl
|
2810 |
|
2811 |
def CheckPrereq(self): |
2812 |
"""Check prerequisites.
|
2813 |
|
2814 |
This checks that the instance is in the cluster and is not running.
|
2815 |
|
2816 |
"""
|
2817 |
instance = self.cfg.GetInstanceInfo(
|
2818 |
self.cfg.ExpandInstanceName(self.op.instance_name)) |
2819 |
if instance is None: |
2820 |
raise errors.OpPrereqError("Instance '%s' not known" % |
2821 |
self.op.instance_name)
|
2822 |
_CheckNodeOnline(self, instance.primary_node)
|
2823 |
|
2824 |
if instance.status != "down": |
2825 |
raise errors.OpPrereqError("Instance '%s' is marked to be up" % |
2826 |
self.op.instance_name)
|
2827 |
remote_info = self.rpc.call_instance_info(instance.primary_node,
|
2828 |
instance.name, |
2829 |
instance.hypervisor) |
2830 |
remote_info.Raise() |
2831 |
if remote_info.data:
|
2832 |
raise errors.OpPrereqError("Instance '%s' is running on the node %s" % |
2833 |
(self.op.instance_name,
|
2834 |
instance.primary_node)) |
2835 |
self.instance = instance
|
2836 |
|
2837 |
# new name verification
|
2838 |
name_info = utils.HostInfo(self.op.new_name)
|
2839 |
|
2840 |
self.op.new_name = new_name = name_info.name
|
2841 |
instance_list = self.cfg.GetInstanceList()
|
2842 |
if new_name in instance_list: |
2843 |
raise errors.OpPrereqError("Instance '%s' is already in the cluster" % |
2844 |
new_name) |
2845 |
|
2846 |
if not getattr(self.op, "ignore_ip", False): |
2847 |
if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
|
2848 |
raise errors.OpPrereqError("IP %s of instance %s already in use" % |
2849 |
(name_info.ip, new_name)) |
2850 |
|
2851 |
|
2852 |
def Exec(self, feedback_fn): |
2853 |
"""Reinstall the instance.
|
2854 |
|
2855 |
"""
|
2856 |
inst = self.instance
|
2857 |
old_name = inst.name |
2858 |
|
2859 |
if inst.disk_template == constants.DT_FILE:
|
2860 |
old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1]) |
2861 |
|
2862 |
self.cfg.RenameInstance(inst.name, self.op.new_name) |
2863 |
# Change the instance lock. This is definitely safe while we hold the BGL
|
2864 |
self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
|
2865 |
self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name) |
2866 |
|
2867 |
# re-read the instance from the configuration after rename
|
2868 |
inst = self.cfg.GetInstanceInfo(self.op.new_name) |
2869 |
|
2870 |
if inst.disk_template == constants.DT_FILE:
|
2871 |
new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1]) |
2872 |
result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
|
2873 |
old_file_storage_dir, |
2874 |
new_file_storage_dir) |
2875 |
result.Raise() |
2876 |
if not result.data: |
2877 |
raise errors.OpExecError("Could not connect to node '%s' to rename" |
2878 |
" directory '%s' to '%s' (but the instance"
|
2879 |
" has been renamed in Ganeti)" % (
|
2880 |
inst.primary_node, old_file_storage_dir, |
2881 |
new_file_storage_dir)) |
2882 |
|
2883 |
if not result.data[0]: |
2884 |
raise errors.OpExecError("Could not rename directory '%s' to '%s'" |
2885 |
" (but the instance has been renamed in"
|
2886 |
" Ganeti)" % (old_file_storage_dir,
|
2887 |
new_file_storage_dir)) |
2888 |
|
2889 |
_StartInstanceDisks(self, inst, None) |
2890 |
try:
|
2891 |
result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
|
2892 |
old_name) |
2893 |
if result.failed or not result.data: |
2894 |
msg = ("Could not run OS rename script for instance %s on node %s"
|
2895 |
" (but the instance has been renamed in Ganeti)" %
|
2896 |
(inst.name, inst.primary_node)) |
2897 |
self.proc.LogWarning(msg)
|
2898 |
finally:
|
2899 |
_ShutdownInstanceDisks(self, inst)
|
2900 |
|
2901 |
|
2902 |
class LURemoveInstance(LogicalUnit): |
2903 |
"""Remove an instance.
|
2904 |
|
2905 |
"""
|
2906 |
HPATH = "instance-remove"
|
2907 |
HTYPE = constants.HTYPE_INSTANCE |
2908 |
_OP_REQP = ["instance_name", "ignore_failures"] |
2909 |
REQ_BGL = False
|
2910 |
|
2911 |
def ExpandNames(self): |
2912 |
self._ExpandAndLockInstance()
|
2913 |
self.needed_locks[locking.LEVEL_NODE] = []
|
2914 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
2915 |
|
2916 |
def DeclareLocks(self, level): |
2917 |
if level == locking.LEVEL_NODE:
|
2918 |
self._LockInstancesNodes()
|
2919 |
|
2920 |
def BuildHooksEnv(self): |
2921 |
"""Build hooks env.
|
2922 |
|
2923 |
This runs on master, primary and secondary nodes of the instance.
|
2924 |
|
2925 |
"""
|
2926 |
env = _BuildInstanceHookEnvByObject(self, self.instance) |
2927 |
nl = [self.cfg.GetMasterNode()]
|
2928 |
return env, nl, nl
|
2929 |
|
2930 |
def CheckPrereq(self): |
2931 |
"""Check prerequisites.
|
2932 |
|
2933 |
This checks that the instance is in the cluster.
|
2934 |
|
2935 |
"""
|
2936 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
2937 |
assert self.instance is not None, \ |
2938 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2939 |
|
2940 |
def Exec(self, feedback_fn): |
2941 |
"""Remove the instance.
|
2942 |
|
2943 |
"""
|
2944 |
instance = self.instance
|
2945 |
logging.info("Shutting down instance %s on node %s",
|
2946 |
instance.name, instance.primary_node) |
2947 |
|
2948 |
result = self.rpc.call_instance_shutdown(instance.primary_node, instance)
|
2949 |
if result.failed or not result.data: |
2950 |
if self.op.ignore_failures: |
2951 |
feedback_fn("Warning: can't shutdown instance")
|
2952 |
else:
|
2953 |
raise errors.OpExecError("Could not shutdown instance %s on node %s" % |
2954 |
(instance.name, instance.primary_node)) |
2955 |
|
2956 |
logging.info("Removing block devices for instance %s", instance.name)
|
2957 |
|
2958 |
if not _RemoveDisks(self, instance): |
2959 |
if self.op.ignore_failures: |
2960 |
feedback_fn("Warning: can't remove instance's disks")
|
2961 |
else:
|
2962 |
raise errors.OpExecError("Can't remove instance's disks") |
2963 |
|
2964 |
logging.info("Removing instance %s out of cluster config", instance.name)
|
2965 |
|
2966 |
self.cfg.RemoveInstance(instance.name)
|
2967 |
self.remove_locks[locking.LEVEL_INSTANCE] = instance.name
|
2968 |
|
2969 |
|
2970 |
class LUQueryInstances(NoHooksLU): |
2971 |
"""Logical unit for querying instances.
|
2972 |
|
2973 |
"""
|
2974 |
_OP_REQP = ["output_fields", "names"] |
2975 |
REQ_BGL = False
|
2976 |
_FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes", |
2977 |
"admin_state", "admin_ram", |
2978 |
"disk_template", "ip", "mac", "bridge", |
2979 |
"sda_size", "sdb_size", "vcpus", "tags", |
2980 |
"network_port", "beparams", |
2981 |
"(disk).(size)/([0-9]+)",
|
2982 |
"(disk).(sizes)",
|
2983 |
"(nic).(mac|ip|bridge)/([0-9]+)",
|
2984 |
"(nic).(macs|ips|bridges)",
|
2985 |
"(disk|nic).(count)",
|
2986 |
"serial_no", "hypervisor", "hvparams",] + |
2987 |
["hv/%s" % name
|
2988 |
for name in constants.HVS_PARAMETERS] + |
2989 |
["be/%s" % name
|
2990 |
for name in constants.BES_PARAMETERS]) |
2991 |
_FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status") |
2992 |
|
2993 |
|
2994 |
def ExpandNames(self): |
2995 |
_CheckOutputFields(static=self._FIELDS_STATIC,
|
2996 |
dynamic=self._FIELDS_DYNAMIC,
|
2997 |
selected=self.op.output_fields)
|
2998 |
|
2999 |
self.needed_locks = {}
|
3000 |
self.share_locks[locking.LEVEL_INSTANCE] = 1 |
3001 |
self.share_locks[locking.LEVEL_NODE] = 1 |
3002 |
|
3003 |
if self.op.names: |
3004 |
self.wanted = _GetWantedInstances(self, self.op.names) |
3005 |
else:
|
3006 |
self.wanted = locking.ALL_SET
|
3007 |
|
3008 |
self.do_locking = self._FIELDS_STATIC.NonMatching(self.op.output_fields) |
3009 |
if self.do_locking: |
3010 |
self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted |
3011 |
self.needed_locks[locking.LEVEL_NODE] = []
|
3012 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
3013 |
|
3014 |
def DeclareLocks(self, level): |
3015 |
if level == locking.LEVEL_NODE and self.do_locking: |
3016 |
self._LockInstancesNodes()
|
3017 |
|
3018 |
def CheckPrereq(self): |
3019 |
"""Check prerequisites.
|
3020 |
|
3021 |
"""
|
3022 |
pass
|
3023 |
|
3024 |
def Exec(self, feedback_fn): |
3025 |
"""Computes the list of nodes and their attributes.
|
3026 |
|
3027 |
"""
|
3028 |
all_info = self.cfg.GetAllInstancesInfo()
|
3029 |
if self.do_locking: |
3030 |
instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
|
3031 |
elif self.wanted != locking.ALL_SET: |
3032 |
instance_names = self.wanted
|
3033 |
missing = set(instance_names).difference(all_info.keys())
|
3034 |
if missing:
|
3035 |
raise errors.OpExecError(
|
3036 |
"Some instances were removed before retrieving their data: %s"
|
3037 |
% missing) |
3038 |
else:
|
3039 |
instance_names = all_info.keys() |
3040 |
|
3041 |
instance_names = utils.NiceSort(instance_names) |
3042 |
instance_list = [all_info[iname] for iname in instance_names] |
3043 |
|
3044 |
# begin data gathering
|
3045 |
|
3046 |
nodes = frozenset([inst.primary_node for inst in instance_list]) |
3047 |
hv_list = list(set([inst.hypervisor for inst in instance_list])) |
3048 |
|
3049 |
bad_nodes = [] |
3050 |
off_nodes = [] |
3051 |
if self.do_locking: |
3052 |
live_data = {} |
3053 |
node_data = self.rpc.call_all_instances_info(nodes, hv_list)
|
3054 |
for name in nodes: |
3055 |
result = node_data[name] |
3056 |
if result.offline:
|
3057 |
# offline nodes will be in both lists
|
3058 |
off_nodes.append(name) |
3059 |
if result.failed:
|
3060 |
bad_nodes.append(name) |
3061 |
else:
|
3062 |
if result.data:
|
3063 |
live_data.update(result.data) |
3064 |
# else no instance is alive
|
3065 |
else:
|
3066 |
live_data = dict([(name, {}) for name in instance_names]) |
3067 |
|
3068 |
# end data gathering
|
3069 |
|
3070 |
HVPREFIX = "hv/"
|
3071 |
BEPREFIX = "be/"
|
3072 |
output = [] |
3073 |
for instance in instance_list: |
3074 |
iout = [] |
3075 |
i_hv = self.cfg.GetClusterInfo().FillHV(instance)
|
3076 |
i_be = self.cfg.GetClusterInfo().FillBE(instance)
|
3077 |
for field in self.op.output_fields: |
3078 |
st_match = self._FIELDS_STATIC.Matches(field)
|
3079 |
if field == "name": |
3080 |
val = instance.name |
3081 |
elif field == "os": |
3082 |
val = instance.os |
3083 |
elif field == "pnode": |
3084 |
val = instance.primary_node |
3085 |
elif field == "snodes": |
3086 |
val = list(instance.secondary_nodes)
|
3087 |
elif field == "admin_state": |
3088 |
val = (instance.status != "down")
|
3089 |
elif field == "oper_state": |
3090 |
if instance.primary_node in bad_nodes: |
3091 |
val = None
|
3092 |
else:
|
3093 |
val = bool(live_data.get(instance.name))
|
3094 |
elif field == "status": |
3095 |
if instance.primary_node in off_nodes: |
3096 |
val = "ERROR_nodeoffline"
|
3097 |
elif instance.primary_node in bad_nodes: |
3098 |
val = "ERROR_nodedown"
|
3099 |
else:
|
3100 |
running = bool(live_data.get(instance.name))
|
3101 |
if running:
|
3102 |
if instance.status != "down": |
3103 |
val = "running"
|
3104 |
else:
|
3105 |
val = "ERROR_up"
|
3106 |
else:
|
3107 |
if instance.status != "down": |
3108 |
val = "ERROR_down"
|
3109 |
else:
|
3110 |
val = "ADMIN_down"
|
3111 |
elif field == "oper_ram": |
3112 |
if instance.primary_node in bad_nodes: |
3113 |
val = None
|
3114 |
elif instance.name in live_data: |
3115 |
val = live_data[instance.name].get("memory", "?") |
3116 |
else:
|
3117 |
val = "-"
|
3118 |
elif field == "disk_template": |
3119 |
val = instance.disk_template |
3120 |
elif field == "ip": |
3121 |
val = instance.nics[0].ip
|
3122 |
elif field == "bridge": |
3123 |
val = instance.nics[0].bridge
|
3124 |
elif field == "mac": |
3125 |
val = instance.nics[0].mac
|
3126 |
elif field == "sda_size" or field == "sdb_size": |
3127 |
idx = ord(field[2]) - ord('a') |
3128 |
try:
|
3129 |
val = instance.FindDisk(idx).size |
3130 |
except errors.OpPrereqError:
|
3131 |
val = None
|
3132 |
elif field == "tags": |
3133 |
val = list(instance.GetTags())
|
3134 |
elif field == "serial_no": |
3135 |
val = instance.serial_no |
3136 |
elif field == "network_port": |
3137 |
val = instance.network_port |
3138 |
elif field == "hypervisor": |
3139 |
val = instance.hypervisor |
3140 |
elif field == "hvparams": |
3141 |
val = i_hv |
3142 |
elif (field.startswith(HVPREFIX) and |
3143 |
field[len(HVPREFIX):] in constants.HVS_PARAMETERS): |
3144 |
val = i_hv.get(field[len(HVPREFIX):], None) |
3145 |
elif field == "beparams": |
3146 |
val = i_be |
3147 |
elif (field.startswith(BEPREFIX) and |
3148 |
field[len(BEPREFIX):] in constants.BES_PARAMETERS): |
3149 |
val = i_be.get(field[len(BEPREFIX):], None) |
3150 |
elif st_match and st_match.groups(): |
3151 |
# matches a variable list
|
3152 |
st_groups = st_match.groups() |
3153 |
if st_groups and st_groups[0] == "disk": |
3154 |
if st_groups[1] == "count": |
3155 |
val = len(instance.disks)
|
3156 |
elif st_groups[1] == "sizes": |
3157 |
val = [disk.size for disk in instance.disks] |
3158 |
elif st_groups[1] == "size": |
3159 |
try:
|
3160 |
val = instance.FindDisk(st_groups[2]).size
|
3161 |
except errors.OpPrereqError:
|
3162 |
val = None
|
3163 |
else:
|
3164 |
assert False, "Unhandled disk parameter" |
3165 |
elif st_groups[0] == "nic": |
3166 |
if st_groups[1] == "count": |
3167 |
val = len(instance.nics)
|
3168 |
elif st_groups[1] == "macs": |
3169 |
val = [nic.mac for nic in instance.nics] |
3170 |
elif st_groups[1] == "ips": |
3171 |
val = [nic.ip for nic in instance.nics] |
3172 |
elif st_groups[1] == "bridges": |
3173 |
val = [nic.bridge for nic in instance.nics] |
3174 |
else:
|
3175 |
# index-based item
|
3176 |
nic_idx = int(st_groups[2]) |
3177 |
if nic_idx >= len(instance.nics): |
3178 |
val = None
|
3179 |
else:
|
3180 |
if st_groups[1] == "mac": |
3181 |
val = instance.nics[nic_idx].mac |
3182 |
elif st_groups[1] == "ip": |
3183 |
val = instance.nics[nic_idx].ip |
3184 |
elif st_groups[1] == "bridge": |
3185 |
val = instance.nics[nic_idx].bridge |
3186 |
else:
|
3187 |
assert False, "Unhandled NIC parameter" |
3188 |
else:
|
3189 |
assert False, "Unhandled variable parameter" |
3190 |
else:
|
3191 |
raise errors.ParameterError(field)
|
3192 |
iout.append(val) |
3193 |
output.append(iout) |
3194 |
|
3195 |
return output
|
3196 |
|
3197 |
|
3198 |
class LUFailoverInstance(LogicalUnit): |
3199 |
"""Failover an instance.
|
3200 |
|
3201 |
"""
|
3202 |
HPATH = "instance-failover"
|
3203 |
HTYPE = constants.HTYPE_INSTANCE |
3204 |
_OP_REQP = ["instance_name", "ignore_consistency"] |
3205 |
REQ_BGL = False
|
3206 |
|
3207 |
def ExpandNames(self): |
3208 |
self._ExpandAndLockInstance()
|
3209 |
self.needed_locks[locking.LEVEL_NODE] = []
|
3210 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
3211 |
|
3212 |
def DeclareLocks(self, level): |
3213 |
if level == locking.LEVEL_NODE:
|
3214 |
self._LockInstancesNodes()
|
3215 |
|
3216 |
def BuildHooksEnv(self): |
3217 |
"""Build hooks env.
|
3218 |
|
3219 |
This runs on master, primary and secondary nodes of the instance.
|
3220 |
|
3221 |
"""
|
3222 |
env = { |
3223 |
"IGNORE_CONSISTENCY": self.op.ignore_consistency, |
3224 |
} |
3225 |
env.update(_BuildInstanceHookEnvByObject(self, self.instance)) |
3226 |
nl = [self.cfg.GetMasterNode()] + list(self.instance.secondary_nodes) |
3227 |
return env, nl, nl
|
3228 |
|
3229 |
def CheckPrereq(self): |
3230 |
"""Check prerequisites.
|
3231 |
|
3232 |
This checks that the instance is in the cluster.
|
3233 |
|
3234 |
"""
|
3235 |
self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
3236 |
assert self.instance is not None, \ |
3237 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
3238 |
|
3239 |
bep = self.cfg.GetClusterInfo().FillBE(instance)
|
3240 |
if instance.disk_template not in constants.DTS_NET_MIRROR: |
3241 |
raise errors.OpPrereqError("Instance's disk layout is not" |
3242 |
" network mirrored, cannot failover.")
|
3243 |
|
3244 |
secondary_nodes = instance.secondary_nodes |
3245 |
if not secondary_nodes: |
3246 |
raise errors.ProgrammerError("no secondary node but using " |
3247 |
"a mirrored disk template")
|
3248 |
|
3249 |
target_node = secondary_nodes[0]
|
3250 |
_CheckNodeOnline(self, target_node)
|
3251 |
# check memory requirements on the secondary node
|
3252 |
_CheckNodeFreeMemory(self, target_node, "failing over instance %s" % |
3253 |
instance.name, bep[constants.BE_MEMORY], |
3254 |
instance.hypervisor) |
3255 |
|
3256 |
# check bridge existance
|
3257 |
brlist = [nic.bridge for nic in instance.nics] |
3258 |
result = self.rpc.call_bridges_exist(target_node, brlist)
|
3259 |
result.Raise() |
3260 |
if not result.data: |
3261 |
raise errors.OpPrereqError("One or more target bridges %s does not" |
3262 |
" exist on destination node '%s'" %
|
3263 |
(brlist, target_node)) |
3264 |
|
3265 |
def Exec(self, feedback_fn): |
3266 |
"""Failover an instance.
|
3267 |
|
3268 |
The failover is done by shutting it down on its present node and
|
3269 |
starting it on the secondary.
|
3270 |
|
3271 |
"""
|
3272 |
instance = self.instance
|
3273 |
|
3274 |
source_node = instance.primary_node |
3275 |
target_node = instance.secondary_nodes[0]
|
3276 |
|
3277 |
feedback_fn("* checking disk consistency between source and target")
|
3278 |
for dev in instance.disks: |
3279 |
# for drbd, these are drbd over lvm
|
3280 |
if not _CheckDiskConsistency(self, dev, target_node, False): |
3281 |
if instance.status == "up" and not self.op.ignore_consistency: |
3282 |
raise errors.OpExecError("Disk %s is degraded on target node," |
3283 |
" aborting failover." % dev.iv_name)
|
3284 |
|
3285 |
feedback_fn("* shutting down instance on source node")
|
3286 |
logging.info("Shutting down instance %s on node %s",
|
3287 |
instance.name, source_node) |
3288 |
|
3289 |
result = self.rpc.call_instance_shutdown(source_node, instance)
|
3290 |
if result.failed or not result.data: |
3291 |
if self.op.ignore_consistency: |
3292 |
self.proc.LogWarning("Could not shutdown instance %s on node %s." |
3293 |
" Proceeding"
|
3294 |
" anyway. Please make sure node %s is down",
|
3295 |
instance.name, source_node, source_node) |
3296 |
else:
|
3297 |
raise errors.OpExecError("Could not shutdown instance %s on node %s" % |
3298 |
(instance.name, source_node)) |
3299 |
|
3300 |
feedback_fn("* deactivating the instance's disks on source node")
|
3301 |
if not _ShutdownInstanceDisks(self, instance, ignore_primary=True): |
3302 |
raise errors.OpExecError("Can't shut down the instance's disks.") |
3303 |
|
3304 |
instance.primary_node = target_node |
3305 |
# distribute new instance config to the other nodes
|
3306 |
self.cfg.Update(instance)
|
3307 |
|
3308 |
# Only start the instance if it's marked as up
|
3309 |
if instance.status == "up": |
3310 |
feedback_fn("* activating the instance's disks on target node")
|
3311 |
logging.info("Starting instance %s on node %s",
|
3312 |
instance.name, target_node) |
3313 |
|
3314 |
disks_ok, dummy = _AssembleInstanceDisks(self, instance,
|
3315 |
ignore_secondaries=True)
|
3316 |
if not disks_ok: |
3317 |
_ShutdownInstanceDisks(self, instance)
|
3318 |
raise errors.OpExecError("Can't activate the instance's disks") |
3319 |
|
3320 |
feedback_fn("* starting the instance on the target node")
|
3321 |
result = self.rpc.call_instance_start(target_node, instance, None) |
3322 |
if result.failed or not result.data: |
3323 |
_ShutdownInstanceDisks(self, instance)
|
3324 |
raise errors.OpExecError("Could not start instance %s on node %s." % |
3325 |
(instance.name, target_node)) |
3326 |
|
3327 |
|
3328 |
def _CreateBlockDevOnPrimary(lu, node, instance, device, info): |
3329 |
"""Create a tree of block devices on the primary node.
|
3330 |
|
3331 |
This always creates all devices.
|
3332 |
|
3333 |
"""
|
3334 |
if device.children:
|
3335 |
for child in device.children: |
3336 |
if not _CreateBlockDevOnPrimary(lu, node, instance, child, info): |
3337 |
return False |
3338 |
|
3339 |
lu.cfg.SetDiskID(device, node) |
3340 |
new_id = lu.rpc.call_blockdev_create(node, device, device.size, |
3341 |
instance.name, True, info)
|
3342 |
if new_id.failed or not new_id.data: |
3343 |
return False |
3344 |
if device.physical_id is None: |
3345 |
device.physical_id = new_id |
3346 |
return True |
3347 |
|
3348 |
|
3349 |
def _CreateBlockDevOnSecondary(lu, node, instance, device, force, info): |
3350 |
"""Create a tree of block devices on a secondary node.
|
3351 |
|
3352 |
If this device type has to be created on secondaries, create it and
|
3353 |
all its children.
|
3354 |
|
3355 |
If not, just recurse to children keeping the same 'force' value.
|
3356 |
|
3357 |
"""
|
3358 |
if device.CreateOnSecondary():
|
3359 |
force = True
|
3360 |
if device.children:
|
3361 |
for child in device.children: |
3362 |
if not _CreateBlockDevOnSecondary(lu, node, instance, |
3363 |
child, force, info): |
3364 |
return False |
3365 |
|
3366 |
if not force: |
3367 |
return True |
3368 |
lu.cfg.SetDiskID(device, node) |
3369 |
new_id = lu.rpc.call_blockdev_create(node, device, device.size, |
3370 |
instance.name, False, info)
|
3371 |
if new_id.failed or not new_id.data: |
3372 |
return False |
3373 |
if device.physical_id is None: |
3374 |
device.physical_id = new_id |
3375 |
return True |
3376 |
|
3377 |
|
3378 |
def _GenerateUniqueNames(lu, exts): |
3379 |
"""Generate a suitable LV name.
|
3380 |
|
3381 |
This will generate a logical volume name for the given instance.
|
3382 |
|
3383 |
"""
|
3384 |
results = [] |
3385 |
for val in exts: |
3386 |
new_id = lu.cfg.GenerateUniqueID() |
3387 |
results.append("%s%s" % (new_id, val))
|
3388 |
return results
|
3389 |
|
3390 |
|
3391 |
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name, |
3392 |
p_minor, s_minor): |
3393 |
"""Generate a drbd8 device complete with its children.
|
3394 |
|
3395 |
"""
|
3396 |
port = lu.cfg.AllocatePort() |
3397 |
vgname = lu.cfg.GetVGName() |
3398 |
shared_secret = lu.cfg.GenerateDRBDSecret() |
3399 |
dev_data = objects.Disk(dev_type=constants.LD_LV, size=size, |
3400 |
logical_id=(vgname, names[0]))
|
3401 |
dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
|
3402 |
logical_id=(vgname, names[1]))
|
3403 |
drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size, |
3404 |
logical_id=(primary, secondary, port, |
3405 |
p_minor, s_minor, |
3406 |
shared_secret), |
3407 |
children=[dev_data, dev_meta], |
3408 |
iv_name=iv_name) |
3409 |
return drbd_dev
|
3410 |
|
3411 |
|
3412 |
def _GenerateDiskTemplate(lu, template_name, |
3413 |
instance_name, primary_node, |
3414 |
secondary_nodes, disk_info, |
3415 |
file_storage_dir, file_driver, |
3416 |
base_index): |
3417 |
"""Generate the entire disk layout for a given template type.
|
3418 |
|
3419 |
"""
|
3420 |
#TODO: compute space requirements
|
3421 |
|
3422 |
vgname = lu.cfg.GetVGName() |
3423 |
disk_count = len(disk_info)
|
3424 |
disks = [] |
3425 |
if template_name == constants.DT_DISKLESS:
|
3426 |
pass
|
3427 |
elif template_name == constants.DT_PLAIN:
|
3428 |
if len(secondary_nodes) != 0: |
3429 |
raise errors.ProgrammerError("Wrong template configuration") |
3430 |
|
3431 |
names = _GenerateUniqueNames(lu, [".disk%d" % i
|
3432 |
for i in range(disk_count)]) |
3433 |
for idx, disk in enumerate(disk_info): |
3434 |
disk_index = idx + base_index |
3435 |
disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
|
3436 |
logical_id=(vgname, names[idx]), |
3437 |
iv_name="disk/%d" % disk_index)
|
3438 |
disks.append(disk_dev) |
3439 |
elif template_name == constants.DT_DRBD8:
|
3440 |
if len(secondary_nodes) != 1: |
3441 |
raise errors.ProgrammerError("Wrong template configuration") |
3442 |
remote_node = secondary_nodes[0]
|
3443 |
minors = lu.cfg.AllocateDRBDMinor( |
3444 |
[primary_node, remote_node] * len(disk_info), instance_name)
|
3445 |
|
3446 |
names = _GenerateUniqueNames(lu, |
3447 |
[".disk%d_%s" % (i, s)
|
3448 |
for i in range(disk_count) |
3449 |
for s in ("data", "meta") |
3450 |
]) |
3451 |
for idx, disk in enumerate(disk_info): |
3452 |
disk_index = idx + base_index |
3453 |
disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node, |
3454 |
disk["size"], names[idx*2:idx*2+2], |
3455 |
"disk/%d" % disk_index,
|
3456 |
minors[idx*2], minors[idx*2+1]) |
3457 |
disks.append(disk_dev) |
3458 |
elif template_name == constants.DT_FILE:
|
3459 |
if len(secondary_nodes) != 0: |
3460 |
raise errors.ProgrammerError("Wrong template configuration") |
3461 |
|
3462 |
for idx, disk in enumerate(disk_info): |
3463 |
disk_index = idx + base_index |
3464 |
disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
|
3465 |
iv_name="disk/%d" % disk_index,
|
3466 |
logical_id=(file_driver, |
3467 |
"%s/disk%d" % (file_storage_dir,
|
3468 |
idx))) |
3469 |
disks.append(disk_dev) |
3470 |
else:
|
3471 |
raise errors.ProgrammerError("Invalid disk template '%s'" % template_name) |
3472 |
return disks
|
3473 |
|
3474 |
|
3475 |
def _GetInstanceInfoText(instance): |
3476 |
"""Compute that text that should be added to the disk's metadata.
|
3477 |
|
3478 |
"""
|
3479 |
return "originstname+%s" % instance.name |
3480 |
|
3481 |
|
3482 |
def _CreateDisks(lu, instance): |
3483 |
"""Create all disks for an instance.
|
3484 |
|
3485 |
This abstracts away some work from AddInstance.
|
3486 |
|
3487 |
@type lu: L{LogicalUnit}
|
3488 |
@param lu: the logical unit on whose behalf we execute
|
3489 |
@type instance: L{objects.Instance}
|
3490 |
@param instance: the instance whose disks we should create
|
3491 |
@rtype: boolean
|
3492 |
@return: the success of the creation
|
3493 |
|
3494 |
"""
|
3495 |
info = _GetInstanceInfoText(instance) |
3496 |
|
3497 |
if instance.disk_template == constants.DT_FILE:
|
3498 |
file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1]) |
3499 |
result = lu.rpc.call_file_storage_dir_create(instance.primary_node, |
3500 |
file_storage_dir) |
3501 |
|
3502 |
if result.failed or not result.data: |
3503 |
logging.error("Could not connect to node '%s'", instance.primary_node)
|
3504 |
return False |
3505 |
|
3506 |
if not result.data[0]: |
3507 |
logging.error("Failed to create directory '%s'", file_storage_dir)
|
3508 |
return False |
3509 |
|
3510 |
# Note: this needs to be kept in sync with adding of disks in
|
3511 |
# LUSetInstanceParams
|
3512 |
for device in instance.disks: |
3513 |
logging.info("Creating volume %s for instance %s",
|
3514 |
device.iv_name, instance.name) |
3515 |
#HARDCODE
|
3516 |
for secondary_node in instance.secondary_nodes: |
3517 |
if not _CreateBlockDevOnSecondary(lu, secondary_node, instance, |
3518 |
device, False, info):
|
3519 |
logging.error("Failed to create volume %s (%s) on secondary node %s!",
|
3520 |
device.iv_name, device, secondary_node) |
3521 |
return False |
3522 |
#HARDCODE
|
3523 |
if not _CreateBlockDevOnPrimary(lu, instance.primary_node, |
3524 |
instance, device, info): |
3525 |
logging.error("Failed to create volume %s on primary!", device.iv_name)
|
3526 |
return False |
3527 |
|
3528 |
return True |
3529 |
|
3530 |
|
3531 |
def _RemoveDisks(lu, instance): |
3532 |
"""Remove all disks for an instance.
|
3533 |
|
3534 |
This abstracts away some work from `AddInstance()` and
|
3535 |
`RemoveInstance()`. Note that in case some of the devices couldn't
|
3536 |
be removed, the removal will continue with the other ones (compare
|
3537 |
with `_CreateDisks()`).
|
3538 |
|
3539 |
@type lu: L{LogicalUnit}
|
3540 |
@param lu: the logical unit on whose behalf we execute
|
3541 |
@type instance: L{objects.Instance}
|
3542 |
@param instance: the instance whose disks we should remove
|
3543 |
@rtype: boolean
|
3544 |
@return: the success of the removal
|
3545 |
|
3546 |
"""
|
3547 |
logging.info("Removing block devices for instance %s", instance.name)
|
3548 |
|
3549 |
result = True
|
3550 |
for device in instance.disks: |
3551 |
for node, disk in device.ComputeNodeTree(instance.primary_node): |
3552 |
lu.cfg.SetDiskID(disk, node) |
3553 |
result = lu.rpc.call_blockdev_remove(node, disk) |
3554 |
if result.failed or not result.data: |
3555 |
lu.proc.LogWarning("Could not remove block device %s on node %s,"
|
3556 |
" continuing anyway", device.iv_name, node)
|
3557 |
result = False
|
3558 |
|
3559 |
if instance.disk_template == constants.DT_FILE:
|
3560 |
file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1]) |
3561 |
result = lu.rpc.call_file_storage_dir_remove(instance.primary_node, |
3562 |
file_storage_dir) |
3563 |
if result.failed or not result.data: |
3564 |
logging.error("Could not remove directory '%s'", file_storage_dir)
|
3565 |
result = False
|
3566 |
|
3567 |
return result
|
3568 |
|
3569 |
|
3570 |
def _ComputeDiskSize(disk_template, disks): |
3571 |
"""Compute disk size requirements in the volume group
|
3572 |
|
3573 |
"""
|
3574 |
# Required free disk space as a function of disk and swap space
|
3575 |
req_size_dict = { |
3576 |
constants.DT_DISKLESS: None,
|
3577 |
constants.DT_PLAIN: sum(d["size"] for d in disks), |
3578 |
# 128 MB are added for drbd metadata for each disk
|
3579 |
constants.DT_DRBD8: sum(d["size"] + 128 for d in disks), |
3580 |
constants.DT_FILE: None,
|
3581 |
} |
3582 |
|
3583 |
if disk_template not in req_size_dict: |
3584 |
raise errors.ProgrammerError("Disk template '%s' size requirement" |
3585 |
" is unknown" % disk_template)
|
3586 |
|
3587 |
return req_size_dict[disk_template]
|
3588 |
|
3589 |
|
3590 |
def _CheckHVParams(lu, nodenames, hvname, hvparams): |
3591 |
"""Hypervisor parameter validation.
|
3592 |
|
3593 |
This function abstract the hypervisor parameter validation to be
|
3594 |
used in both instance create and instance modify.
|
3595 |
|
3596 |
@type lu: L{LogicalUnit}
|
3597 |
@param lu: the logical unit for which we check
|
3598 |
@type nodenames: list
|
3599 |
@param nodenames: the list of nodes on which we should check
|
3600 |
@type hvname: string
|
3601 |
@param hvname: the name of the hypervisor we should use
|
3602 |
@type hvparams: dict
|
3603 |
@param hvparams: the parameters which we need to check
|
3604 |
@raise errors.OpPrereqError: if the parameters are not valid
|
3605 |
|
3606 |
"""
|
3607 |
hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames, |
3608 |
hvname, |
3609 |
hvparams) |
3610 |
for node in nodenames: |
3611 |
info = hvinfo[node] |
3612 |
info.Raise() |
3613 |
if not info.data or not isinstance(info.data, (tuple, list)): |
3614 |
raise errors.OpPrereqError("Cannot get current information" |
3615 |
" from node '%s' (%s)" % (node, info.data))
|
3616 |
if not info.data[0]: |
3617 |
raise errors.OpPrereqError("Hypervisor parameter validation failed:" |
3618 |
" %s" % info.data[1]) |
3619 |
|
3620 |
|
3621 |
class LUCreateInstance(LogicalUnit): |
3622 |
"""Create an instance.
|
3623 |
|
3624 |
"""
|
3625 |
HPATH = "instance-add"
|
3626 |
HTYPE = constants.HTYPE_INSTANCE |
3627 |
_OP_REQP = ["instance_name", "disks", "disk_template", |
3628 |
"mode", "start", |
3629 |
"wait_for_sync", "ip_check", "nics", |
3630 |
"hvparams", "beparams"] |
3631 |
REQ_BGL = False
|
3632 |
|
3633 |
def _ExpandNode(self, node): |
3634 |
"""Expands and checks one node name.
|
3635 |
|
3636 |
"""
|
3637 |
node_full = self.cfg.ExpandNodeName(node)
|
3638 |
if node_full is None: |
3639 |
raise errors.OpPrereqError("Unknown node %s" % node) |
3640 |
return node_full
|
3641 |
|
3642 |
def ExpandNames(self): |
3643 |
"""ExpandNames for CreateInstance.
|
3644 |
|
3645 |
Figure out the right locks for instance creation.
|
3646 |
|
3647 |
"""
|
3648 |
self.needed_locks = {}
|
3649 |
|
3650 |
# set optional parameters to none if they don't exist
|
3651 |
for attr in ["pnode", "snode", "iallocator", "hypervisor"]: |
3652 |
if not hasattr(self.op, attr): |
3653 |
setattr(self.op, attr, None) |
3654 |
|
3655 |
# cheap checks, mostly valid constants given
|
3656 |
|
3657 |
# verify creation mode
|
3658 |
if self.op.mode not in (constants.INSTANCE_CREATE, |
3659 |
constants.INSTANCE_IMPORT): |
3660 |
raise errors.OpPrereqError("Invalid instance creation mode '%s'" % |
3661 |
self.op.mode)
|
3662 |
|
3663 |
# disk template and mirror node verification
|
3664 |
if self.op.disk_template not in constants.DISK_TEMPLATES: |
3665 |
raise errors.OpPrereqError("Invalid disk template name") |
3666 |
|
3667 |
if self.op.hypervisor is None: |
3668 |
self.op.hypervisor = self.cfg.GetHypervisorType() |
3669 |
|
3670 |
cluster = self.cfg.GetClusterInfo()
|
3671 |
enabled_hvs = cluster.enabled_hypervisors |
3672 |
if self.op.hypervisor not in enabled_hvs: |
3673 |
raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the" |
3674 |
" cluster (%s)" % (self.op.hypervisor, |
3675 |
",".join(enabled_hvs)))
|
3676 |
|
3677 |
# check hypervisor parameter syntax (locally)
|
3678 |
|
3679 |
filled_hvp = cluster.FillDict(cluster.hvparams[self.op.hypervisor],
|
3680 |
self.op.hvparams)
|
3681 |
hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
|
3682 |
hv_type.CheckParameterSyntax(filled_hvp) |
3683 |
|
3684 |
# fill and remember the beparams dict
|
3685 |
utils.CheckBEParams(self.op.beparams)
|
3686 |
self.be_full = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT],
|
3687 |
self.op.beparams)
|
3688 |
|
3689 |
#### instance parameters check
|
3690 |
|
3691 |
# instance name verification
|
3692 |
hostname1 = utils.HostInfo(self.op.instance_name)
|
3693 |
self.op.instance_name = instance_name = hostname1.name
|
3694 |
|
3695 |
# this is just a preventive check, but someone might still add this
|
3696 |
# instance in the meantime, and creation will fail at lock-add time
|
3697 |
if instance_name in self.cfg.GetInstanceList(): |
3698 |
raise errors.OpPrereqError("Instance '%s' is already in the cluster" % |
3699 |
instance_name) |
3700 |
|
3701 |
self.add_locks[locking.LEVEL_INSTANCE] = instance_name
|
3702 |
|
3703 |
# NIC buildup
|
3704 |
self.nics = []
|
3705 |
for nic in self.op.nics: |
3706 |
# ip validity checks
|
3707 |
ip = nic.get("ip", None) |
3708 |
if ip is None or ip.lower() == "none": |
3709 |
nic_ip = None
|
3710 |
elif ip.lower() == constants.VALUE_AUTO:
|
3711 |
nic_ip = hostname1.ip |
3712 |
else:
|
3713 |
if not utils.IsValidIP(ip): |
3714 |
raise errors.OpPrereqError("Given IP address '%s' doesn't look" |
3715 |
" like a valid IP" % ip)
|
3716 |
nic_ip = ip |
3717 |
|
3718 |
# MAC address verification
|
3719 |
mac = nic.get("mac", constants.VALUE_AUTO)
|
3720 |
if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
3721 |
if not utils.IsValidMac(mac.lower()): |
3722 |
raise errors.OpPrereqError("Invalid MAC address specified: %s" % |
3723 |
mac) |
3724 |
# bridge verification
|
3725 |
bridge = nic.get("bridge", self.cfg.GetDefBridge()) |
3726 |
self.nics.append(objects.NIC(mac=mac, ip=nic_ip, bridge=bridge))
|
3727 |
|
3728 |
# disk checks/pre-build
|
3729 |
self.disks = []
|
3730 |
for disk in self.op.disks: |
3731 |
mode = disk.get("mode", constants.DISK_RDWR)
|
3732 |
if mode not in constants.DISK_ACCESS_SET: |
3733 |
raise errors.OpPrereqError("Invalid disk access mode '%s'" % |
3734 |
mode) |
3735 |
size = disk.get("size", None) |
3736 |
if size is None: |
3737 |
raise errors.OpPrereqError("Missing disk size") |
3738 |
try:
|
3739 |
size = int(size)
|
3740 |
except ValueError: |
3741 |
raise errors.OpPrereqError("Invalid disk size '%s'" % size) |
3742 |
self.disks.append({"size": size, "mode": mode}) |
3743 |
|
3744 |
# used in CheckPrereq for ip ping check
|
3745 |
self.check_ip = hostname1.ip
|
3746 |
|
3747 |
# file storage checks
|
3748 |
if (self.op.file_driver and |
3749 |
not self.op.file_driver in constants.FILE_DRIVER): |
3750 |
raise errors.OpPrereqError("Invalid file driver name '%s'" % |
3751 |
self.op.file_driver)
|
3752 |
|
3753 |
if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir): |
3754 |
raise errors.OpPrereqError("File storage directory path not absolute") |
3755 |
|
3756 |
### Node/iallocator related checks
|
3757 |
if [self.op.iallocator, self.op.pnode].count(None) != 1: |
3758 |
raise errors.OpPrereqError("One and only one of iallocator and primary" |
3759 |
" node must be given")
|
3760 |
|
3761 |
if self.op.iallocator: |
3762 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
3763 |
else:
|
3764 |
self.op.pnode = self._ExpandNode(self.op.pnode) |
3765 |
nodelist = [self.op.pnode]
|
3766 |
if self.op.snode is not None: |
3767 |
self.op.snode = self._ExpandNode(self.op.snode) |
3768 |
nodelist.append(self.op.snode)
|
3769 |
self.needed_locks[locking.LEVEL_NODE] = nodelist
|
3770 |
|
3771 |
# in case of import lock the source node too
|
3772 |
if self.op.mode == constants.INSTANCE_IMPORT: |
3773 |
src_node = getattr(self.op, "src_node", None) |
3774 |
src_path = getattr(self.op, "src_path", None) |
3775 |
|
3776 |
if src_path is None: |
3777 |
self.op.src_path = src_path = self.op.instance_name |
3778 |
|
3779 |
if src_node is None: |
3780 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
3781 |
self.op.src_node = None |
3782 |
if os.path.isabs(src_path):
|
3783 |
raise errors.OpPrereqError("Importing an instance from an absolute" |
3784 |
" path requires a source node option.")
|
3785 |
else:
|
3786 |
self.op.src_node = src_node = self._ExpandNode(src_node) |
3787 |
if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET: |
3788 |
self.needed_locks[locking.LEVEL_NODE].append(src_node)
|
3789 |
if not os.path.isabs(src_path): |
3790 |
self.op.src_path = src_path = \
|
3791 |
os.path.join(constants.EXPORT_DIR, src_path) |
3792 |
|
3793 |
else: # INSTANCE_CREATE |
3794 |
if getattr(self.op, "os_type", None) is None: |
3795 |
raise errors.OpPrereqError("No guest OS specified") |
3796 |
|
3797 |
def _RunAllocator(self): |
3798 |
"""Run the allocator based on input opcode.
|
3799 |
|
3800 |
"""
|
3801 |
nics = [n.ToDict() for n in self.nics] |
3802 |
ial = IAllocator(self,
|
3803 |
mode=constants.IALLOCATOR_MODE_ALLOC, |
3804 |
name=self.op.instance_name,
|
3805 |
disk_template=self.op.disk_template,
|
3806 |
tags=[], |
3807 |
os=self.op.os_type,
|
3808 |
vcpus=self.be_full[constants.BE_VCPUS],
|
3809 |
mem_size=self.be_full[constants.BE_MEMORY],
|
3810 |
disks=self.disks,
|
3811 |
nics=nics, |
3812 |
hypervisor=self.op.hypervisor,
|
3813 |
) |
3814 |
|
3815 |
ial.Run(self.op.iallocator)
|
3816 |
|
3817 |
if not ial.success: |
3818 |
raise errors.OpPrereqError("Can't compute nodes using" |
3819 |
" iallocator '%s': %s" % (self.op.iallocator, |
3820 |
ial.info)) |
3821 |
if len(ial.nodes) != ial.required_nodes: |
3822 |
raise errors.OpPrereqError("iallocator '%s' returned invalid number" |
3823 |
" of nodes (%s), required %s" %
|
3824 |
(self.op.iallocator, len(ial.nodes), |
3825 |
ial.required_nodes)) |
3826 |
self.op.pnode = ial.nodes[0] |
3827 |
self.LogInfo("Selected nodes for instance %s via iallocator %s: %s", |
3828 |
self.op.instance_name, self.op.iallocator, |
3829 |
", ".join(ial.nodes))
|
3830 |
if ial.required_nodes == 2: |
3831 |
self.op.snode = ial.nodes[1] |
3832 |
|
3833 |
def BuildHooksEnv(self): |
3834 |
"""Build hooks env.
|
3835 |
|
3836 |
This runs on master, primary and secondary nodes of the instance.
|
3837 |
|
3838 |
"""
|
3839 |
env = { |
3840 |
"INSTANCE_DISK_TEMPLATE": self.op.disk_template, |
3841 |
"INSTANCE_DISK_SIZE": ",".join(str(d["size"]) for d in self.disks), |
3842 |
"INSTANCE_ADD_MODE": self.op.mode, |
3843 |
} |
3844 |
if self.op.mode == constants.INSTANCE_IMPORT: |
3845 |
env["INSTANCE_SRC_NODE"] = self.op.src_node |
3846 |
env["INSTANCE_SRC_PATH"] = self.op.src_path |
3847 |
env["INSTANCE_SRC_IMAGES"] = self.src_images |
3848 |
|
3849 |
env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
|
3850 |
primary_node=self.op.pnode,
|
3851 |
secondary_nodes=self.secondaries,
|
3852 |
status=self.instance_status,
|
3853 |
os_type=self.op.os_type,
|
3854 |
memory=self.be_full[constants.BE_MEMORY],
|
3855 |
vcpus=self.be_full[constants.BE_VCPUS],
|
3856 |
nics=[(n.ip, n.bridge, n.mac) for n in self.nics], |
3857 |
)) |
3858 |
|
3859 |
nl = ([self.cfg.GetMasterNode(), self.op.pnode] + |
3860 |
self.secondaries)
|
3861 |
return env, nl, nl
|
3862 |
|
3863 |
|
3864 |
def CheckPrereq(self): |
3865 |
"""Check prerequisites.
|
3866 |
|
3867 |
"""
|
3868 |
if (not self.cfg.GetVGName() and |
3869 |
self.op.disk_template not in constants.DTS_NOT_LVM): |
3870 |
raise errors.OpPrereqError("Cluster does not support lvm-based" |
3871 |
" instances")
|
3872 |
|
3873 |
|
3874 |
if self.op.mode == constants.INSTANCE_IMPORT: |
3875 |
src_node = self.op.src_node
|
3876 |
src_path = self.op.src_path
|
3877 |
|
3878 |
if src_node is None: |
3879 |
exp_list = self.rpc.call_export_list(
|
3880 |
self.acquired_locks[locking.LEVEL_NODE])
|
3881 |
found = False
|
3882 |
for node in exp_list: |
3883 |
if not exp_list[node].failed and src_path in exp_list[node].data: |
3884 |
found = True
|
3885 |
self.op.src_node = src_node = node
|
3886 |
self.op.src_path = src_path = os.path.join(constants.EXPORT_DIR,
|
3887 |
src_path) |
3888 |
break
|
3889 |
if not found: |
3890 |
raise errors.OpPrereqError("No export found for relative path %s" % |
3891 |
src_path) |
3892 |
|
3893 |
_CheckNodeOnline(self, src_node)
|
3894 |
result = self.rpc.call_export_info(src_node, src_path)
|
3895 |
result.Raise() |
3896 |
if not result.data: |
3897 |
raise errors.OpPrereqError("No export found in dir %s" % src_path) |
3898 |
|
3899 |
export_info = result.data |
3900 |
if not export_info.has_section(constants.INISECT_EXP): |
3901 |
raise errors.ProgrammerError("Corrupted export config") |
3902 |
|
3903 |
ei_version = export_info.get(constants.INISECT_EXP, 'version')
|
3904 |
if (int(ei_version) != constants.EXPORT_VERSION): |
3905 |
raise errors.OpPrereqError("Wrong export version %s (wanted %d)" % |
3906 |
(ei_version, constants.EXPORT_VERSION)) |
3907 |
|
3908 |
# Check that the new instance doesn't have less disks than the export
|
3909 |
instance_disks = len(self.disks) |
3910 |
export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
|
3911 |
if instance_disks < export_disks:
|
3912 |
raise errors.OpPrereqError("Not enough disks to import." |
3913 |
" (instance: %d, export: %d)" %
|
3914 |
(instance_disks, export_disks)) |
3915 |
|
3916 |
self.op.os_type = export_info.get(constants.INISECT_EXP, 'os') |
3917 |
disk_images = [] |
3918 |
for idx in range(export_disks): |
3919 |
option = 'disk%d_dump' % idx
|
3920 |
if export_info.has_option(constants.INISECT_INS, option):
|
3921 |
# FIXME: are the old os-es, disk sizes, etc. useful?
|
3922 |
export_name = export_info.get(constants.INISECT_INS, option) |
3923 |
image = os.path.join(src_path, export_name) |
3924 |
disk_images.append(image) |
3925 |
else:
|
3926 |
disk_images.append(False)
|
3927 |
|
3928 |
self.src_images = disk_images
|
3929 |
|
3930 |
old_name = export_info.get(constants.INISECT_INS, 'name')
|
3931 |
# FIXME: int() here could throw a ValueError on broken exports
|
3932 |
exp_nic_count = int(export_info.get(constants.INISECT_INS, 'nic_count')) |
3933 |
if self.op.instance_name == old_name: |
3934 |
for idx, nic in enumerate(self.nics): |
3935 |
if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx: |
3936 |
nic_mac_ini = 'nic%d_mac' % idx
|
3937 |
nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini) |
3938 |
|
3939 |
# ip ping checks (we use the same ip that was resolved in ExpandNames)
|
3940 |
if self.op.start and not self.op.ip_check: |
3941 |
raise errors.OpPrereqError("Cannot ignore IP address conflicts when" |
3942 |
" adding an instance in start mode")
|
3943 |
|
3944 |
if self.op.ip_check: |
3945 |
if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT): |
3946 |
raise errors.OpPrereqError("IP %s of instance %s already in use" % |
3947 |
(self.check_ip, self.op.instance_name)) |
3948 |
|
3949 |
#### allocator run
|
3950 |
|
3951 |
if self.op.iallocator is not None: |
3952 |
self._RunAllocator()
|
3953 |
|
3954 |
#### node related checks
|
3955 |
|
3956 |
# check primary node
|
3957 |
self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode) |
3958 |
assert self.pnode is not None, \ |
3959 |
"Cannot retrieve locked node %s" % self.op.pnode |
3960 |
if pnode.offline:
|
3961 |
raise errors.OpPrereqError("Cannot use offline primary node '%s'" % |
3962 |
pnode.name) |
3963 |
|
3964 |
self.secondaries = []
|
3965 |
|
3966 |
# mirror node verification
|
3967 |
if self.op.disk_template in constants.DTS_NET_MIRROR: |
3968 |
if self.op.snode is None: |
3969 |
raise errors.OpPrereqError("The networked disk templates need" |
3970 |
" a mirror node")
|
3971 |
if self.op.snode == pnode.name: |
3972 |
raise errors.OpPrereqError("The secondary node cannot be" |
3973 |
" the primary node.")
|
3974 |
self.secondaries.append(self.op.snode) |
3975 |
_CheckNodeOnline(self, self.op.snode) |
3976 |
|
3977 |
nodenames = [pnode.name] + self.secondaries
|
3978 |
|
3979 |
req_size = _ComputeDiskSize(self.op.disk_template,
|
3980 |
self.disks)
|
3981 |
|
3982 |
# Check lv size requirements
|
3983 |
if req_size is not None: |
3984 |
nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(), |
3985 |
self.op.hypervisor)
|
3986 |
for node in nodenames: |
3987 |
info = nodeinfo[node] |
3988 |
info.Raise() |
3989 |
info = info.data |
3990 |
if not info: |
3991 |
raise errors.OpPrereqError("Cannot get current information" |
3992 |
" from node '%s'" % node)
|
3993 |
vg_free = info.get('vg_free', None) |
3994 |
if not isinstance(vg_free, int): |
3995 |
raise errors.OpPrereqError("Can't compute free disk space on" |
3996 |
" node %s" % node)
|
3997 |
if req_size > info['vg_free']: |
3998 |
raise errors.OpPrereqError("Not enough disk space on target node %s." |
3999 |
" %d MB available, %d MB required" %
|
4000 |
(node, info['vg_free'], req_size))
|
4001 |
|
4002 |
_CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams) |
4003 |
|
4004 |
# os verification
|
4005 |
result = self.rpc.call_os_get(pnode.name, self.op.os_type) |
4006 |
result.Raise() |
4007 |
if not isinstance(result.data, objects.OS): |
4008 |
raise errors.OpPrereqError("OS '%s' not in supported os list for" |
4009 |
" primary node" % self.op.os_type) |
4010 |
|
4011 |
# bridge check on primary node
|
4012 |
bridges = [n.bridge for n in self.nics] |
4013 |
result = self.rpc.call_bridges_exist(self.pnode.name, bridges) |
4014 |
result.Raise() |
4015 |
if not result.data: |
4016 |
raise errors.OpPrereqError("One of the target bridges '%s' does not" |
4017 |
" exist on destination node '%s'" %
|
4018 |
(",".join(bridges), pnode.name))
|
4019 |
|
4020 |
# memory check on primary node
|
4021 |
if self.op.start: |
4022 |
_CheckNodeFreeMemory(self, self.pnode.name, |
4023 |
"creating instance %s" % self.op.instance_name, |
4024 |
self.be_full[constants.BE_MEMORY],
|
4025 |
self.op.hypervisor)
|
4026 |
|
4027 |
if self.op.start: |
4028 |
self.instance_status = 'up' |
4029 |
else:
|
4030 |
self.instance_status = 'down' |
4031 |
|
4032 |
def Exec(self, feedback_fn): |
4033 |
"""Create and add the instance to the cluster.
|
4034 |
|
4035 |
"""
|
4036 |
instance = self.op.instance_name
|
4037 |
pnode_name = self.pnode.name
|
4038 |
|
4039 |
for nic in self.nics: |
4040 |
if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
4041 |
nic.mac = self.cfg.GenerateMAC()
|
4042 |
|
4043 |
ht_kind = self.op.hypervisor
|
4044 |
if ht_kind in constants.HTS_REQ_PORT: |
4045 |
network_port = self.cfg.AllocatePort()
|
4046 |
else:
|
4047 |
network_port = None
|
4048 |
|
4049 |
##if self.op.vnc_bind_address is None:
|
4050 |
## self.op.vnc_bind_address = constants.VNC_DEFAULT_BIND_ADDRESS
|
4051 |
|
4052 |
# this is needed because os.path.join does not accept None arguments
|
4053 |
if self.op.file_storage_dir is None: |
4054 |
string_file_storage_dir = ""
|
4055 |
else:
|
4056 |
string_file_storage_dir = self.op.file_storage_dir
|
4057 |
|
4058 |
# build the full file storage dir path
|
4059 |
file_storage_dir = os.path.normpath(os.path.join( |
4060 |
self.cfg.GetFileStorageDir(),
|
4061 |
string_file_storage_dir, instance)) |
4062 |
|
4063 |
|
4064 |
disks = _GenerateDiskTemplate(self,
|
4065 |
self.op.disk_template,
|
4066 |
instance, pnode_name, |
4067 |
self.secondaries,
|
4068 |
self.disks,
|
4069 |
file_storage_dir, |
4070 |
self.op.file_driver,
|
4071 |
0)
|
4072 |
|
4073 |
iobj = objects.Instance(name=instance, os=self.op.os_type,
|
4074 |
primary_node=pnode_name, |
4075 |
nics=self.nics, disks=disks,
|
4076 |
disk_template=self.op.disk_template,
|
4077 |
status=self.instance_status,
|
4078 |
network_port=network_port, |
4079 |
beparams=self.op.beparams,
|
4080 |
hvparams=self.op.hvparams,
|
4081 |
hypervisor=self.op.hypervisor,
|
4082 |
) |
4083 |
|
4084 |
feedback_fn("* creating instance disks...")
|
4085 |
if not _CreateDisks(self, iobj): |
4086 |
_RemoveDisks(self, iobj)
|
4087 |
self.cfg.ReleaseDRBDMinors(instance)
|
4088 |
raise errors.OpExecError("Device creation failed, reverting...") |
4089 |
|
4090 |
feedback_fn("adding instance %s to cluster config" % instance)
|
4091 |
|
4092 |
self.cfg.AddInstance(iobj)
|
4093 |
# Declare that we don't want to remove the instance lock anymore, as we've
|
4094 |
# added the instance to the config
|
4095 |
del self.remove_locks[locking.LEVEL_INSTANCE] |
4096 |
# Remove the temp. assignements for the instance's drbds
|
4097 |
self.cfg.ReleaseDRBDMinors(instance)
|
4098 |
# Unlock all the nodes
|
4099 |
if self.op.mode == constants.INSTANCE_IMPORT: |
4100 |
nodes_keep = [self.op.src_node]
|
4101 |
nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE] |
4102 |
if node != self.op.src_node] |
4103 |
self.context.glm.release(locking.LEVEL_NODE, nodes_release)
|
4104 |
self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
|
4105 |
else:
|
4106 |
self.context.glm.release(locking.LEVEL_NODE)
|
4107 |
del self.acquired_locks[locking.LEVEL_NODE] |
4108 |
|
4109 |
if self.op.wait_for_sync: |
4110 |
disk_abort = not _WaitForSync(self, iobj) |
4111 |
elif iobj.disk_template in constants.DTS_NET_MIRROR: |
4112 |
# make sure the disks are not degraded (still sync-ing is ok)
|
4113 |
time.sleep(15)
|
4114 |
feedback_fn("* checking mirrors status")
|
4115 |
disk_abort = not _WaitForSync(self, iobj, oneshot=True) |
4116 |
else:
|
4117 |
disk_abort = False
|
4118 |
|
4119 |
if disk_abort:
|
4120 |
_RemoveDisks(self, iobj)
|
4121 |
self.cfg.RemoveInstance(iobj.name)
|
4122 |
# Make sure the instance lock gets removed
|
4123 |
self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
|
4124 |
raise errors.OpExecError("There are some degraded disks for" |
4125 |
" this instance")
|
4126 |
|
4127 |
feedback_fn("creating os for instance %s on node %s" %
|
4128 |
(instance, pnode_name)) |
4129 |
|
4130 |
if iobj.disk_template != constants.DT_DISKLESS:
|
4131 |
if self.op.mode == constants.INSTANCE_CREATE: |
4132 |
feedback_fn("* running the instance OS create scripts...")
|
4133 |
result = self.rpc.call_instance_os_add(pnode_name, iobj)
|
4134 |
result.Raise() |
4135 |
if not result.data: |
4136 |
raise errors.OpExecError("Could not add os for instance %s" |
4137 |
" on node %s" %
|
4138 |
(instance, pnode_name)) |
4139 |
|
4140 |
elif self.op.mode == constants.INSTANCE_IMPORT: |
4141 |
feedback_fn("* running the instance OS import scripts...")
|
4142 |
src_node = self.op.src_node
|
4143 |
src_images = self.src_images
|
4144 |
cluster_name = self.cfg.GetClusterName()
|
4145 |
import_result = self.rpc.call_instance_os_import(pnode_name, iobj,
|
4146 |
src_node, src_images, |
4147 |
cluster_name) |
4148 |
import_result.Raise() |
4149 |
for idx, result in enumerate(import_result.data): |
4150 |
if not result: |
4151 |
self.LogWarning("Could not import the image %s for instance" |
4152 |
" %s, disk %d, on node %s" %
|
4153 |
(src_images[idx], instance, idx, pnode_name)) |
4154 |
else:
|
4155 |
# also checked in the prereq part
|
4156 |
raise errors.ProgrammerError("Unknown OS initialization mode '%s'" |
4157 |
% self.op.mode)
|
4158 |
|
4159 |
if self.op.start: |
4160 |
logging.info("Starting instance %s on node %s", instance, pnode_name)
|
4161 |
feedback_fn("* starting instance...")
|
4162 |
result = self.rpc.call_instance_start(pnode_name, iobj, None) |
4163 |
result.Raise() |
4164 |
if not result.data: |
4165 |
raise errors.OpExecError("Could not start instance") |
4166 |
|
4167 |
|
4168 |
class LUConnectConsole(NoHooksLU): |
4169 |
"""Connect to an instance's console.
|
4170 |
|
4171 |
This is somewhat special in that it returns the command line that
|
4172 |
you need to run on the master node in order to connect to the
|
4173 |
console.
|
4174 |
|
4175 |
"""
|
4176 |
_OP_REQP = ["instance_name"]
|
4177 |
REQ_BGL = False
|
4178 |
|
4179 |
def ExpandNames(self): |
4180 |
self._ExpandAndLockInstance()
|
4181 |
|
4182 |
def CheckPrereq(self): |
4183 |
"""Check prerequisites.
|
4184 |
|
4185 |
This checks that the instance is in the cluster.
|
4186 |
|
4187 |
"""
|
4188 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
4189 |
assert self.instance is not None, \ |
4190 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
4191 |
_CheckNodeOnline(self, self.op.primary_node) |
4192 |
|
4193 |
def Exec(self, feedback_fn): |
4194 |
"""Connect to the console of an instance
|
4195 |
|
4196 |
"""
|
4197 |
instance = self.instance
|
4198 |
node = instance.primary_node |
4199 |
|
4200 |
node_insts = self.rpc.call_instance_list([node],
|
4201 |
[instance.hypervisor])[node] |
4202 |
node_insts.Raise() |
4203 |
|
4204 |
if instance.name not in node_insts.data: |
4205 |
raise errors.OpExecError("Instance %s is not running." % instance.name) |
4206 |
|
4207 |
logging.debug("Connecting to console of %s on %s", instance.name, node)
|
4208 |
|
4209 |
hyper = hypervisor.GetHypervisor(instance.hypervisor) |
4210 |
console_cmd = hyper.GetShellCommandForConsole(instance) |
4211 |
|
4212 |
# build ssh cmdline
|
4213 |
return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True) |
4214 |
|
4215 |
|
4216 |
class LUReplaceDisks(LogicalUnit): |
4217 |
"""Replace the disks of an instance.
|
4218 |
|
4219 |
"""
|
4220 |
HPATH = "mirrors-replace"
|
4221 |
HTYPE = constants.HTYPE_INSTANCE |
4222 |
_OP_REQP = ["instance_name", "mode", "disks"] |
4223 |
REQ_BGL = False
|
4224 |
|
4225 |
def ExpandNames(self): |
4226 |
self._ExpandAndLockInstance()
|
4227 |
|
4228 |
if not hasattr(self.op, "remote_node"): |
4229 |
self.op.remote_node = None |
4230 |
|
4231 |
ia_name = getattr(self.op, "iallocator", None) |
4232 |
if ia_name is not None: |
4233 |
if self.op.remote_node is not None: |
4234 |
raise errors.OpPrereqError("Give either the iallocator or the new" |
4235 |
" secondary, not both")
|
4236 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
4237 |
elif self.op.remote_node is not None: |
4238 |
remote_node = self.cfg.ExpandNodeName(self.op.remote_node) |
4239 |
if remote_node is None: |
4240 |
raise errors.OpPrereqError("Node '%s' not known" % |
4241 |
self.op.remote_node)
|
4242 |
self.op.remote_node = remote_node
|
4243 |
self.needed_locks[locking.LEVEL_NODE] = [remote_node]
|
4244 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
|
4245 |
else:
|
4246 |
self.needed_locks[locking.LEVEL_NODE] = []
|
4247 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
4248 |
|
4249 |
def DeclareLocks(self, level): |
4250 |
# If we're not already locking all nodes in the set we have to declare the
|
4251 |
# instance's primary/secondary nodes.
|
4252 |
if (level == locking.LEVEL_NODE and |
4253 |
self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET): |
4254 |
self._LockInstancesNodes()
|
4255 |
|
4256 |
def _RunAllocator(self): |
4257 |
"""Compute a new secondary node using an IAllocator.
|
4258 |
|
4259 |
"""
|
4260 |
ial = IAllocator(self,
|
4261 |
mode=constants.IALLOCATOR_MODE_RELOC, |
4262 |
name=self.op.instance_name,
|
4263 |
relocate_from=[self.sec_node])
|
4264 |
|
4265 |
ial.Run(self.op.iallocator)
|
4266 |
|
4267 |
if not ial.success: |
4268 |
raise errors.OpPrereqError("Can't compute nodes using" |
4269 |
" iallocator '%s': %s" % (self.op.iallocator, |
4270 |
ial.info)) |
4271 |
if len(ial.nodes) != ial.required_nodes: |
4272 |
raise errors.OpPrereqError("iallocator '%s' returned invalid number" |
4273 |
" of nodes (%s), required %s" %
|
4274 |
(len(ial.nodes), ial.required_nodes))
|
4275 |
self.op.remote_node = ial.nodes[0] |
4276 |
self.LogInfo("Selected new secondary for the instance: %s", |
4277 |
self.op.remote_node)
|
4278 |
|
4279 |
def BuildHooksEnv(self): |
4280 |
"""Build hooks env.
|
4281 |
|
4282 |
This runs on the master, the primary and all the secondaries.
|
4283 |
|
4284 |
"""
|
4285 |
env = { |
4286 |
"MODE": self.op.mode, |
4287 |
"NEW_SECONDARY": self.op.remote_node, |
4288 |
"OLD_SECONDARY": self.instance.secondary_nodes[0], |
4289 |
} |
4290 |
env.update(_BuildInstanceHookEnvByObject(self, self.instance)) |
4291 |
nl = [ |
4292 |
self.cfg.GetMasterNode(),
|
4293 |
self.instance.primary_node,
|
4294 |
] |
4295 |
if self.op.remote_node is not None: |
4296 |
nl.append(self.op.remote_node)
|
4297 |
return env, nl, nl
|
4298 |
|
4299 |
def CheckPrereq(self): |
4300 |
"""Check prerequisites.
|
4301 |
|
4302 |
This checks that the instance is in the cluster.
|
4303 |
|
4304 |
"""
|
4305 |
instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
4306 |
assert instance is not None, \ |
4307 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
4308 |
self.instance = instance
|
4309 |
|
4310 |
if instance.disk_template not in constants.DTS_NET_MIRROR: |
4311 |
raise errors.OpPrereqError("Instance's disk layout is not" |
4312 |
" network mirrored.")
|
4313 |
|
4314 |
if len(instance.secondary_nodes) != 1: |
4315 |
raise errors.OpPrereqError("The instance has a strange layout," |
4316 |
" expected one secondary but found %d" %
|
4317 |
len(instance.secondary_nodes))
|
4318 |
|
4319 |
self.sec_node = instance.secondary_nodes[0] |
4320 |
|
4321 |
ia_name = getattr(self.op, "iallocator", None) |
4322 |
if ia_name is not None: |
4323 |
self._RunAllocator()
|
4324 |
|
4325 |
remote_node = self.op.remote_node
|
4326 |
if remote_node is not None: |
4327 |
self.remote_node_info = self.cfg.GetNodeInfo(remote_node) |
4328 |
assert self.remote_node_info is not None, \ |
4329 |
"Cannot retrieve locked node %s" % remote_node
|
4330 |
else:
|
4331 |
self.remote_node_info = None |
4332 |
if remote_node == instance.primary_node:
|
4333 |
raise errors.OpPrereqError("The specified node is the primary node of" |
4334 |
" the instance.")
|
4335 |
elif remote_node == self.sec_node: |
4336 |
if self.op.mode == constants.REPLACE_DISK_SEC: |
4337 |
# this is for DRBD8, where we can't execute the same mode of
|
4338 |
# replacement as for drbd7 (no different port allocated)
|
4339 |
raise errors.OpPrereqError("Same secondary given, cannot execute" |
4340 |
" replacement")
|
4341 |
if instance.disk_template == constants.DT_DRBD8:
|
4342 |
if (self.op.mode == constants.REPLACE_DISK_ALL and |
4343 |
remote_node is not None): |
4344 |
# switch to replace secondary mode
|
4345 |
self.op.mode = constants.REPLACE_DISK_SEC
|
4346 |
|
4347 |
if self.op.mode == constants.REPLACE_DISK_ALL: |
4348 |
raise errors.OpPrereqError("Template 'drbd' only allows primary or" |
4349 |
" secondary disk replacement, not"
|
4350 |
" both at once")
|
4351 |
elif self.op.mode == constants.REPLACE_DISK_PRI: |
4352 |
if remote_node is not None: |
4353 |
raise errors.OpPrereqError("Template 'drbd' does not allow changing" |
4354 |
" the secondary while doing a primary"
|
4355 |
" node disk replacement")
|
4356 |
self.tgt_node = instance.primary_node
|
4357 |
self.oth_node = instance.secondary_nodes[0] |
4358 |
_CheckNodeOnline(self, self.tgt_node) |
4359 |
_CheckNodeOnline(self, self.oth_node) |
4360 |
elif self.op.mode == constants.REPLACE_DISK_SEC: |
4361 |
self.new_node = remote_node # this can be None, in which case |
4362 |
# we don't change the secondary
|
4363 |
self.tgt_node = instance.secondary_nodes[0] |
4364 |
self.oth_node = instance.primary_node
|
4365 |
_CheckNodeOnline(self, self.oth_node) |
4366 |
if self.new_node is not None: |
4367 |
_CheckNodeOnline(self, self.new_node) |
4368 |
else:
|
4369 |
_CheckNodeOnline(self, self.tgt_node) |
4370 |
else:
|
4371 |
raise errors.ProgrammerError("Unhandled disk replace mode") |
4372 |
|
4373 |
if not self.op.disks: |
4374 |
self.op.disks = range(len(instance.disks)) |
4375 |
|
4376 |
for disk_idx in self.op.disks: |
4377 |
instance.FindDisk(disk_idx) |
4378 |
|
4379 |
def _ExecD8DiskOnly(self, feedback_fn): |
4380 |
"""Replace a disk on the primary or secondary for dbrd8.
|
4381 |
|
4382 |
The algorithm for replace is quite complicated:
|
4383 |
|
4384 |
1. for each disk to be replaced:
|
4385 |
|
4386 |
1. create new LVs on the target node with unique names
|
4387 |
1. detach old LVs from the drbd device
|
4388 |
1. rename old LVs to name_replaced.<time_t>
|
4389 |
1. rename new LVs to old LVs
|
4390 |
1. attach the new LVs (with the old names now) to the drbd device
|
4391 |
|
4392 |
1. wait for sync across all devices
|
4393 |
|
4394 |
1. for each modified disk:
|
4395 |
|
4396 |
1. remove old LVs (which have the name name_replaces.<time_t>)
|
4397 |
|
4398 |
Failures are not very well handled.
|
4399 |
|
4400 |
"""
|
4401 |
steps_total = 6
|
4402 |
warning, info = (self.proc.LogWarning, self.proc.LogInfo) |
4403 |
instance = self.instance
|
4404 |
iv_names = {} |
4405 |
vgname = self.cfg.GetVGName()
|
4406 |
# start of work
|
4407 |
cfg = self.cfg
|
4408 |
tgt_node = self.tgt_node
|
4409 |
oth_node = self.oth_node
|
4410 |
|
4411 |
# Step: check device activation
|
4412 |
self.proc.LogStep(1, steps_total, "check device existence") |
4413 |
info("checking volume groups")
|
4414 |
my_vg = cfg.GetVGName() |
4415 |
results = self.rpc.call_vg_list([oth_node, tgt_node])
|
4416 |
if not results: |
4417 |
raise errors.OpExecError("Can't list volume groups on the nodes") |
4418 |
for node in oth_node, tgt_node: |
4419 |
res = results[node] |
4420 |
if res.failed or not res.data or my_vg not in res.data: |
4421 |
raise errors.OpExecError("Volume group '%s' not found on %s" % |
4422 |
(my_vg, node)) |
4423 |
for idx, dev in enumerate(instance.disks): |
4424 |
if idx not in self.op.disks: |
4425 |
continue
|
4426 |
for node in tgt_node, oth_node: |
4427 |
info("checking disk/%d on %s" % (idx, node))
|
4428 |
cfg.SetDiskID(dev, node) |
4429 |
if not self.rpc.call_blockdev_find(node, dev): |
4430 |
raise errors.OpExecError("Can't find disk/%d on node %s" % |
4431 |
(idx, node)) |
4432 |
|
4433 |
# Step: check other node consistency
|
4434 |
self.proc.LogStep(2, steps_total, "check peer consistency") |
4435 |
for idx, dev in enumerate(instance.disks): |
4436 |
if idx not in self.op.disks: |
4437 |
continue
|
4438 |
info("checking disk/%d consistency on %s" % (idx, oth_node))
|
4439 |
if not _CheckDiskConsistency(self, dev, oth_node, |
4440 |
oth_node==instance.primary_node): |
4441 |
raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe" |
4442 |
" to replace disks on this node (%s)" %
|
4443 |
(oth_node, tgt_node)) |
4444 |
|
4445 |
# Step: create new storage
|
4446 |
self.proc.LogStep(3, steps_total, "allocate new storage") |
4447 |
for idx, dev in enumerate(instance.disks): |
4448 |
if idx not in self.op.disks: |
4449 |
continue
|
4450 |
size = dev.size |
4451 |
cfg.SetDiskID(dev, tgt_node) |
4452 |
lv_names = [".disk%d_%s" % (idx, suf)
|
4453 |
for suf in ["data", "meta"]] |
4454 |
names = _GenerateUniqueNames(self, lv_names)
|
4455 |
lv_data = objects.Disk(dev_type=constants.LD_LV, size=size, |
4456 |
logical_id=(vgname, names[0]))
|
4457 |
lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
|
4458 |
logical_id=(vgname, names[1]))
|
4459 |
new_lvs = [lv_data, lv_meta] |
4460 |
old_lvs = dev.children |
4461 |
iv_names[dev.iv_name] = (dev, old_lvs, new_lvs) |
4462 |
info("creating new local storage on %s for %s" %
|
4463 |
(tgt_node, dev.iv_name)) |
4464 |
# since we *always* want to create this LV, we use the
|
4465 |
# _Create...OnPrimary (which forces the creation), even if we
|
4466 |
# are talking about the secondary node
|
4467 |
for new_lv in new_lvs: |
4468 |
if not _CreateBlockDevOnPrimary(self, tgt_node, instance, new_lv, |
4469 |
_GetInstanceInfoText(instance)): |
4470 |
raise errors.OpExecError("Failed to create new LV named '%s' on" |
4471 |
" node '%s'" %
|
4472 |
(new_lv.logical_id[1], tgt_node))
|
4473 |
|
4474 |
# Step: for each lv, detach+rename*2+attach
|
4475 |
self.proc.LogStep(4, steps_total, "change drbd configuration") |
4476 |
for dev, old_lvs, new_lvs in iv_names.itervalues(): |
4477 |
info("detaching %s drbd from local storage" % dev.iv_name)
|
4478 |
result = self.rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs)
|
4479 |
result.Raise() |
4480 |
if not result.data: |
4481 |
raise errors.OpExecError("Can't detach drbd from local storage on node" |
4482 |
" %s for device %s" % (tgt_node, dev.iv_name))
|
4483 |
#dev.children = []
|
4484 |
#cfg.Update(instance)
|
4485 |
|
4486 |
# ok, we created the new LVs, so now we know we have the needed
|
4487 |
# storage; as such, we proceed on the target node to rename
|
4488 |
# old_lv to _old, and new_lv to old_lv; note that we rename LVs
|
4489 |
# using the assumption that logical_id == physical_id (which in
|
4490 |
# turn is the unique_id on that node)
|
4491 |
|
4492 |
# FIXME(iustin): use a better name for the replaced LVs
|
4493 |
temp_suffix = int(time.time())
|
4494 |
ren_fn = lambda d, suff: (d.physical_id[0], |
4495 |
d.physical_id[1] + "_replaced-%s" % suff) |
4496 |
# build the rename list based on what LVs exist on the node
|
4497 |
rlist = [] |
4498 |
for to_ren in old_lvs: |
4499 |
find_res = self.rpc.call_blockdev_find(tgt_node, to_ren)
|
4500 |
if not find_res.failed and find_res.data is not None: # device exists |
4501 |
rlist.append((to_ren, ren_fn(to_ren, temp_suffix))) |
4502 |
|
4503 |
info("renaming the old LVs on the target node")
|
4504 |
result = self.rpc.call_blockdev_rename(tgt_node, rlist)
|
4505 |
result.Raise() |
4506 |
if not result.data: |
4507 |
raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node) |
4508 |
# now we rename the new LVs to the old LVs
|
4509 |
info("renaming the new LVs on the target node")
|
4510 |
rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)] |
4511 |
result = self.rpc.call_blockdev_rename(tgt_node, rlist)
|
4512 |
result.Raise() |
4513 |
if not result.data: |
4514 |
raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node) |
4515 |
|
4516 |
for old, new in zip(old_lvs, new_lvs): |
4517 |
new.logical_id = old.logical_id |
4518 |
cfg.SetDiskID(new, tgt_node) |
4519 |
|
4520 |
for disk in old_lvs: |
4521 |
disk.logical_id = ren_fn(disk, temp_suffix) |
4522 |
cfg.SetDiskID(disk, tgt_node) |
4523 |
|
4524 |
# now that the new lvs have the old name, we can add them to the device
|
4525 |
info("adding new mirror component on %s" % tgt_node)
|
4526 |
result =self.rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs)
|
4527 |
if result.failed or not result.data: |
4528 |
for new_lv in new_lvs: |
4529 |
result = self.rpc.call_blockdev_remove(tgt_node, new_lv)
|
4530 |
if result.failed or not result.data: |
4531 |
warning("Can't rollback device %s", hint="manually cleanup unused" |
4532 |
" logical volumes")
|
4533 |
raise errors.OpExecError("Can't add local storage to drbd") |
4534 |
|
4535 |
dev.children = new_lvs |
4536 |
cfg.Update(instance) |
4537 |
|
4538 |
# Step: wait for sync
|
4539 |
|
4540 |
# this can fail as the old devices are degraded and _WaitForSync
|
4541 |
# does a combined result over all disks, so we don't check its
|
4542 |
# return value
|
4543 |
self.proc.LogStep(5, steps_total, "sync devices") |
4544 |
_WaitForSync(self, instance, unlock=True) |
4545 |
|
4546 |
# so check manually all the devices
|
4547 |
for name, (dev, old_lvs, new_lvs) in iv_names.iteritems(): |
4548 |
cfg.SetDiskID(dev, instance.primary_node) |
4549 |
result = self.rpc.call_blockdev_find(instance.primary_node, dev)
|
4550 |
if result.failed or result.data[5]: |
4551 |
raise errors.OpExecError("DRBD device %s is degraded!" % name) |
4552 |
|
4553 |
# Step: remove old storage
|
4554 |
self.proc.LogStep(6, steps_total, "removing old storage") |
4555 |
for name, (dev, old_lvs, new_lvs) in iv_names.iteritems(): |
4556 |
info("remove logical volumes for %s" % name)
|
4557 |
for lv in old_lvs: |
4558 |
cfg.SetDiskID(lv, tgt_node) |
4559 |
result = self.rpc.call_blockdev_remove(tgt_node, lv)
|
4560 |
if result.failed or not result.data: |
4561 |
warning("Can't remove old LV", hint="manually remove unused LVs") |
4562 |
continue
|
4563 |
|
4564 |
def _ExecD8Secondary(self, feedback_fn): |
4565 |
"""Replace the secondary node for drbd8.
|
4566 |
|
4567 |
The algorithm for replace is quite complicated:
|
4568 |
- for all disks of the instance:
|
4569 |
- create new LVs on the new node with same names
|
4570 |
- shutdown the drbd device on the old secondary
|
4571 |
- disconnect the drbd network on the primary
|
4572 |
- create the drbd device on the new secondary
|
4573 |
- network attach the drbd on the primary, using an artifice:
|
4574 |
the drbd code for Attach() will connect to the network if it
|
4575 |
finds a device which is connected to the good local disks but
|
4576 |
not network enabled
|
4577 |
- wait for sync across all devices
|
4578 |
- remove all disks from the old secondary
|
4579 |
|
4580 |
Failures are not very well handled.
|
4581 |
|
4582 |
"""
|
4583 |
steps_total = 6
|
4584 |
warning, info = (self.proc.LogWarning, self.proc.LogInfo) |
4585 |
instance = self.instance
|
4586 |
iv_names = {} |
4587 |
vgname = self.cfg.GetVGName()
|
4588 |
# start of work
|
4589 |
cfg = self.cfg
|
4590 |
old_node = self.tgt_node
|
4591 |
new_node = self.new_node
|
4592 |
pri_node = instance.primary_node |
4593 |
|
4594 |
# Step: check device activation
|
4595 |
self.proc.LogStep(1, steps_total, "check device existence") |
4596 |
info("checking volume groups")
|
4597 |
my_vg = cfg.GetVGName() |
4598 |
results = self.rpc.call_vg_list([pri_node, new_node])
|
4599 |
for node in pri_node, new_node: |
4600 |
res = results[node] |
4601 |
if res.failed or not res.data or my_vg not in res.data: |
4602 |
raise errors.OpExecError("Volume group '%s' not found on %s" % |
4603 |
(my_vg, node)) |
4604 |
for idx, dev in enumerate(instance.disks): |
4605 |
if idx not in self.op.disks: |
4606 |
continue
|
4607 |
info("checking disk/%d on %s" % (idx, pri_node))
|
4608 |
cfg.SetDiskID(dev, pri_node) |
4609 |
result = self.rpc.call_blockdev_find(pri_node, dev)
|
4610 |
result.Raise() |
4611 |
if not result.data: |
4612 |
raise errors.OpExecError("Can't find disk/%d on node %s" % |
4613 |
(idx, pri_node)) |
4614 |
|
4615 |
# Step: check other node consistency
|
4616 |
self.proc.LogStep(2, steps_total, "check peer consistency") |
4617 |
for idx, dev in enumerate(instance.disks): |
4618 |
if idx not in self.op.disks: |
4619 |
continue
|
4620 |
info("checking disk/%d consistency on %s" % (idx, pri_node))
|
4621 |
if not _CheckDiskConsistency(self, dev, pri_node, True, ldisk=True): |
4622 |
raise errors.OpExecError("Primary node (%s) has degraded storage," |
4623 |
" unsafe to replace the secondary" %
|
4624 |
pri_node) |
4625 |
|
4626 |
# Step: create new storage
|
4627 |
self.proc.LogStep(3, steps_total, "allocate new storage") |
4628 |
for idx, dev in enumerate(instance.disks): |
4629 |
size = dev.size |
4630 |
info("adding new local storage on %s for disk/%d" %
|
4631 |
(new_node, idx)) |
4632 |
# since we *always* want to create this LV, we use the
|
4633 |
# _Create...OnPrimary (which forces the creation), even if we
|
4634 |
# are talking about the secondary node
|
4635 |
for new_lv in dev.children: |
4636 |
if not _CreateBlockDevOnPrimary(self, new_node, instance, new_lv, |
4637 |
_GetInstanceInfoText(instance)): |
4638 |
raise errors.OpExecError("Failed to create new LV named '%s' on" |
4639 |
" node '%s'" %
|
4640 |
(new_lv.logical_id[1], new_node))
|
4641 |
|
4642 |
# Step 4: dbrd minors and drbd setups changes
|
4643 |
# after this, we must manually remove the drbd minors on both the
|
4644 |
# error and the success paths
|
4645 |
minors = cfg.AllocateDRBDMinor([new_node for dev in instance.disks], |
4646 |
instance.name) |
4647 |
logging.debug("Allocated minors %s" % (minors,))
|
4648 |
self.proc.LogStep(4, steps_total, "changing drbd configuration") |
4649 |
for idx, (dev, new_minor) in enumerate(zip(instance.disks, minors)): |
4650 |
size = dev.size |
4651 |
info("activating a new drbd on %s for disk/%d" % (new_node, idx))
|
4652 |
# create new devices on new_node
|
4653 |
if pri_node == dev.logical_id[0]: |
4654 |
new_logical_id = (pri_node, new_node, |
4655 |
dev.logical_id[2], dev.logical_id[3], new_minor, |
4656 |
dev.logical_id[5])
|
4657 |
else:
|
4658 |
new_logical_id = (new_node, pri_node, |
4659 |
dev.logical_id[2], new_minor, dev.logical_id[4], |
4660 |
dev.logical_id[5])
|
4661 |
iv_names[idx] = (dev, dev.children, new_logical_id) |
4662 |
logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
|
4663 |
new_logical_id) |
4664 |
new_drbd = objects.Disk(dev_type=constants.LD_DRBD8, |
4665 |
logical_id=new_logical_id, |
4666 |
children=dev.children) |
4667 |
if not _CreateBlockDevOnSecondary(self, new_node, instance, |
4668 |
new_drbd, False,
|
4669 |
_GetInstanceInfoText(instance)): |
4670 |
self.cfg.ReleaseDRBDMinors(instance.name)
|
4671 |
raise errors.OpExecError("Failed to create new DRBD on" |
4672 |
" node '%s'" % new_node)
|
4673 |
|
4674 |
for idx, dev in enumerate(instance.disks): |
4675 |
# we have new devices, shutdown the drbd on the old secondary
|
4676 |
info("shutting down drbd for disk/%d on old node" % idx)
|
4677 |
cfg.SetDiskID(dev, old_node) |
4678 |
result = self.rpc.call_blockdev_shutdown(old_node, dev)
|
4679 |
if result.failed or not result.data: |
4680 |
warning("Failed to shutdown drbd for disk/%d on old node" % idx,
|
4681 |
hint="Please cleanup this device manually as soon as possible")
|
4682 |
|
4683 |
info("detaching primary drbds from the network (=> standalone)")
|
4684 |
done = 0
|
4685 |
for idx, dev in enumerate(instance.disks): |
4686 |
cfg.SetDiskID(dev, pri_node) |
4687 |
# set the network part of the physical (unique in bdev terms) id
|
4688 |
# to None, meaning detach from network
|
4689 |
dev.physical_id = (None, None, None, None) + dev.physical_id[4:] |
4690 |
# and 'find' the device, which will 'fix' it to match the
|
4691 |
# standalone state
|
4692 |
result = self.rpc.call_blockdev_find(pri_node, dev)
|
4693 |
if not result.failed and result.data: |
4694 |
done += 1
|
4695 |
else:
|
4696 |
warning("Failed to detach drbd disk/%d from network, unusual case" %
|
4697 |
idx) |
4698 |
|
4699 |
if not done: |
4700 |
# no detaches succeeded (very unlikely)
|
4701 |
self.cfg.ReleaseDRBDMinors(instance.name)
|
4702 |
raise errors.OpExecError("Can't detach at least one DRBD from old node") |
4703 |
|
4704 |
# if we managed to detach at least one, we update all the disks of
|
4705 |
# the instance to point to the new secondary
|
4706 |
info("updating instance configuration")
|
4707 |
for dev, _, new_logical_id in iv_names.itervalues(): |
4708 |
dev.logical_id = new_logical_id |
4709 |
cfg.SetDiskID(dev, pri_node) |
4710 |
cfg.Update(instance) |
4711 |
# we can remove now the temp minors as now the new values are
|
4712 |
# written to the config file (and therefore stable)
|
4713 |
self.cfg.ReleaseDRBDMinors(instance.name)
|
4714 |
|
4715 |
# and now perform the drbd attach
|
4716 |
info("attaching primary drbds to new secondary (standalone => connected)")
|
4717 |
failures = [] |
4718 |
for idx, dev in enumerate(instance.disks): |
4719 |
info("attaching primary drbd for disk/%d to new secondary node" % idx)
|
4720 |
# since the attach is smart, it's enough to 'find' the device,
|
4721 |
# it will automatically activate the network, if the physical_id
|
4722 |
# is correct
|
4723 |
cfg.SetDiskID(dev, pri_node) |
4724 |
logging.debug("Disk to attach: %s", dev)
|
4725 |
result = self.rpc.call_blockdev_find(pri_node, dev)
|
4726 |
if result.failed or not result.data: |
4727 |
warning("can't attach drbd disk/%d to new secondary!" % idx,
|
4728 |
"please do a gnt-instance info to see the status of disks")
|
4729 |
|
4730 |
# this can fail as the old devices are degraded and _WaitForSync
|
4731 |
# does a combined result over all disks, so we don't check its
|
4732 |
# return value
|
4733 |
self.proc.LogStep(5, steps_total, "sync devices") |
4734 |
_WaitForSync(self, instance, unlock=True) |
4735 |
|
4736 |
# so check manually all the devices
|
4737 |
for idx, (dev, old_lvs, _) in iv_names.iteritems(): |
4738 |
cfg.SetDiskID(dev, pri_node) |
4739 |
result = self.rpc.call_blockdev_find(pri_node, dev)
|
4740 |
result.Raise() |
4741 |
if result.data[5]: |
4742 |
raise errors.OpExecError("DRBD device disk/%d is degraded!" % idx) |
4743 |
|
4744 |
self.proc.LogStep(6, steps_total, "removing old storage") |
4745 |
for idx, (dev, old_lvs, _) in iv_names.iteritems(): |
4746 |
info("remove logical volumes for disk/%d" % idx)
|
4747 |
for lv in old_lvs: |
4748 |
cfg.SetDiskID(lv, old_node) |
4749 |
result = self.rpc.call_blockdev_remove(old_node, lv)
|
4750 |
if result.failed or not result.data: |
4751 |
warning("Can't remove LV on old secondary",
|
4752 |
hint="Cleanup stale volumes by hand")
|
4753 |
|
4754 |
def Exec(self, feedback_fn): |
4755 |
"""Execute disk replacement.
|
4756 |
|
4757 |
This dispatches the disk replacement to the appropriate handler.
|
4758 |
|
4759 |
"""
|
4760 |
instance = self.instance
|
4761 |
|
4762 |
# Activate the instance disks if we're replacing them on a down instance
|
4763 |
if instance.status == "down": |
4764 |
_StartInstanceDisks(self, instance, True) |
4765 |
|
4766 |
if instance.disk_template == constants.DT_DRBD8:
|
4767 |
if self.op.remote_node is None: |
4768 |
fn = self._ExecD8DiskOnly
|
4769 |
else:
|
4770 |
fn = self._ExecD8Secondary
|
4771 |
else:
|
4772 |
raise errors.ProgrammerError("Unhandled disk replacement case") |
4773 |
|
4774 |
ret = fn(feedback_fn) |
4775 |
|
4776 |
# Deactivate the instance disks if we're replacing them on a down instance
|
4777 |
if instance.status == "down": |
4778 |
_SafeShutdownInstanceDisks(self, instance)
|
4779 |
|
4780 |
return ret
|
4781 |
|
4782 |
|
4783 |
class LUGrowDisk(LogicalUnit): |
4784 |
"""Grow a disk of an instance.
|
4785 |
|
4786 |
"""
|
4787 |
HPATH = "disk-grow"
|
4788 |
HTYPE = constants.HTYPE_INSTANCE |
4789 |
_OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"] |
4790 |
REQ_BGL = False
|
4791 |
|
4792 |
def ExpandNames(self): |
4793 |
self._ExpandAndLockInstance()
|
4794 |
self.needed_locks[locking.LEVEL_NODE] = []
|
4795 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
4796 |
|
4797 |
def DeclareLocks(self, level): |
4798 |
if level == locking.LEVEL_NODE:
|
4799 |
self._LockInstancesNodes()
|
4800 |
|
4801 |
def BuildHooksEnv(self): |
4802 |
"""Build hooks env.
|
4803 |
|
4804 |
This runs on the master, the primary and all the secondaries.
|
4805 |
|
4806 |
"""
|
4807 |
env = { |
4808 |
"DISK": self.op.disk, |
4809 |
"AMOUNT": self.op.amount, |
4810 |
} |
4811 |
env.update(_BuildInstanceHookEnvByObject(self, self.instance)) |
4812 |
nl = [ |
4813 |
self.cfg.GetMasterNode(),
|
4814 |
self.instance.primary_node,
|
4815 |
] |
4816 |
return env, nl, nl
|
4817 |
|
4818 |
def CheckPrereq(self): |
4819 |
"""Check prerequisites.
|
4820 |
|
4821 |
This checks that the instance is in the cluster.
|
4822 |
|
4823 |
"""
|
4824 |
instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
4825 |
assert instance is not None, \ |
4826 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
4827 |
_CheckNodeOnline(self, instance.primary_node)
|
4828 |
for node in instance.secondary_nodes: |
4829 |
_CheckNodeOnline(self, node)
|
4830 |
|
4831 |
|
4832 |
self.instance = instance
|
4833 |
|
4834 |
if instance.disk_template not in (constants.DT_PLAIN, constants.DT_DRBD8): |
4835 |
raise errors.OpPrereqError("Instance's disk layout does not support" |
4836 |
" growing.")
|
4837 |
|
4838 |
self.disk = instance.FindDisk(self.op.disk) |
4839 |
|
4840 |
nodenames = [instance.primary_node] + list(instance.secondary_nodes)
|
4841 |
nodeinfo = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(), |
4842 |
instance.hypervisor) |
4843 |
for node in nodenames: |
4844 |
info = nodeinfo[node] |
4845 |
if info.failed or not info.data: |
4846 |
raise errors.OpPrereqError("Cannot get current information" |
4847 |
" from node '%s'" % node)
|
4848 |
vg_free = info.data.get('vg_free', None) |
4849 |
if not isinstance(vg_free, int): |
4850 |
raise errors.OpPrereqError("Can't compute free disk space on" |
4851 |
" node %s" % node)
|
4852 |
if self.op.amount > vg_free: |
4853 |
raise errors.OpPrereqError("Not enough disk space on target node %s:" |
4854 |
" %d MiB available, %d MiB required" %
|
4855 |
(node, vg_free, self.op.amount))
|
4856 |
|
4857 |
def Exec(self, feedback_fn): |
4858 |
"""Execute disk grow.
|
4859 |
|
4860 |
"""
|
4861 |
instance = self.instance
|
4862 |
disk = self.disk
|
4863 |
for node in (instance.secondary_nodes + (instance.primary_node,)): |
4864 |
self.cfg.SetDiskID(disk, node)
|
4865 |
result = self.rpc.call_blockdev_grow(node, disk, self.op.amount) |
4866 |
result.Raise() |
4867 |
if (not result.data or not isinstance(result.data, (list, tuple)) or |
4868 |
len(result.data) != 2): |
4869 |
raise errors.OpExecError("Grow request failed to node %s" % node) |
4870 |
elif not result.data[0]: |
4871 |
raise errors.OpExecError("Grow request failed to node %s: %s" % |
4872 |
(node, result.data[1]))
|
4873 |
disk.RecordGrow(self.op.amount)
|
4874 |
self.cfg.Update(instance)
|
4875 |
if self.op.wait_for_sync: |
4876 |
disk_abort = not _WaitForSync(self, instance) |
4877 |
if disk_abort:
|
4878 |
self.proc.LogWarning("Warning: disk sync-ing has not returned a good" |
4879 |
" status.\nPlease check the instance.")
|
4880 |
|
4881 |
|
4882 |
class LUQueryInstanceData(NoHooksLU): |
4883 |
"""Query runtime instance data.
|
4884 |
|
4885 |
"""
|
4886 |
_OP_REQP = ["instances", "static"] |
4887 |
REQ_BGL = False
|
4888 |
|
4889 |
def ExpandNames(self): |
4890 |
self.needed_locks = {}
|
4891 |
self.share_locks = dict(((i, 1) for i in locking.LEVELS)) |
4892 |
|
4893 |
if not isinstance(self.op.instances, list): |
4894 |
raise errors.OpPrereqError("Invalid argument type 'instances'") |
4895 |
|
4896 |
if self.op.instances: |
4897 |
self.wanted_names = []
|
4898 |
for name in self.op.instances: |
4899 |
full_name = self.cfg.ExpandInstanceName(name)
|
4900 |
if full_name is None: |
4901 |
raise errors.OpPrereqError("Instance '%s' not known" % |
4902 |
self.op.instance_name)
|
4903 |
self.wanted_names.append(full_name)
|
4904 |
self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names |
4905 |
else:
|
4906 |
self.wanted_names = None |
4907 |
self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
|
4908 |
|
4909 |
self.needed_locks[locking.LEVEL_NODE] = []
|
4910 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
4911 |
|
4912 |
def DeclareLocks(self, level): |
4913 |
if level == locking.LEVEL_NODE:
|
4914 |
self._LockInstancesNodes()
|
4915 |
|
4916 |
def CheckPrereq(self): |
4917 |
"""Check prerequisites.
|
4918 |
|
4919 |
This only checks the optional instance list against the existing names.
|
4920 |
|
4921 |
"""
|
4922 |
if self.wanted_names is None: |
4923 |
self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE] |
4924 |
|
4925 |
self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name |
4926 |
in self.wanted_names] |
4927 |
return
|
4928 |
|
4929 |
def _ComputeDiskStatus(self, instance, snode, dev): |
4930 |
"""Compute block device status.
|
4931 |
|
4932 |
"""
|
4933 |
static = self.op.static
|
4934 |
if not static: |
4935 |
self.cfg.SetDiskID(dev, instance.primary_node)
|
4936 |
dev_pstatus = self.rpc.call_blockdev_find(instance.primary_node, dev)
|
4937 |
dev_pstatus.Raise() |
4938 |
dev_pstatus = dev_pstatus.data |
4939 |
else:
|
4940 |
dev_pstatus = None
|
4941 |
|
4942 |
if dev.dev_type in constants.LDS_DRBD: |
4943 |
# we change the snode then (otherwise we use the one passed in)
|
4944 |
if dev.logical_id[0] == instance.primary_node: |
4945 |
snode = dev.logical_id[1]
|
4946 |
else:
|
4947 |
snode = dev.logical_id[0]
|
4948 |
|
4949 |
if snode and not static: |
4950 |
self.cfg.SetDiskID(dev, snode)
|
4951 |
dev_sstatus = self.rpc.call_blockdev_find(snode, dev)
|
4952 |
dev_sstatus.Raise() |
4953 |
dev_sstatus = dev_sstatus.data |
4954 |
else:
|
4955 |
dev_sstatus = None
|
4956 |
|
4957 |
if dev.children:
|
4958 |
dev_children = [self._ComputeDiskStatus(instance, snode, child)
|
4959 |
for child in dev.children] |
4960 |
else:
|
4961 |
dev_children = [] |
4962 |
|
4963 |
data = { |
4964 |
"iv_name": dev.iv_name,
|
4965 |
"dev_type": dev.dev_type,
|
4966 |
"logical_id": dev.logical_id,
|
4967 |
"physical_id": dev.physical_id,
|
4968 |
"pstatus": dev_pstatus,
|
4969 |
"sstatus": dev_sstatus,
|
4970 |
"children": dev_children,
|
4971 |
"mode": dev.mode,
|
4972 |
} |
4973 |
|
4974 |
return data
|
4975 |
|
4976 |
def Exec(self, feedback_fn): |
4977 |
"""Gather and return data"""
|
4978 |
result = {} |
4979 |
|
4980 |
cluster = self.cfg.GetClusterInfo()
|
4981 |
|
4982 |
for instance in self.wanted_instances: |
4983 |
if not self.op.static: |
4984 |
remote_info = self.rpc.call_instance_info(instance.primary_node,
|
4985 |
instance.name, |
4986 |
instance.hypervisor) |
4987 |
remote_info.Raise() |
4988 |
remote_info = remote_info.data |
4989 |
if remote_info and "state" in remote_info: |
4990 |
remote_state = "up"
|
4991 |
else:
|
4992 |
remote_state = "down"
|
4993 |
else:
|
4994 |
remote_state = None
|
4995 |
if instance.status == "down": |
4996 |
config_state = "down"
|
4997 |
else:
|
4998 |
config_state = "up"
|
4999 |
|
5000 |
disks = [self._ComputeDiskStatus(instance, None, device) |
5001 |
for device in instance.disks] |
5002 |
|
5003 |
idict = { |
5004 |
"name": instance.name,
|
5005 |
"config_state": config_state,
|
5006 |
"run_state": remote_state,
|
5007 |
"pnode": instance.primary_node,
|
5008 |
"snodes": instance.secondary_nodes,
|
5009 |
"os": instance.os,
|
5010 |
"nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics], |
5011 |
"disks": disks,
|
5012 |
"hypervisor": instance.hypervisor,
|
5013 |
"network_port": instance.network_port,
|
5014 |
"hv_instance": instance.hvparams,
|
5015 |
"hv_actual": cluster.FillHV(instance),
|
5016 |
"be_instance": instance.beparams,
|
5017 |
"be_actual": cluster.FillBE(instance),
|
5018 |
} |
5019 |
|
5020 |
result[instance.name] = idict |
5021 |
|
5022 |
return result
|
5023 |
|
5024 |
|
5025 |
class LUSetInstanceParams(LogicalUnit): |
5026 |
"""Modifies an instances's parameters.
|
5027 |
|
5028 |
"""
|
5029 |
HPATH = "instance-modify"
|
5030 |
HTYPE = constants.HTYPE_INSTANCE |
5031 |
_OP_REQP = ["instance_name"]
|
5032 |
REQ_BGL = False
|
5033 |
|
5034 |
def CheckArguments(self): |
5035 |
if not hasattr(self.op, 'nics'): |
5036 |
self.op.nics = []
|
5037 |
if not hasattr(self.op, 'disks'): |
5038 |
self.op.disks = []
|
5039 |
if not hasattr(self.op, 'beparams'): |
5040 |
self.op.beparams = {}
|
5041 |
if not hasattr(self.op, 'hvparams'): |
5042 |
self.op.hvparams = {}
|
5043 |
self.op.force = getattr(self.op, "force", False) |
5044 |
if not (self.op.nics or self.op.disks or |
5045 |
self.op.hvparams or self.op.beparams): |
5046 |
raise errors.OpPrereqError("No changes submitted") |
5047 |
|
5048 |
utils.CheckBEParams(self.op.beparams)
|
5049 |
|
5050 |
# Disk validation
|
5051 |
disk_addremove = 0
|
5052 |
for disk_op, disk_dict in self.op.disks: |
5053 |
if disk_op == constants.DDM_REMOVE:
|
5054 |
disk_addremove += 1
|
5055 |
continue
|
5056 |
elif disk_op == constants.DDM_ADD:
|
5057 |
disk_addremove += 1
|
5058 |
else:
|
5059 |
if not isinstance(disk_op, int): |
5060 |
raise errors.OpPrereqError("Invalid disk index") |
5061 |
if disk_op == constants.DDM_ADD:
|
5062 |
mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
|
5063 |
if mode not in (constants.DISK_RDONLY, constants.DISK_RDWR): |
5064 |
raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode) |
5065 |
size = disk_dict.get('size', None) |
5066 |
if size is None: |
5067 |
raise errors.OpPrereqError("Required disk parameter size missing") |
5068 |
try:
|
5069 |
size = int(size)
|
5070 |
except ValueError, err: |
5071 |
raise errors.OpPrereqError("Invalid disk size parameter: %s" % |
5072 |
str(err))
|
5073 |
disk_dict['size'] = size
|
5074 |
else:
|
5075 |
# modification of disk
|
5076 |
if 'size' in disk_dict: |
5077 |
raise errors.OpPrereqError("Disk size change not possible, use" |
5078 |
" grow-disk")
|
5079 |
|
5080 |
if disk_addremove > 1: |
5081 |
raise errors.OpPrereqError("Only one disk add or remove operation" |
5082 |
" supported at a time")
|
5083 |
|
5084 |
# NIC validation
|
5085 |
nic_addremove = 0
|
5086 |
for nic_op, nic_dict in self.op.nics: |
5087 |
if nic_op == constants.DDM_REMOVE:
|
5088 |
nic_addremove += 1
|
5089 |
continue
|
5090 |
elif nic_op == constants.DDM_ADD:
|
5091 |
nic_addremove += 1
|
5092 |
else:
|
5093 |
if not isinstance(nic_op, int): |
5094 |
raise errors.OpPrereqError("Invalid nic index") |
5095 |
|
5096 |
# nic_dict should be a dict
|
5097 |
nic_ip = nic_dict.get('ip', None) |
5098 |
if nic_ip is not None: |
5099 |
if nic_ip.lower() == "none": |
5100 |
nic_dict['ip'] = None |
5101 |
else:
|
5102 |
if not utils.IsValidIP(nic_ip): |
5103 |
raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip) |
5104 |
# we can only check None bridges and assign the default one
|
5105 |
nic_bridge = nic_dict.get('bridge', None) |
5106 |
if nic_bridge is None: |
5107 |
nic_dict['bridge'] = self.cfg.GetDefBridge() |
5108 |
# but we can validate MACs
|
5109 |
nic_mac = nic_dict.get('mac', None) |
5110 |
if nic_mac is not None: |
5111 |
if self.cfg.IsMacInUse(nic_mac): |
5112 |
raise errors.OpPrereqError("MAC address %s already in use" |
5113 |
" in cluster" % nic_mac)
|
5114 |
if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
5115 |
if not utils.IsValidMac(nic_mac): |
5116 |
raise errors.OpPrereqError("Invalid MAC address %s" % nic_mac) |
5117 |
if nic_addremove > 1: |
5118 |
raise errors.OpPrereqError("Only one NIC add or remove operation" |
5119 |
" supported at a time")
|
5120 |
|
5121 |
def ExpandNames(self): |
5122 |
self._ExpandAndLockInstance()
|
5123 |
self.needed_locks[locking.LEVEL_NODE] = []
|
5124 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
5125 |
|
5126 |
def DeclareLocks(self, level): |
5127 |
if level == locking.LEVEL_NODE:
|
5128 |
self._LockInstancesNodes()
|
5129 |
|
5130 |
def BuildHooksEnv(self): |
5131 |
"""Build hooks env.
|
5132 |
|
5133 |
This runs on the master, primary and secondaries.
|
5134 |
|
5135 |
"""
|
5136 |
args = dict()
|
5137 |
if constants.BE_MEMORY in self.be_new: |
5138 |
args['memory'] = self.be_new[constants.BE_MEMORY] |
5139 |
if constants.BE_VCPUS in self.be_new: |
5140 |
args['vcpus'] = self.be_new[constants.BE_VCPUS] |
5141 |
# FIXME: readd disk/nic changes
|
5142 |
env = _BuildInstanceHookEnvByObject(self, self.instance, override=args) |
5143 |
nl = [self.cfg.GetMasterNode(),
|
5144 |
self.instance.primary_node] + list(self.instance.secondary_nodes) |
5145 |
return env, nl, nl
|
5146 |
|
5147 |
def CheckPrereq(self): |
5148 |
"""Check prerequisites.
|
5149 |
|
5150 |
This only checks the instance list against the existing names.
|
5151 |
|
5152 |
"""
|
5153 |
force = self.force = self.op.force |
5154 |
|
5155 |
# checking the new params on the primary/secondary nodes
|
5156 |
|
5157 |
instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name) |
5158 |
assert self.instance is not None, \ |
5159 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
5160 |
pnode = self.instance.primary_node
|
5161 |
nodelist = [pnode] |
5162 |
nodelist.extend(instance.secondary_nodes) |
5163 |
|
5164 |
# hvparams processing
|
5165 |
if self.op.hvparams: |
5166 |
i_hvdict = copy.deepcopy(instance.hvparams) |
5167 |
for key, val in self.op.hvparams.iteritems(): |
5168 |
if val == constants.VALUE_DEFAULT:
|
5169 |
try:
|
5170 |
del i_hvdict[key]
|
5171 |
except KeyError: |
5172 |
pass
|
5173 |
elif val == constants.VALUE_NONE:
|
5174 |
i_hvdict[key] = None
|
5175 |
else:
|
5176 |
i_hvdict[key] = val |
5177 |
cluster = self.cfg.GetClusterInfo()
|
5178 |
hv_new = cluster.FillDict(cluster.hvparams[instance.hypervisor], |
5179 |
i_hvdict) |
5180 |
# local check
|
5181 |
hypervisor.GetHypervisor( |
5182 |
instance.hypervisor).CheckParameterSyntax(hv_new) |
5183 |
_CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
|
5184 |
self.hv_new = hv_new # the new actual values |
5185 |
self.hv_inst = i_hvdict # the new dict (without defaults) |
5186 |
else:
|
5187 |
self.hv_new = self.hv_inst = {} |
5188 |
|
5189 |
# beparams processing
|
5190 |
if self.op.beparams: |
5191 |
i_bedict = copy.deepcopy(instance.beparams) |
5192 |
for key, val in self.op.beparams.iteritems(): |
5193 |
if val == constants.VALUE_DEFAULT:
|
5194 |
try:
|
5195 |
del i_bedict[key]
|
5196 |
except KeyError: |
5197 |
pass
|
5198 |
else:
|
5199 |
i_bedict[key] = val |
5200 |
cluster = self.cfg.GetClusterInfo()
|
5201 |
be_new = cluster.FillDict(cluster.beparams[constants.BEGR_DEFAULT], |
5202 |
i_bedict) |
5203 |
self.be_new = be_new # the new actual values |
5204 |
self.be_inst = i_bedict # the new dict (without defaults) |
5205 |
else:
|
5206 |
self.be_new = self.be_inst = {} |
5207 |
|
5208 |
self.warn = []
|
5209 |
|
5210 |
if constants.BE_MEMORY in self.op.beparams and not self.force: |
5211 |
mem_check_list = [pnode] |
5212 |
if be_new[constants.BE_AUTO_BALANCE]:
|
5213 |
# either we changed auto_balance to yes or it was from before
|
5214 |
mem_check_list.extend(instance.secondary_nodes) |
5215 |
instance_info = self.rpc.call_instance_info(pnode, instance.name,
|
5216 |
instance.hypervisor) |
5217 |
nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(), |
5218 |
instance.hypervisor) |
5219 |
if nodeinfo[pnode].failed or not isinstance(nodeinfo[pnode].data, dict): |
5220 |
# Assume the primary node is unreachable and go ahead
|
5221 |
self.warn.append("Can't get info from primary node %s" % pnode) |
5222 |
else:
|
5223 |
if not instance_info.failed and instance_info.data: |
5224 |
current_mem = instance_info.data['memory']
|
5225 |
else:
|
5226 |
# Assume instance not running
|
5227 |
# (there is a slight race condition here, but it's not very probable,
|
5228 |
# and we have no other way to check)
|
5229 |
current_mem = 0
|
5230 |
miss_mem = (be_new[constants.BE_MEMORY] - current_mem - |
5231 |
nodeinfo[pnode].data['memory_free'])
|
5232 |
if miss_mem > 0: |
5233 |
raise errors.OpPrereqError("This change will prevent the instance" |
5234 |
" from starting, due to %d MB of memory"
|
5235 |
" missing on its primary node" % miss_mem)
|
5236 |
|
5237 |
if be_new[constants.BE_AUTO_BALANCE]:
|
5238 |
for node, nres in instance.secondary_nodes.iteritems(): |
5239 |
if nres.failed or not isinstance(nres.data, dict): |
5240 |
self.warn.append("Can't get info from secondary node %s" % node) |
5241 |
elif be_new[constants.BE_MEMORY] > nres.data['memory_free']: |
5242 |
self.warn.append("Not enough memory to failover instance to" |
5243 |
" secondary node %s" % node)
|
5244 |
|
5245 |
# NIC processing
|
5246 |
for nic_op, nic_dict in self.op.nics: |
5247 |
if nic_op == constants.DDM_REMOVE:
|
5248 |
if not instance.nics: |
5249 |
raise errors.OpPrereqError("Instance has no NICs, cannot remove") |
5250 |
continue
|
5251 |
if nic_op != constants.DDM_ADD:
|
5252 |
# an existing nic
|
5253 |
if nic_op < 0 or nic_op >= len(instance.nics): |
5254 |
raise errors.OpPrereqError("Invalid NIC index %s, valid values" |
5255 |
" are 0 to %d" %
|
5256 |
(nic_op, len(instance.nics)))
|
5257 |
nic_bridge = nic_dict.get('bridge', None) |
5258 |
if nic_bridge is not None: |
5259 |
if not self.rpc.call_bridges_exist(pnode, [nic_bridge]): |
5260 |
msg = ("Bridge '%s' doesn't exist on one of"
|
5261 |
" the instance nodes" % nic_bridge)
|
5262 |
if self.force: |
5263 |
self.warn.append(msg)
|
5264 |
else:
|
5265 |
raise errors.OpPrereqError(msg)
|
5266 |
|
5267 |
# DISK processing
|
5268 |
if self.op.disks and instance.disk_template == constants.DT_DISKLESS: |
5269 |
raise errors.OpPrereqError("Disk operations not supported for" |
5270 |
" diskless instances")
|
5271 |
for disk_op, disk_dict in self.op.disks: |
5272 |
if disk_op == constants.DDM_REMOVE:
|
5273 |
if len(instance.disks) == 1: |
5274 |
raise errors.OpPrereqError("Cannot remove the last disk of" |
5275 |
" an instance")
|
5276 |
ins_l = self.rpc.call_instance_list([pnode], [instance.hypervisor])
|
5277 |
ins_l = ins_l[pnode] |
5278 |
if not type(ins_l) is list: |
5279 |
raise errors.OpPrereqError("Can't contact node '%s'" % pnode) |
5280 |
if instance.name in ins_l: |
5281 |
raise errors.OpPrereqError("Instance is running, can't remove" |
5282 |
" disks.")
|
5283 |
|
5284 |
if (disk_op == constants.DDM_ADD and |
5285 |
len(instance.nics) >= constants.MAX_DISKS):
|
5286 |
raise errors.OpPrereqError("Instance has too many disks (%d), cannot" |
5287 |
" add more" % constants.MAX_DISKS)
|
5288 |
if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE): |
5289 |
# an existing disk
|
5290 |
if disk_op < 0 or disk_op >= len(instance.disks): |
5291 |
raise errors.OpPrereqError("Invalid disk index %s, valid values" |
5292 |
" are 0 to %d" %
|
5293 |
(disk_op, len(instance.disks)))
|
5294 |
|
5295 |
return
|
5296 |
|
5297 |
def Exec(self, feedback_fn): |
5298 |
"""Modifies an instance.
|
5299 |
|
5300 |
All parameters take effect only at the next restart of the instance.
|
5301 |
|
5302 |
"""
|
5303 |
# Process here the warnings from CheckPrereq, as we don't have a
|
5304 |
# feedback_fn there.
|
5305 |
for warn in self.warn: |
5306 |
feedback_fn("WARNING: %s" % warn)
|
5307 |
|
5308 |
result = [] |
5309 |
instance = self.instance
|
5310 |
# disk changes
|
5311 |
for disk_op, disk_dict in self.op.disks: |
5312 |
if disk_op == constants.DDM_REMOVE:
|
5313 |
# remove the last disk
|
5314 |
device = instance.disks.pop() |
5315 |
device_idx = len(instance.disks)
|
5316 |
for node, disk in device.ComputeNodeTree(instance.primary_node): |
5317 |
self.cfg.SetDiskID(disk, node)
|
5318 |
result = self.rpc.call_blockdev_remove(node, disk)
|
5319 |
if result.failed or not result.data: |
5320 |
self.proc.LogWarning("Could not remove disk/%d on node %s," |
5321 |
" continuing anyway", device_idx, node)
|
5322 |
result.append(("disk/%d" % device_idx, "remove")) |
5323 |
elif disk_op == constants.DDM_ADD:
|
5324 |
# add a new disk
|
5325 |
if instance.disk_template == constants.DT_FILE:
|
5326 |
file_driver, file_path = instance.disks[0].logical_id
|
5327 |
file_path = os.path.dirname(file_path) |
5328 |
else:
|
5329 |
file_driver = file_path = None
|
5330 |
disk_idx_base = len(instance.disks)
|
5331 |
new_disk = _GenerateDiskTemplate(self,
|
5332 |
instance.disk_template, |
5333 |
instance, instance.primary_node, |
5334 |
instance.secondary_nodes, |
5335 |
[disk_dict], |
5336 |
file_path, |
5337 |
file_driver, |
5338 |
disk_idx_base)[0]
|
5339 |
new_disk.mode = disk_dict['mode']
|
5340 |
instance.disks.append(new_disk) |
5341 |
info = _GetInstanceInfoText(instance) |
5342 |
|
5343 |
logging.info("Creating volume %s for instance %s",
|
5344 |
new_disk.iv_name, instance.name) |
5345 |
# Note: this needs to be kept in sync with _CreateDisks
|
5346 |
#HARDCODE
|
5347 |
for secondary_node in instance.secondary_nodes: |
5348 |
if not _CreateBlockDevOnSecondary(self, secondary_node, instance, |
5349 |
new_disk, False, info):
|
5350 |
self.LogWarning("Failed to create volume %s (%s) on" |
5351 |
" secondary node %s!",
|
5352 |
new_disk.iv_name, new_disk, secondary_node) |
5353 |
#HARDCODE
|
5354 |
if not _CreateBlockDevOnPrimary(self, instance.primary_node, |
5355 |
instance, new_disk, info): |
5356 |
self.LogWarning("Failed to create volume %s on primary!", |
5357 |
new_disk.iv_name) |
5358 |
result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" % |
5359 |
(new_disk.size, new_disk.mode))) |
5360 |
else:
|
5361 |
# change a given disk
|
5362 |
instance.disks[disk_op].mode = disk_dict['mode']
|
5363 |
result.append(("disk.mode/%d" % disk_op, disk_dict['mode'])) |
5364 |
# NIC changes
|
5365 |
for nic_op, nic_dict in self.op.nics: |
5366 |
if nic_op == constants.DDM_REMOVE:
|
5367 |
# remove the last nic
|
5368 |
del instance.nics[-1] |
5369 |
result.append(("nic.%d" % len(instance.nics), "remove")) |
5370 |
elif nic_op == constants.DDM_ADD:
|
5371 |
# add a new nic
|
5372 |
if 'mac' not in nic_dict: |
5373 |
mac = constants.VALUE_GENERATE |
5374 |
else:
|
5375 |
mac = nic_dict['mac']
|
5376 |
if mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
5377 |
mac = self.cfg.GenerateMAC()
|
5378 |
new_nic = objects.NIC(mac=mac, ip=nic_dict.get('ip', None), |
5379 |
bridge=nic_dict.get('bridge', None)) |
5380 |
instance.nics.append(new_nic) |
5381 |
result.append(("nic.%d" % (len(instance.nics) - 1), |
5382 |
"add:mac=%s,ip=%s,bridge=%s" %
|
5383 |
(new_nic.mac, new_nic.ip, new_nic.bridge))) |
5384 |
else:
|
5385 |
# change a given nic
|
5386 |
for key in 'mac', 'ip', 'bridge': |
5387 |
if key in nic_dict: |
5388 |
setattr(instance.nics[nic_op], key, nic_dict[key])
|
5389 |
result.append(("nic.%s/%d" % (key, nic_op), nic_dict[key]))
|
5390 |
|
5391 |
# hvparams changes
|
5392 |
if self.op.hvparams: |
5393 |
instance.hvparams = self.hv_new
|
5394 |
for key, val in self.op.hvparams.iteritems(): |
5395 |
result.append(("hv/%s" % key, val))
|
5396 |
|
5397 |
# beparams changes
|
5398 |
if self.op.beparams: |
5399 |
instance.beparams = self.be_inst
|
5400 |
for key, val in self.op.beparams.iteritems(): |
5401 |
result.append(("be/%s" % key, val))
|
5402 |
|
5403 |
self.cfg.Update(instance)
|
5404 |
|
5405 |
return result
|
5406 |
|
5407 |
|
5408 |
class LUQueryExports(NoHooksLU): |
5409 |
"""Query the exports list
|
5410 |
|
5411 |
"""
|
5412 |
_OP_REQP = ['nodes']
|
5413 |
REQ_BGL = False
|
5414 |
|
5415 |
def ExpandNames(self): |
5416 |
self.needed_locks = {}
|
5417 |
self.share_locks[locking.LEVEL_NODE] = 1 |
5418 |
if not self.op.nodes: |
5419 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
5420 |
else:
|
5421 |
self.needed_locks[locking.LEVEL_NODE] = \
|
5422 |
_GetWantedNodes(self, self.op.nodes) |
5423 |
|
5424 |
def CheckPrereq(self): |
5425 |
"""Check prerequisites.
|
5426 |
|
5427 |
"""
|
5428 |
self.nodes = self.acquired_locks[locking.LEVEL_NODE] |
5429 |
|
5430 |
def Exec(self, feedback_fn): |
5431 |
"""Compute the list of all the exported system images.
|
5432 |
|
5433 |
@rtype: dict
|
5434 |
@return: a dictionary with the structure node->(export-list)
|
5435 |
where export-list is a list of the instances exported on
|
5436 |
that node.
|
5437 |
|
5438 |
"""
|
5439 |
rpcresult = self.rpc.call_export_list(self.nodes) |
5440 |
result = {} |
5441 |
for node in rpcresult: |
5442 |
if rpcresult[node].failed:
|
5443 |
result[node] = False
|
5444 |
else:
|
5445 |
result[node] = rpcresult[node].data |
5446 |
|
5447 |
return result
|
5448 |
|
5449 |
|
5450 |
class LUExportInstance(LogicalUnit): |
5451 |
"""Export an instance to an image in the cluster.
|
5452 |
|
5453 |
"""
|
5454 |
HPATH = "instance-export"
|
5455 |
HTYPE = constants.HTYPE_INSTANCE |
5456 |
_OP_REQP = ["instance_name", "target_node", "shutdown"] |
5457 |
REQ_BGL = False
|
5458 |
|
5459 |
def ExpandNames(self): |
5460 |
self._ExpandAndLockInstance()
|
5461 |
# FIXME: lock only instance primary and destination node
|
5462 |
#
|
5463 |
# Sad but true, for now we have do lock all nodes, as we don't know where
|
5464 |
# the previous export might be, and and in this LU we search for it and
|
5465 |
# remove it from its current node. In the future we could fix this by:
|
5466 |
# - making a tasklet to search (share-lock all), then create the new one,
|
5467 |
# then one to remove, after
|
5468 |
# - removing the removal operation altoghether
|
5469 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
5470 |
|
5471 |
def DeclareLocks(self, level): |
5472 |
"""Last minute lock declaration."""
|
5473 |
# All nodes are locked anyway, so nothing to do here.
|
5474 |
|
5475 |
def BuildHooksEnv(self): |
5476 |
"""Build hooks env.
|
5477 |
|
5478 |
This will run on the master, primary node and target node.
|
5479 |
|
5480 |
"""
|
5481 |
env = { |
5482 |
"EXPORT_NODE": self.op.target_node, |
5483 |
"EXPORT_DO_SHUTDOWN": self.op.shutdown, |
5484 |
} |
5485 |
env.update(_BuildInstanceHookEnvByObject(self, self.instance)) |
5486 |
nl = [self.cfg.GetMasterNode(), self.instance.primary_node, |
5487 |
self.op.target_node]
|
5488 |
return env, nl, nl
|
5489 |
|
5490 |
def CheckPrereq(self): |
5491 |
"""Check prerequisites.
|
5492 |
|
5493 |
This checks that the instance and node names are valid.
|
5494 |
|
5495 |
"""
|
5496 |
instance_name = self.op.instance_name
|
5497 |
self.instance = self.cfg.GetInstanceInfo(instance_name) |
5498 |
assert self.instance is not None, \ |
5499 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
5500 |
_CheckNodeOnline(self, instance.primary_node)
|
5501 |
|
5502 |
self.dst_node = self.cfg.GetNodeInfo( |
5503 |
self.cfg.ExpandNodeName(self.op.target_node)) |
5504 |
|
5505 |
if self.dst_node is None: |
5506 |
# This is wrong node name, not a non-locked node
|
5507 |
raise errors.OpPrereqError("Wrong node name %s" % self.op.target_node) |
5508 |
_CheckNodeOnline(self, self.op.target_node) |
5509 |
|
5510 |
# instance disk type verification
|
5511 |
for disk in self.instance.disks: |
5512 |
if disk.dev_type == constants.LD_FILE:
|
5513 |
raise errors.OpPrereqError("Export not supported for instances with" |
5514 |
" file-based disks")
|
5515 |
|
5516 |
def Exec(self, feedback_fn): |
5517 |
"""Export an instance to an image in the cluster.
|
5518 |
|
5519 |
"""
|
5520 |
instance = self.instance
|
5521 |
dst_node = self.dst_node
|
5522 |
src_node = instance.primary_node |
5523 |
if self.op.shutdown: |
5524 |
# shutdown the instance, but not the disks
|
5525 |
result = self.rpc.call_instance_shutdown(src_node, instance)
|
5526 |
result.Raise() |
5527 |
if not result.data: |
5528 |
raise errors.OpExecError("Could not shutdown instance %s on node %s" % |
5529 |
(instance.name, src_node)) |
5530 |
|
5531 |
vgname = self.cfg.GetVGName()
|
5532 |
|
5533 |
snap_disks = [] |
5534 |
|
5535 |
try:
|
5536 |
for disk in instance.disks: |
5537 |
# new_dev_name will be a snapshot of an lvm leaf of the one we passed
|
5538 |
new_dev_name = self.rpc.call_blockdev_snapshot(src_node, disk)
|
5539 |
if new_dev_name.failed or not new_dev_name.data: |
5540 |
self.LogWarning("Could not snapshot block device %s on node %s", |
5541 |
disk.logical_id[1], src_node)
|
5542 |
snap_disks.append(False)
|
5543 |
else:
|
5544 |
new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size, |
5545 |
logical_id=(vgname, new_dev_name.data), |
5546 |
physical_id=(vgname, new_dev_name.data), |
5547 |
iv_name=disk.iv_name) |
5548 |
snap_disks.append(new_dev) |
5549 |
|
5550 |
finally:
|
5551 |
if self.op.shutdown and instance.status == "up": |
5552 |
result = self.rpc.call_instance_start(src_node, instance, None) |
5553 |
if result.failed or not result.data: |
5554 |
_ShutdownInstanceDisks(self, instance)
|
5555 |
raise errors.OpExecError("Could not start instance") |
5556 |
|
5557 |
# TODO: check for size
|
5558 |
|
5559 |
cluster_name = self.cfg.GetClusterName()
|
5560 |
for idx, dev in enumerate(snap_disks): |
5561 |
if dev:
|
5562 |
result = self.rpc.call_snapshot_export(src_node, dev, dst_node.name,
|
5563 |
instance, cluster_name, idx) |
5564 |
if result.failed or not result.data: |
5565 |
self.LogWarning("Could not export block device %s from node %s to" |
5566 |
" node %s", dev.logical_id[1], src_node, |
5567 |
dst_node.name) |
5568 |
result = self.rpc.call_blockdev_remove(src_node, dev)
|
5569 |
if result.failed or not result.data: |
5570 |
self.LogWarning("Could not remove snapshot block device %s from node" |
5571 |
" %s", dev.logical_id[1], src_node) |
5572 |
|
5573 |
result = self.rpc.call_finalize_export(dst_node.name, instance, snap_disks)
|
5574 |
if result.failed or not result.data: |
5575 |
self.LogWarning("Could not finalize export for instance %s on node %s", |
5576 |
instance.name, dst_node.name) |
5577 |
|
5578 |
nodelist = self.cfg.GetNodeList()
|
5579 |
nodelist.remove(dst_node.name) |
5580 |
|
5581 |
# on one-node clusters nodelist will be empty after the removal
|
5582 |
# if we proceed the backup would be removed because OpQueryExports
|
5583 |
# substitutes an empty list with the full cluster node list.
|
5584 |
if nodelist:
|
5585 |
exportlist = self.rpc.call_export_list(nodelist)
|
5586 |
for node in exportlist: |
5587 |
if exportlist[node].failed:
|
5588 |
continue
|
5589 |
if instance.name in exportlist[node].data: |
5590 |
if not self.rpc.call_export_remove(node, instance.name): |
5591 |
self.LogWarning("Could not remove older export for instance %s" |
5592 |
" on node %s", instance.name, node)
|
5593 |
|
5594 |
|
5595 |
class LURemoveExport(NoHooksLU): |
5596 |
"""Remove exports related to the named instance.
|
5597 |
|
5598 |
"""
|
5599 |
_OP_REQP = ["instance_name"]
|
5600 |
REQ_BGL = False
|
5601 |
|
5602 |
def ExpandNames(self): |
5603 |
self.needed_locks = {}
|
5604 |
# We need all nodes to be locked in order for RemoveExport to work, but we
|
5605 |
# don't need to lock the instance itself, as nothing will happen to it (and
|
5606 |
# we can remove exports also for a removed instance)
|
5607 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
5608 |
|
5609 |
def CheckPrereq(self): |
5610 |
"""Check prerequisites.
|
5611 |
"""
|
5612 |
pass
|
5613 |
|
5614 |
def Exec(self, feedback_fn): |
5615 |
"""Remove any export.
|
5616 |
|
5617 |
"""
|
5618 |
instance_name = self.cfg.ExpandInstanceName(self.op.instance_name) |
5619 |
# If the instance was not found we'll try with the name that was passed in.
|
5620 |
# This will only work if it was an FQDN, though.
|
5621 |
fqdn_warn = False
|
5622 |
if not instance_name: |
5623 |
fqdn_warn = True
|
5624 |
instance_name = self.op.instance_name
|
5625 |
|
5626 |
exportlist = self.rpc.call_export_list(self.acquired_locks[ |
5627 |
locking.LEVEL_NODE]) |
5628 |
found = False
|
5629 |
for node in exportlist: |
5630 |
if exportlist[node].failed:
|
5631 |
self.LogWarning("Failed to query node %s, continuing" % node) |
5632 |
continue
|
5633 |
if instance_name in exportlist[node].data: |
5634 |
found = True
|
5635 |
result = self.rpc.call_export_remove(node, instance_name)
|
5636 |
if result.failed or not result.data: |
5637 |
logging.error("Could not remove export for instance %s"
|
5638 |
" on node %s", instance_name, node)
|
5639 |
|
5640 |
if fqdn_warn and not found: |
5641 |
feedback_fn("Export not found. If trying to remove an export belonging"
|
5642 |
" to a deleted instance please use its Fully Qualified"
|
5643 |
" Domain Name.")
|
5644 |
|
5645 |
|
5646 |
class TagsLU(NoHooksLU): |
5647 |
"""Generic tags LU.
|
5648 |
|
5649 |
This is an abstract class which is the parent of all the other tags LUs.
|
5650 |
|
5651 |
"""
|
5652 |
|
5653 |
def ExpandNames(self): |
5654 |
self.needed_locks = {}
|
5655 |
if self.op.kind == constants.TAG_NODE: |
5656 |
name = self.cfg.ExpandNodeName(self.op.name) |
5657 |
if name is None: |
5658 |
raise errors.OpPrereqError("Invalid node name (%s)" % |
5659 |
(self.op.name,))
|
5660 |
self.op.name = name
|
5661 |
self.needed_locks[locking.LEVEL_NODE] = name
|
5662 |
elif self.op.kind == constants.TAG_INSTANCE: |
5663 |
name = self.cfg.ExpandInstanceName(self.op.name) |
5664 |
if name is None: |
5665 |
raise errors.OpPrereqError("Invalid instance name (%s)" % |
5666 |
(self.op.name,))
|
5667 |
self.op.name = name
|
5668 |
self.needed_locks[locking.LEVEL_INSTANCE] = name
|
5669 |
|
5670 |
def CheckPrereq(self): |
5671 |
"""Check prerequisites.
|
5672 |
|
5673 |
"""
|
5674 |
if self.op.kind == constants.TAG_CLUSTER: |
5675 |
self.target = self.cfg.GetClusterInfo() |
5676 |
elif self.op.kind == constants.TAG_NODE: |
5677 |
self.target = self.cfg.GetNodeInfo(self.op.name) |
5678 |
elif self.op.kind == constants.TAG_INSTANCE: |
5679 |
self.target = self.cfg.GetInstanceInfo(self.op.name) |
5680 |
else:
|
5681 |
raise errors.OpPrereqError("Wrong tag type requested (%s)" % |
5682 |
str(self.op.kind)) |
5683 |
|
5684 |
|
5685 |
class LUGetTags(TagsLU): |
5686 |
"""Returns the tags of a given object.
|
5687 |
|
5688 |
"""
|
5689 |
_OP_REQP = ["kind", "name"] |
5690 |
REQ_BGL = False
|
5691 |
|
5692 |
def Exec(self, feedback_fn): |
5693 |
"""Returns the tag list.
|
5694 |
|
5695 |
"""
|
5696 |
return list(self.target.GetTags()) |
5697 |
|
5698 |
|
5699 |
class LUSearchTags(NoHooksLU): |
5700 |
"""Searches the tags for a given pattern.
|
5701 |
|
5702 |
"""
|
5703 |
_OP_REQP = ["pattern"]
|
5704 |
REQ_BGL = False
|
5705 |
|
5706 |
def ExpandNames(self): |
5707 |
self.needed_locks = {}
|
5708 |
|
5709 |
def CheckPrereq(self): |
5710 |
"""Check prerequisites.
|
5711 |
|
5712 |
This checks the pattern passed for validity by compiling it.
|
5713 |
|
5714 |
"""
|
5715 |
try:
|
5716 |
self.re = re.compile(self.op.pattern) |
5717 |
except re.error, err:
|
5718 |
raise errors.OpPrereqError("Invalid search pattern '%s': %s" % |
5719 |
(self.op.pattern, err))
|
5720 |
|
5721 |
def Exec(self, feedback_fn): |
5722 |
"""Returns the tag list.
|
5723 |
|
5724 |
"""
|
5725 |
cfg = self.cfg
|
5726 |
tgts = [("/cluster", cfg.GetClusterInfo())]
|
5727 |
ilist = cfg.GetAllInstancesInfo().values() |
5728 |
tgts.extend([("/instances/%s" % i.name, i) for i in ilist]) |
5729 |
nlist = cfg.GetAllNodesInfo().values() |
5730 |
tgts.extend([("/nodes/%s" % n.name, n) for n in nlist]) |
5731 |
results = [] |
5732 |
for path, target in tgts: |
5733 |
for tag in target.GetTags(): |
5734 |
if self.re.search(tag): |
5735 |
results.append((path, tag)) |
5736 |
return results
|
5737 |
|
5738 |
|
5739 |
class LUAddTags(TagsLU): |
5740 |
"""Sets a tag on a given object.
|
5741 |
|
5742 |
"""
|
5743 |
_OP_REQP = ["kind", "name", "tags"] |
5744 |
REQ_BGL = False
|
5745 |
|
5746 |
def CheckPrereq(self): |
5747 |
"""Check prerequisites.
|
5748 |
|
5749 |
This checks the type and length of the tag name and value.
|
5750 |
|
5751 |
"""
|
5752 |
TagsLU.CheckPrereq(self)
|
5753 |
for tag in self.op.tags: |
5754 |
objects.TaggableObject.ValidateTag(tag) |
5755 |
|
5756 |
def Exec(self, feedback_fn): |
5757 |
"""Sets the tag.
|
5758 |
|
5759 |
"""
|
5760 |
try:
|
5761 |
for tag in self.op.tags: |
5762 |
self.target.AddTag(tag)
|
5763 |
except errors.TagError, err:
|
5764 |
raise errors.OpExecError("Error while setting tag: %s" % str(err)) |
5765 |
try:
|
5766 |
self.cfg.Update(self.target) |
5767 |
except errors.ConfigurationError:
|
5768 |
raise errors.OpRetryError("There has been a modification to the" |
5769 |
" config file and the operation has been"
|
5770 |
" aborted. Please retry.")
|
5771 |
|
5772 |
|
5773 |
class LUDelTags(TagsLU): |
5774 |
"""Delete a list of tags from a given object.
|
5775 |
|
5776 |
"""
|
5777 |
_OP_REQP = ["kind", "name", "tags"] |
5778 |
REQ_BGL = False
|
5779 |
|
5780 |
def CheckPrereq(self): |
5781 |
"""Check prerequisites.
|
5782 |
|
5783 |
This checks that we have the given tag.
|
5784 |
|
5785 |
"""
|
5786 |
TagsLU.CheckPrereq(self)
|
5787 |
for tag in self.op.tags: |
5788 |
objects.TaggableObject.ValidateTag(tag) |
5789 |
del_tags = frozenset(self.op.tags) |
5790 |
cur_tags = self.target.GetTags()
|
5791 |
if not del_tags <= cur_tags: |
5792 |
diff_tags = del_tags - cur_tags |
5793 |
diff_names = ["'%s'" % tag for tag in diff_tags] |
5794 |
diff_names.sort() |
5795 |
raise errors.OpPrereqError("Tag(s) %s not found" % |
5796 |
(",".join(diff_names)))
|
5797 |
|
5798 |
def Exec(self, feedback_fn): |
5799 |
"""Remove the tag from the object.
|
5800 |
|
5801 |
"""
|
5802 |
for tag in self.op.tags: |
5803 |
self.target.RemoveTag(tag)
|
5804 |
try:
|
5805 |
self.cfg.Update(self.target) |
5806 |
except errors.ConfigurationError:
|
5807 |
raise errors.OpRetryError("There has been a modification to the" |
5808 |
" config file and the operation has been"
|
5809 |
" aborted. Please retry.")
|
5810 |
|
5811 |
|
5812 |
class LUTestDelay(NoHooksLU): |
5813 |
"""Sleep for a specified amount of time.
|
5814 |
|
5815 |
This LU sleeps on the master and/or nodes for a specified amount of
|
5816 |
time.
|
5817 |
|
5818 |
"""
|
5819 |
_OP_REQP = ["duration", "on_master", "on_nodes"] |
5820 |
REQ_BGL = False
|
5821 |
|
5822 |
def ExpandNames(self): |
5823 |
"""Expand names and set required locks.
|
5824 |
|
5825 |
This expands the node list, if any.
|
5826 |
|
5827 |
"""
|
5828 |
self.needed_locks = {}
|
5829 |
if self.op.on_nodes: |
5830 |
# _GetWantedNodes can be used here, but is not always appropriate to use
|
5831 |
# this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
|
5832 |
# more information.
|
5833 |
self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes) |
5834 |
self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes |
5835 |
|
5836 |
def CheckPrereq(self): |
5837 |
"""Check prerequisites.
|
5838 |
|
5839 |
"""
|
5840 |
|
5841 |
def Exec(self, feedback_fn): |
5842 |
"""Do the actual sleep.
|
5843 |
|
5844 |
"""
|
5845 |
if self.op.on_master: |
5846 |
if not utils.TestDelay(self.op.duration): |
5847 |
raise errors.OpExecError("Error during master delay test") |
5848 |
if self.op.on_nodes: |
5849 |
result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration) |
5850 |
if not result: |
5851 |
raise errors.OpExecError("Complete failure from rpc call") |
5852 |
for node, node_result in result.items(): |
5853 |
node_result.Raise() |
5854 |
if not node_result.data: |
5855 |
raise errors.OpExecError("Failure during rpc call to node %s," |
5856 |
" result: %s" % (node, node_result.data))
|
5857 |
|
5858 |
|
5859 |
class IAllocator(object): |
5860 |
"""IAllocator framework.
|
5861 |
|
5862 |
An IAllocator instance has three sets of attributes:
|
5863 |
- cfg that is needed to query the cluster
|
5864 |
- input data (all members of the _KEYS class attribute are required)
|
5865 |
- four buffer attributes (in|out_data|text), that represent the
|
5866 |
input (to the external script) in text and data structure format,
|
5867 |
and the output from it, again in two formats
|
5868 |
- the result variables from the script (success, info, nodes) for
|
5869 |
easy usage
|
5870 |
|
5871 |
"""
|
5872 |
_ALLO_KEYS = [ |
5873 |
"mem_size", "disks", "disk_template", |
5874 |
"os", "tags", "nics", "vcpus", "hypervisor", |
5875 |
] |
5876 |
_RELO_KEYS = [ |
5877 |
"relocate_from",
|
5878 |
] |
5879 |
|
5880 |
def __init__(self, lu, mode, name, **kwargs): |
5881 |
self.lu = lu
|
5882 |
# init buffer variables
|
5883 |
self.in_text = self.out_text = self.in_data = self.out_data = None |
5884 |
# init all input fields so that pylint is happy
|
5885 |
self.mode = mode
|
5886 |
self.name = name
|
5887 |
self.mem_size = self.disks = self.disk_template = None |
5888 |
self.os = self.tags = self.nics = self.vcpus = None |
5889 |
self.relocate_from = None |
5890 |
# computed fields
|
5891 |
self.required_nodes = None |
5892 |
# init result fields
|
5893 |
self.success = self.info = self.nodes = None |
5894 |
if self.mode == constants.IALLOCATOR_MODE_ALLOC: |
5895 |
keyset = self._ALLO_KEYS
|
5896 |
elif self.mode == constants.IALLOCATOR_MODE_RELOC: |
5897 |
keyset = self._RELO_KEYS
|
5898 |
else:
|
5899 |
raise errors.ProgrammerError("Unknown mode '%s' passed to the" |
5900 |
" IAllocator" % self.mode) |
5901 |
for key in kwargs: |
5902 |
if key not in keyset: |
5903 |
raise errors.ProgrammerError("Invalid input parameter '%s' to" |
5904 |
" IAllocator" % key)
|
5905 |
setattr(self, key, kwargs[key]) |
5906 |
for key in keyset: |
5907 |
if key not in kwargs: |
5908 |
raise errors.ProgrammerError("Missing input parameter '%s' to" |
5909 |
" IAllocator" % key)
|
5910 |
self._BuildInputData()
|
5911 |
|
5912 |
def _ComputeClusterData(self): |
5913 |
"""Compute the generic allocator input data.
|
5914 |
|
5915 |
This is the data that is independent of the actual operation.
|
5916 |
|
5917 |
"""
|
5918 |
cfg = self.lu.cfg
|
5919 |
cluster_info = cfg.GetClusterInfo() |
5920 |
# cluster data
|
5921 |
data = { |
5922 |
"version": 1, |
5923 |
"cluster_name": cfg.GetClusterName(),
|
5924 |
"cluster_tags": list(cluster_info.GetTags()), |
5925 |
"enable_hypervisors": list(cluster_info.enabled_hypervisors), |
5926 |
# we don't have job IDs
|
5927 |
} |
5928 |
iinfo = cfg.GetAllInstancesInfo().values() |
5929 |
i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo] |
5930 |
|
5931 |
# node data
|
5932 |
node_results = {} |
5933 |
node_list = cfg.GetNodeList() |
5934 |
|
5935 |
if self.mode == constants.IALLOCATOR_MODE_ALLOC: |
5936 |
hypervisor = self.hypervisor
|
5937 |
elif self.mode == constants.IALLOCATOR_MODE_RELOC: |
5938 |
hypervisor = cfg.GetInstanceInfo(self.name).hypervisor
|
5939 |
|
5940 |
node_data = self.lu.rpc.call_node_info(node_list, cfg.GetVGName(),
|
5941 |
hypervisor) |
5942 |
node_iinfo = self.lu.rpc.call_all_instances_info(node_list,
|
5943 |
cluster_info.enabled_hypervisors) |
5944 |
for nname in node_list: |
5945 |
ninfo = cfg.GetNodeInfo(nname) |
5946 |
node_data[nname].Raise() |
5947 |
if not isinstance(node_data[nname].data, dict): |
5948 |
raise errors.OpExecError("Can't get data for node %s" % nname) |
5949 |
remote_info = node_data[nname].data |
5950 |
for attr in ['memory_total', 'memory_free', 'memory_dom0', |
5951 |
'vg_size', 'vg_free', 'cpu_total']: |
5952 |
if attr not in remote_info: |
5953 |
raise errors.OpExecError("Node '%s' didn't return attribute '%s'" % |
5954 |
(nname, attr)) |
5955 |
try:
|
5956 |
remote_info[attr] = int(remote_info[attr])
|
5957 |
except ValueError, err: |
5958 |
raise errors.OpExecError("Node '%s' returned invalid value for '%s':" |
5959 |
" %s" % (nname, attr, str(err))) |
5960 |
# compute memory used by primary instances
|
5961 |
i_p_mem = i_p_up_mem = 0
|
5962 |
for iinfo, beinfo in i_list: |
5963 |
if iinfo.primary_node == nname:
|
5964 |
i_p_mem += beinfo[constants.BE_MEMORY] |
5965 |
if iinfo.name not in node_iinfo[nname]: |
5966 |
i_used_mem = 0
|
5967 |
else:
|
5968 |
i_used_mem = int(node_iinfo[nname][iinfo.name]['memory']) |
5969 |
i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem |
5970 |
remote_info['memory_free'] -= max(0, i_mem_diff) |
5971 |
|
5972 |
if iinfo.status == "up": |
5973 |
i_p_up_mem += beinfo[constants.BE_MEMORY] |
5974 |
|
5975 |
# compute memory used by instances
|
5976 |
pnr = { |
5977 |
"tags": list(ninfo.GetTags()), |
5978 |
"total_memory": remote_info['memory_total'], |
5979 |
"reserved_memory": remote_info['memory_dom0'], |
5980 |
"free_memory": remote_info['memory_free'], |
5981 |
"i_pri_memory": i_p_mem,
|
5982 |
"i_pri_up_memory": i_p_up_mem,
|
5983 |
"total_disk": remote_info['vg_size'], |
5984 |
"free_disk": remote_info['vg_free'], |
5985 |
"primary_ip": ninfo.primary_ip,
|
5986 |
"secondary_ip": ninfo.secondary_ip,
|
5987 |
"total_cpus": remote_info['cpu_total'], |
5988 |
"offline": ninfo.offline,
|
5989 |
} |
5990 |
node_results[nname] = pnr |
5991 |
data["nodes"] = node_results
|
5992 |
|
5993 |
# instance data
|
5994 |
instance_data = {} |
5995 |
for iinfo, beinfo in i_list: |
5996 |
nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge} |
5997 |
for n in iinfo.nics] |
5998 |
pir = { |
5999 |
"tags": list(iinfo.GetTags()), |
6000 |
"should_run": iinfo.status == "up", |
6001 |
"vcpus": beinfo[constants.BE_VCPUS],
|
6002 |
"memory": beinfo[constants.BE_MEMORY],
|
6003 |
"os": iinfo.os,
|
6004 |
"nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes), |
6005 |
"nics": nic_data,
|
6006 |
"disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks], |
6007 |
"disk_template": iinfo.disk_template,
|
6008 |
"hypervisor": iinfo.hypervisor,
|
6009 |
} |
6010 |
instance_data[iinfo.name] = pir |
6011 |
|
6012 |
data["instances"] = instance_data
|
6013 |
|
6014 |
self.in_data = data
|
6015 |
|
6016 |
def _AddNewInstance(self): |
6017 |
"""Add new instance data to allocator structure.
|
6018 |
|
6019 |
This in combination with _AllocatorGetClusterData will create the
|
6020 |
correct structure needed as input for the allocator.
|
6021 |
|
6022 |
The checks for the completeness of the opcode must have already been
|
6023 |
done.
|
6024 |
|
6025 |
"""
|
6026 |
data = self.in_data
|
6027 |
if len(self.disks) != 2: |
6028 |
raise errors.OpExecError("Only two-disk configurations supported") |
6029 |
|
6030 |
disk_space = _ComputeDiskSize(self.disk_template, self.disks) |
6031 |
|
6032 |
if self.disk_template in constants.DTS_NET_MIRROR: |
6033 |
self.required_nodes = 2 |
6034 |
else:
|
6035 |
self.required_nodes = 1 |
6036 |
request = { |
6037 |
"type": "allocate", |
6038 |
"name": self.name, |
6039 |
"disk_template": self.disk_template, |
6040 |
"tags": self.tags, |
6041 |
"os": self.os, |
6042 |
"vcpus": self.vcpus, |
6043 |
"memory": self.mem_size, |
6044 |
"disks": self.disks, |
6045 |
"disk_space_total": disk_space,
|
6046 |
"nics": self.nics, |
6047 |
"required_nodes": self.required_nodes, |
6048 |
} |
6049 |
data["request"] = request
|
6050 |
|
6051 |
def _AddRelocateInstance(self): |
6052 |
"""Add relocate instance data to allocator structure.
|
6053 |
|
6054 |
This in combination with _IAllocatorGetClusterData will create the
|
6055 |
correct structure needed as input for the allocator.
|
6056 |
|
6057 |
The checks for the completeness of the opcode must have already been
|
6058 |
done.
|
6059 |
|
6060 |
"""
|
6061 |
instance = self.lu.cfg.GetInstanceInfo(self.name) |
6062 |
if instance is None: |
6063 |
raise errors.ProgrammerError("Unknown instance '%s' passed to" |
6064 |
" IAllocator" % self.name) |
6065 |
|
6066 |
if instance.disk_template not in constants.DTS_NET_MIRROR: |
6067 |
raise errors.OpPrereqError("Can't relocate non-mirrored instances") |
6068 |
|
6069 |
if len(instance.secondary_nodes) != 1: |
6070 |
raise errors.OpPrereqError("Instance has not exactly one secondary node") |
6071 |
|
6072 |
self.required_nodes = 1 |
6073 |
disk_sizes = [{'size': disk.size} for disk in instance.disks] |
6074 |
disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes) |
6075 |
|
6076 |
request = { |
6077 |
"type": "relocate", |
6078 |
"name": self.name, |
6079 |
"disk_space_total": disk_space,
|
6080 |
"required_nodes": self.required_nodes, |
6081 |
"relocate_from": self.relocate_from, |
6082 |
} |
6083 |
self.in_data["request"] = request |
6084 |
|
6085 |
def _BuildInputData(self): |
6086 |
"""Build input data structures.
|
6087 |
|
6088 |
"""
|
6089 |
self._ComputeClusterData()
|
6090 |
|
6091 |
if self.mode == constants.IALLOCATOR_MODE_ALLOC: |
6092 |
self._AddNewInstance()
|
6093 |
else:
|
6094 |
self._AddRelocateInstance()
|
6095 |
|
6096 |
self.in_text = serializer.Dump(self.in_data) |
6097 |
|
6098 |
def Run(self, name, validate=True, call_fn=None): |
6099 |
"""Run an instance allocator and return the results.
|
6100 |
|
6101 |
"""
|
6102 |
if call_fn is None: |
6103 |
call_fn = self.lu.rpc.call_iallocator_runner
|
6104 |
data = self.in_text
|
6105 |
|
6106 |
result = call_fn(self.lu.cfg.GetMasterNode(), name, self.in_text) |
6107 |
result.Raise() |
6108 |
|
6109 |
if not isinstance(result.data, (list, tuple)) or len(result.data) != 4: |
6110 |
raise errors.OpExecError("Invalid result from master iallocator runner") |
6111 |
|
6112 |
rcode, stdout, stderr, fail = result.data |
6113 |
|
6114 |
if rcode == constants.IARUN_NOTFOUND:
|
6115 |
raise errors.OpExecError("Can't find allocator '%s'" % name) |
6116 |
elif rcode == constants.IARUN_FAILURE:
|
6117 |
raise errors.OpExecError("Instance allocator call failed: %s," |
6118 |
" output: %s" % (fail, stdout+stderr))
|
6119 |
self.out_text = stdout
|
6120 |
if validate:
|
6121 |
self._ValidateResult()
|
6122 |
|
6123 |
def _ValidateResult(self): |
6124 |
"""Process the allocator results.
|
6125 |
|
6126 |
This will process and if successful save the result in
|
6127 |
self.out_data and the other parameters.
|
6128 |
|
6129 |
"""
|
6130 |
try:
|
6131 |
rdict = serializer.Load(self.out_text)
|
6132 |
except Exception, err: |
6133 |
raise errors.OpExecError("Can't parse iallocator results: %s" % str(err)) |
6134 |
|
6135 |
if not isinstance(rdict, dict): |
6136 |
raise errors.OpExecError("Can't parse iallocator results: not a dict") |
6137 |
|
6138 |
for key in "success", "info", "nodes": |
6139 |
if key not in rdict: |
6140 |
raise errors.OpExecError("Can't parse iallocator results:" |
6141 |
" missing key '%s'" % key)
|
6142 |
setattr(self, key, rdict[key]) |
6143 |
|
6144 |
if not isinstance(rdict["nodes"], list): |
6145 |
raise errors.OpExecError("Can't parse iallocator results: 'nodes' key" |
6146 |
" is not a list")
|
6147 |
self.out_data = rdict
|
6148 |
|
6149 |
|
6150 |
class LUTestAllocator(NoHooksLU): |
6151 |
"""Run allocator tests.
|
6152 |
|
6153 |
This LU runs the allocator tests
|
6154 |
|
6155 |
"""
|
6156 |
_OP_REQP = ["direction", "mode", "name"] |
6157 |
|
6158 |
def CheckPrereq(self): |
6159 |
"""Check prerequisites.
|
6160 |
|
6161 |
This checks the opcode parameters depending on the director and mode test.
|
6162 |
|
6163 |
"""
|
6164 |
if self.op.mode == constants.IALLOCATOR_MODE_ALLOC: |
6165 |
for attr in ["name", "mem_size", "disks", "disk_template", |
6166 |
"os", "tags", "nics", "vcpus"]: |
6167 |
if not hasattr(self.op, attr): |
6168 |
raise errors.OpPrereqError("Missing attribute '%s' on opcode input" % |
6169 |
attr) |
6170 |
iname = self.cfg.ExpandInstanceName(self.op.name) |
6171 |
if iname is not None: |
6172 |
raise errors.OpPrereqError("Instance '%s' already in the cluster" % |
6173 |
iname) |
6174 |
if not isinstance(self.op.nics, list): |
6175 |
raise errors.OpPrereqError("Invalid parameter 'nics'") |
6176 |
for row in self.op.nics: |
6177 |
if (not isinstance(row, dict) or |
6178 |
"mac" not in row or |
6179 |
"ip" not in row or |
6180 |
"bridge" not in row): |
6181 |
raise errors.OpPrereqError("Invalid contents of the" |
6182 |
" 'nics' parameter")
|
6183 |
if not isinstance(self.op.disks, list): |
6184 |
raise errors.OpPrereqError("Invalid parameter 'disks'") |
6185 |
if len(self.op.disks) != 2: |
6186 |
raise errors.OpPrereqError("Only two-disk configurations supported") |
6187 |
for row in self.op.disks: |
6188 |
if (not isinstance(row, dict) or |
6189 |
"size" not in row or |
6190 |
not isinstance(row["size"], int) or |
6191 |
"mode" not in row or |
6192 |
row["mode"] not in ['r', 'w']): |
6193 |
raise errors.OpPrereqError("Invalid contents of the" |
6194 |
" 'disks' parameter")
|
6195 |
if self.op.hypervisor is None: |
6196 |
self.op.hypervisor = self.cfg.GetHypervisorType() |
6197 |
elif self.op.mode == constants.IALLOCATOR_MODE_RELOC: |
6198 |
if not hasattr(self.op, "name"): |
6199 |
raise errors.OpPrereqError("Missing attribute 'name' on opcode input") |
6200 |
fname = self.cfg.ExpandInstanceName(self.op.name) |
6201 |
if fname is None: |
6202 |
raise errors.OpPrereqError("Instance '%s' not found for relocation" % |
6203 |
self.op.name)
|
6204 |
self.op.name = fname
|
6205 |
self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes |
6206 |
else:
|
6207 |
raise errors.OpPrereqError("Invalid test allocator mode '%s'" % |
6208 |
self.op.mode)
|
6209 |
|
6210 |
if self.op.direction == constants.IALLOCATOR_DIR_OUT: |
6211 |
if not hasattr(self.op, "allocator") or self.op.allocator is None: |
6212 |
raise errors.OpPrereqError("Missing allocator name") |
6213 |
elif self.op.direction != constants.IALLOCATOR_DIR_IN: |
6214 |
raise errors.OpPrereqError("Wrong allocator test '%s'" % |
6215 |
self.op.direction)
|
6216 |
|
6217 |
def Exec(self, feedback_fn): |
6218 |
"""Run the allocator test.
|
6219 |
|
6220 |
"""
|
6221 |
if self.op.mode == constants.IALLOCATOR_MODE_ALLOC: |
6222 |
ial = IAllocator(self,
|
6223 |
mode=self.op.mode,
|
6224 |
name=self.op.name,
|
6225 |
mem_size=self.op.mem_size,
|
6226 |
disks=self.op.disks,
|
6227 |
disk_template=self.op.disk_template,
|
6228 |
os=self.op.os,
|
6229 |
tags=self.op.tags,
|
6230 |
nics=self.op.nics,
|
6231 |
vcpus=self.op.vcpus,
|
6232 |
hypervisor=self.op.hypervisor,
|
6233 |
) |
6234 |
else:
|
6235 |
ial = IAllocator(self,
|
6236 |
mode=self.op.mode,
|
6237 |
name=self.op.name,
|
6238 |
relocate_from=list(self.relocate_from), |
6239 |
) |
6240 |
|
6241 |
if self.op.direction == constants.IALLOCATOR_DIR_IN: |
6242 |
result = ial.in_text |
6243 |
else:
|
6244 |
ial.Run(self.op.allocator, validate=False) |
6245 |
result = ial.out_text |
6246 |
return result
|