LUClusterVerifyConfig: Share BGL, acquire all locks in shared mode
[ganeti-local] / lib / cmdlib.py
1 #
2 #
3
4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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=W0201,C0302
25
26 # W0201 since most LU attributes are defined in CheckPrereq or similar
27 # functions
28
29 # C0302: since we have waaaay to many lines in this module
30
31 import os
32 import os.path
33 import time
34 import re
35 import platform
36 import logging
37 import copy
38 import OpenSSL
39 import socket
40 import tempfile
41 import shutil
42 import itertools
43 import operator
44
45 from ganeti import ssh
46 from ganeti import utils
47 from ganeti import errors
48 from ganeti import hypervisor
49 from ganeti import locking
50 from ganeti import constants
51 from ganeti import objects
52 from ganeti import serializer
53 from ganeti import ssconf
54 from ganeti import uidpool
55 from ganeti import compat
56 from ganeti import masterd
57 from ganeti import netutils
58 from ganeti import query
59 from ganeti import qlang
60 from ganeti import opcodes
61 from ganeti import ht
62
63 import ganeti.masterd.instance # pylint: disable=W0611
64
65
66 class ResultWithJobs:
67   """Data container for LU results with jobs.
68
69   Instances of this class returned from L{LogicalUnit.Exec} will be recognized
70   by L{mcpu.Processor._ProcessResult}. The latter will then submit the jobs
71   contained in the C{jobs} attribute and include the job IDs in the opcode
72   result.
73
74   """
75   def __init__(self, jobs, **kwargs):
76     """Initializes this class.
77
78     Additional return values can be specified as keyword arguments.
79
80     @type jobs: list of lists of L{opcode.OpCode}
81     @param jobs: A list of lists of opcode objects
82
83     """
84     self.jobs = jobs
85     self.other = kwargs
86
87
88 class LogicalUnit(object):
89   """Logical Unit base class.
90
91   Subclasses must follow these rules:
92     - implement ExpandNames
93     - implement CheckPrereq (except when tasklets are used)
94     - implement Exec (except when tasklets are used)
95     - implement BuildHooksEnv
96     - implement BuildHooksNodes
97     - redefine HPATH and HTYPE
98     - optionally redefine their run requirements:
99         REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
100
101   Note that all commands require root permissions.
102
103   @ivar dry_run_result: the value (if any) that will be returned to the caller
104       in dry-run mode (signalled by opcode dry_run parameter)
105
106   """
107   HPATH = None
108   HTYPE = None
109   REQ_BGL = True
110
111   def __init__(self, processor, op, context, rpc):
112     """Constructor for LogicalUnit.
113
114     This needs to be overridden in derived classes in order to check op
115     validity.
116
117     """
118     self.proc = processor
119     self.op = op
120     self.cfg = context.cfg
121     self.glm = context.glm
122     # readability alias
123     self.owned_locks = context.glm.list_owned
124     self.context = context
125     self.rpc = rpc
126     # Dicts used to declare locking needs to mcpu
127     self.needed_locks = None
128     self.share_locks = dict.fromkeys(locking.LEVELS, 0)
129     self.add_locks = {}
130     self.remove_locks = {}
131     # Used to force good behavior when calling helper functions
132     self.recalculate_locks = {}
133     # logging
134     self.Log = processor.Log # pylint: disable=C0103
135     self.LogWarning = processor.LogWarning # pylint: disable=C0103
136     self.LogInfo = processor.LogInfo # pylint: disable=C0103
137     self.LogStep = processor.LogStep # pylint: disable=C0103
138     # support for dry-run
139     self.dry_run_result = None
140     # support for generic debug attribute
141     if (not hasattr(self.op, "debug_level") or
142         not isinstance(self.op.debug_level, int)):
143       self.op.debug_level = 0
144
145     # Tasklets
146     self.tasklets = None
147
148     # Validate opcode parameters and set defaults
149     self.op.Validate(True)
150
151     self.CheckArguments()
152
153   def CheckArguments(self):
154     """Check syntactic validity for the opcode arguments.
155
156     This method is for doing a simple syntactic check and ensure
157     validity of opcode parameters, without any cluster-related
158     checks. While the same can be accomplished in ExpandNames and/or
159     CheckPrereq, doing these separate is better because:
160
161       - ExpandNames is left as as purely a lock-related function
162       - CheckPrereq is run after we have acquired locks (and possible
163         waited for them)
164
165     The function is allowed to change the self.op attribute so that
166     later methods can no longer worry about missing parameters.
167
168     """
169     pass
170
171   def ExpandNames(self):
172     """Expand names for this LU.
173
174     This method is called before starting to execute the opcode, and it should
175     update all the parameters of the opcode to their canonical form (e.g. a
176     short node name must be fully expanded after this method has successfully
177     completed). This way locking, hooks, logging, etc. can work correctly.
178
179     LUs which implement this method must also populate the self.needed_locks
180     member, as a dict with lock levels as keys, and a list of needed lock names
181     as values. Rules:
182
183       - use an empty dict if you don't need any lock
184       - if you don't need any lock at a particular level omit that level
185       - don't put anything for the BGL level
186       - if you want all locks at a level use locking.ALL_SET as a value
187
188     If you need to share locks (rather than acquire them exclusively) at one
189     level you can modify self.share_locks, setting a true value (usually 1) for
190     that level. By default locks are not shared.
191
192     This function can also define a list of tasklets, which then will be
193     executed in order instead of the usual LU-level CheckPrereq and Exec
194     functions, if those are not defined by the LU.
195
196     Examples::
197
198       # Acquire all nodes and one instance
199       self.needed_locks = {
200         locking.LEVEL_NODE: locking.ALL_SET,
201         locking.LEVEL_INSTANCE: ['instance1.example.com'],
202       }
203       # Acquire just two nodes
204       self.needed_locks = {
205         locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
206       }
207       # Acquire no locks
208       self.needed_locks = {} # No, you can't leave it to the default value None
209
210     """
211     # The implementation of this method is mandatory only if the new LU is
212     # concurrent, so that old LUs don't need to be changed all at the same
213     # time.
214     if self.REQ_BGL:
215       self.needed_locks = {} # Exclusive LUs don't need locks.
216     else:
217       raise NotImplementedError
218
219   def DeclareLocks(self, level):
220     """Declare LU locking needs for a level
221
222     While most LUs can just declare their locking needs at ExpandNames time,
223     sometimes there's the need to calculate some locks after having acquired
224     the ones before. This function is called just before acquiring locks at a
225     particular level, but after acquiring the ones at lower levels, and permits
226     such calculations. It can be used to modify self.needed_locks, and by
227     default it does nothing.
228
229     This function is only called if you have something already set in
230     self.needed_locks for the level.
231
232     @param level: Locking level which is going to be locked
233     @type level: member of ganeti.locking.LEVELS
234
235     """
236
237   def CheckPrereq(self):
238     """Check prerequisites for this LU.
239
240     This method should check that the prerequisites for the execution
241     of this LU are fulfilled. It can do internode communication, but
242     it should be idempotent - no cluster or system changes are
243     allowed.
244
245     The method should raise errors.OpPrereqError in case something is
246     not fulfilled. Its return value is ignored.
247
248     This method should also update all the parameters of the opcode to
249     their canonical form if it hasn't been done by ExpandNames before.
250
251     """
252     if self.tasklets is not None:
253       for (idx, tl) in enumerate(self.tasklets):
254         logging.debug("Checking prerequisites for tasklet %s/%s",
255                       idx + 1, len(self.tasklets))
256         tl.CheckPrereq()
257     else:
258       pass
259
260   def Exec(self, feedback_fn):
261     """Execute the LU.
262
263     This method should implement the actual work. It should raise
264     errors.OpExecError for failures that are somewhat dealt with in
265     code, or expected.
266
267     """
268     if self.tasklets is not None:
269       for (idx, tl) in enumerate(self.tasklets):
270         logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
271         tl.Exec(feedback_fn)
272     else:
273       raise NotImplementedError
274
275   def BuildHooksEnv(self):
276     """Build hooks environment for this LU.
277
278     @rtype: dict
279     @return: Dictionary containing the environment that will be used for
280       running the hooks for this LU. The keys of the dict must not be prefixed
281       with "GANETI_"--that'll be added by the hooks runner. The hooks runner
282       will extend the environment with additional variables. If no environment
283       should be defined, an empty dictionary should be returned (not C{None}).
284     @note: If the C{HPATH} attribute of the LU class is C{None}, this function
285       will not be called.
286
287     """
288     raise NotImplementedError
289
290   def BuildHooksNodes(self):
291     """Build list of nodes to run LU's hooks.
292
293     @rtype: tuple; (list, list)
294     @return: Tuple containing a list of node names on which the hook
295       should run before the execution and a list of node names on which the
296       hook should run after the execution. No nodes should be returned as an
297       empty list (and not None).
298     @note: If the C{HPATH} attribute of the LU class is C{None}, this function
299       will not be called.
300
301     """
302     raise NotImplementedError
303
304   def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
305     """Notify the LU about the results of its hooks.
306
307     This method is called every time a hooks phase is executed, and notifies
308     the Logical Unit about the hooks' result. The LU can then use it to alter
309     its result based on the hooks.  By default the method does nothing and the
310     previous result is passed back unchanged but any LU can define it if it
311     wants to use the local cluster hook-scripts somehow.
312
313     @param phase: one of L{constants.HOOKS_PHASE_POST} or
314         L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
315     @param hook_results: the results of the multi-node hooks rpc call
316     @param feedback_fn: function used send feedback back to the caller
317     @param lu_result: the previous Exec result this LU had, or None
318         in the PRE phase
319     @return: the new Exec result, based on the previous result
320         and hook results
321
322     """
323     # API must be kept, thus we ignore the unused argument and could
324     # be a function warnings
325     # pylint: disable=W0613,R0201
326     return lu_result
327
328   def _ExpandAndLockInstance(self):
329     """Helper function to expand and lock an instance.
330
331     Many LUs that work on an instance take its name in self.op.instance_name
332     and need to expand it and then declare the expanded name for locking. This
333     function does it, and then updates self.op.instance_name to the expanded
334     name. It also initializes needed_locks as a dict, if this hasn't been done
335     before.
336
337     """
338     if self.needed_locks is None:
339       self.needed_locks = {}
340     else:
341       assert locking.LEVEL_INSTANCE not in self.needed_locks, \
342         "_ExpandAndLockInstance called with instance-level locks set"
343     self.op.instance_name = _ExpandInstanceName(self.cfg,
344                                                 self.op.instance_name)
345     self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
346
347   def _LockInstancesNodes(self, primary_only=False):
348     """Helper function to declare instances' nodes for locking.
349
350     This function should be called after locking one or more instances to lock
351     their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
352     with all primary or secondary nodes for instances already locked and
353     present in self.needed_locks[locking.LEVEL_INSTANCE].
354
355     It should be called from DeclareLocks, and for safety only works if
356     self.recalculate_locks[locking.LEVEL_NODE] is set.
357
358     In the future it may grow parameters to just lock some instance's nodes, or
359     to just lock primaries or secondary nodes, if needed.
360
361     If should be called in DeclareLocks in a way similar to::
362
363       if level == locking.LEVEL_NODE:
364         self._LockInstancesNodes()
365
366     @type primary_only: boolean
367     @param primary_only: only lock primary nodes of locked instances
368
369     """
370     assert locking.LEVEL_NODE in self.recalculate_locks, \
371       "_LockInstancesNodes helper function called with no nodes to recalculate"
372
373     # TODO: check if we're really been called with the instance locks held
374
375     # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
376     # future we might want to have different behaviors depending on the value
377     # of self.recalculate_locks[locking.LEVEL_NODE]
378     wanted_nodes = []
379     locked_i = self.owned_locks(locking.LEVEL_INSTANCE)
380     for _, instance in self.cfg.GetMultiInstanceInfo(locked_i):
381       wanted_nodes.append(instance.primary_node)
382       if not primary_only:
383         wanted_nodes.extend(instance.secondary_nodes)
384
385     if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
386       self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
387     elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
388       self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
389
390     del self.recalculate_locks[locking.LEVEL_NODE]
391
392
393 class NoHooksLU(LogicalUnit): # pylint: disable=W0223
394   """Simple LU which runs no hooks.
395
396   This LU is intended as a parent for other LogicalUnits which will
397   run no hooks, in order to reduce duplicate code.
398
399   """
400   HPATH = None
401   HTYPE = None
402
403   def BuildHooksEnv(self):
404     """Empty BuildHooksEnv for NoHooksLu.
405
406     This just raises an error.
407
408     """
409     raise AssertionError("BuildHooksEnv called for NoHooksLUs")
410
411   def BuildHooksNodes(self):
412     """Empty BuildHooksNodes for NoHooksLU.
413
414     """
415     raise AssertionError("BuildHooksNodes called for NoHooksLU")
416
417
418 class Tasklet:
419   """Tasklet base class.
420
421   Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
422   they can mix legacy code with tasklets. Locking needs to be done in the LU,
423   tasklets know nothing about locks.
424
425   Subclasses must follow these rules:
426     - Implement CheckPrereq
427     - Implement Exec
428
429   """
430   def __init__(self, lu):
431     self.lu = lu
432
433     # Shortcuts
434     self.cfg = lu.cfg
435     self.rpc = lu.rpc
436
437   def CheckPrereq(self):
438     """Check prerequisites for this tasklets.
439
440     This method should check whether the prerequisites for the execution of
441     this tasklet are fulfilled. It can do internode communication, but it
442     should be idempotent - no cluster or system changes are allowed.
443
444     The method should raise errors.OpPrereqError in case something is not
445     fulfilled. Its return value is ignored.
446
447     This method should also update all parameters to their canonical form if it
448     hasn't been done before.
449
450     """
451     pass
452
453   def Exec(self, feedback_fn):
454     """Execute the tasklet.
455
456     This method should implement the actual work. It should raise
457     errors.OpExecError for failures that are somewhat dealt with in code, or
458     expected.
459
460     """
461     raise NotImplementedError
462
463
464 class _QueryBase:
465   """Base for query utility classes.
466
467   """
468   #: Attribute holding field definitions
469   FIELDS = None
470
471   def __init__(self, filter_, fields, use_locking):
472     """Initializes this class.
473
474     """
475     self.use_locking = use_locking
476
477     self.query = query.Query(self.FIELDS, fields, filter_=filter_,
478                              namefield="name")
479     self.requested_data = self.query.RequestedData()
480     self.names = self.query.RequestedNames()
481
482     # Sort only if no names were requested
483     self.sort_by_name = not self.names
484
485     self.do_locking = None
486     self.wanted = None
487
488   def _GetNames(self, lu, all_names, lock_level):
489     """Helper function to determine names asked for in the query.
490
491     """
492     if self.do_locking:
493       names = lu.owned_locks(lock_level)
494     else:
495       names = all_names
496
497     if self.wanted == locking.ALL_SET:
498       assert not self.names
499       # caller didn't specify names, so ordering is not important
500       return utils.NiceSort(names)
501
502     # caller specified names and we must keep the same order
503     assert self.names
504     assert not self.do_locking or lu.glm.is_owned(lock_level)
505
506     missing = set(self.wanted).difference(names)
507     if missing:
508       raise errors.OpExecError("Some items were removed before retrieving"
509                                " their data: %s" % missing)
510
511     # Return expanded names
512     return self.wanted
513
514   def ExpandNames(self, lu):
515     """Expand names for this query.
516
517     See L{LogicalUnit.ExpandNames}.
518
519     """
520     raise NotImplementedError()
521
522   def DeclareLocks(self, lu, level):
523     """Declare locks for this query.
524
525     See L{LogicalUnit.DeclareLocks}.
526
527     """
528     raise NotImplementedError()
529
530   def _GetQueryData(self, lu):
531     """Collects all data for this query.
532
533     @return: Query data object
534
535     """
536     raise NotImplementedError()
537
538   def NewStyleQuery(self, lu):
539     """Collect data and execute query.
540
541     """
542     return query.GetQueryResponse(self.query, self._GetQueryData(lu),
543                                   sort_by_name=self.sort_by_name)
544
545   def OldStyleQuery(self, lu):
546     """Collect data and execute query.
547
548     """
549     return self.query.OldStyleQuery(self._GetQueryData(lu),
550                                     sort_by_name=self.sort_by_name)
551
552
553 def _ShareAll():
554   """Returns a dict declaring all lock levels shared.
555
556   """
557   return dict.fromkeys(locking.LEVELS, 1)
558
559
560 def _CheckInstanceNodeGroups(cfg, instance_name, owned_groups):
561   """Checks if the owned node groups are still correct for an instance.
562
563   @type cfg: L{config.ConfigWriter}
564   @param cfg: The cluster configuration
565   @type instance_name: string
566   @param instance_name: Instance name
567   @type owned_groups: set or frozenset
568   @param owned_groups: List of currently owned node groups
569
570   """
571   inst_groups = cfg.GetInstanceNodeGroups(instance_name)
572
573   if not owned_groups.issuperset(inst_groups):
574     raise errors.OpPrereqError("Instance %s's node groups changed since"
575                                " locks were acquired, current groups are"
576                                " are '%s', owning groups '%s'; retry the"
577                                " operation" %
578                                (instance_name,
579                                 utils.CommaJoin(inst_groups),
580                                 utils.CommaJoin(owned_groups)),
581                                errors.ECODE_STATE)
582
583   return inst_groups
584
585
586 def _CheckNodeGroupInstances(cfg, group_uuid, owned_instances):
587   """Checks if the instances in a node group are still correct.
588
589   @type cfg: L{config.ConfigWriter}
590   @param cfg: The cluster configuration
591   @type group_uuid: string
592   @param group_uuid: Node group UUID
593   @type owned_instances: set or frozenset
594   @param owned_instances: List of currently owned instances
595
596   """
597   wanted_instances = cfg.GetNodeGroupInstances(group_uuid)
598   if owned_instances != wanted_instances:
599     raise errors.OpPrereqError("Instances in node group '%s' changed since"
600                                " locks were acquired, wanted '%s', have '%s';"
601                                " retry the operation" %
602                                (group_uuid,
603                                 utils.CommaJoin(wanted_instances),
604                                 utils.CommaJoin(owned_instances)),
605                                errors.ECODE_STATE)
606
607   return wanted_instances
608
609
610 def _SupportsOob(cfg, node):
611   """Tells if node supports OOB.
612
613   @type cfg: L{config.ConfigWriter}
614   @param cfg: The cluster configuration
615   @type node: L{objects.Node}
616   @param node: The node
617   @return: The OOB script if supported or an empty string otherwise
618
619   """
620   return cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM]
621
622
623 def _GetWantedNodes(lu, nodes):
624   """Returns list of checked and expanded node names.
625
626   @type lu: L{LogicalUnit}
627   @param lu: the logical unit on whose behalf we execute
628   @type nodes: list
629   @param nodes: list of node names or None for all nodes
630   @rtype: list
631   @return: the list of nodes, sorted
632   @raise errors.ProgrammerError: if the nodes parameter is wrong type
633
634   """
635   if nodes:
636     return [_ExpandNodeName(lu.cfg, name) for name in nodes]
637
638   return utils.NiceSort(lu.cfg.GetNodeList())
639
640
641 def _GetWantedInstances(lu, instances):
642   """Returns list of checked and expanded instance names.
643
644   @type lu: L{LogicalUnit}
645   @param lu: the logical unit on whose behalf we execute
646   @type instances: list
647   @param instances: list of instance names or None for all instances
648   @rtype: list
649   @return: the list of instances, sorted
650   @raise errors.OpPrereqError: if the instances parameter is wrong type
651   @raise errors.OpPrereqError: if any of the passed instances is not found
652
653   """
654   if instances:
655     wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
656   else:
657     wanted = utils.NiceSort(lu.cfg.GetInstanceList())
658   return wanted
659
660
661 def _GetUpdatedParams(old_params, update_dict,
662                       use_default=True, use_none=False):
663   """Return the new version of a parameter dictionary.
664
665   @type old_params: dict
666   @param old_params: old parameters
667   @type update_dict: dict
668   @param update_dict: dict containing new parameter values, or
669       constants.VALUE_DEFAULT to reset the parameter to its default
670       value
671   @param use_default: boolean
672   @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
673       values as 'to be deleted' values
674   @param use_none: boolean
675   @type use_none: whether to recognise C{None} values as 'to be
676       deleted' values
677   @rtype: dict
678   @return: the new parameter dictionary
679
680   """
681   params_copy = copy.deepcopy(old_params)
682   for key, val in update_dict.iteritems():
683     if ((use_default and val == constants.VALUE_DEFAULT) or
684         (use_none and val is None)):
685       try:
686         del params_copy[key]
687       except KeyError:
688         pass
689     else:
690       params_copy[key] = val
691   return params_copy
692
693
694 def _ReleaseLocks(lu, level, names=None, keep=None):
695   """Releases locks owned by an LU.
696
697   @type lu: L{LogicalUnit}
698   @param level: Lock level
699   @type names: list or None
700   @param names: Names of locks to release
701   @type keep: list or None
702   @param keep: Names of locks to retain
703
704   """
705   assert not (keep is not None and names is not None), \
706          "Only one of the 'names' and the 'keep' parameters can be given"
707
708   if names is not None:
709     should_release = names.__contains__
710   elif keep:
711     should_release = lambda name: name not in keep
712   else:
713     should_release = None
714
715   if should_release:
716     retain = []
717     release = []
718
719     # Determine which locks to release
720     for name in lu.owned_locks(level):
721       if should_release(name):
722         release.append(name)
723       else:
724         retain.append(name)
725
726     assert len(lu.owned_locks(level)) == (len(retain) + len(release))
727
728     # Release just some locks
729     lu.glm.release(level, names=release)
730
731     assert frozenset(lu.owned_locks(level)) == frozenset(retain)
732   else:
733     # Release everything
734     lu.glm.release(level)
735
736     assert not lu.glm.is_owned(level), "No locks should be owned"
737
738
739 def _MapInstanceDisksToNodes(instances):
740   """Creates a map from (node, volume) to instance name.
741
742   @type instances: list of L{objects.Instance}
743   @rtype: dict; tuple of (node name, volume name) as key, instance name as value
744
745   """
746   return dict(((node, vol), inst.name)
747               for inst in instances
748               for (node, vols) in inst.MapLVsByNode().items()
749               for vol in vols)
750
751
752 def _RunPostHook(lu, node_name):
753   """Runs the post-hook for an opcode on a single node.
754
755   """
756   hm = lu.proc.hmclass(lu.rpc.call_hooks_runner, lu)
757   try:
758     hm.RunPhase(constants.HOOKS_PHASE_POST, nodes=[node_name])
759   except:
760     # pylint: disable=W0702
761     lu.LogWarning("Errors occurred running hooks on %s" % node_name)
762
763
764 def _CheckOutputFields(static, dynamic, selected):
765   """Checks whether all selected fields are valid.
766
767   @type static: L{utils.FieldSet}
768   @param static: static fields set
769   @type dynamic: L{utils.FieldSet}
770   @param dynamic: dynamic fields set
771
772   """
773   f = utils.FieldSet()
774   f.Extend(static)
775   f.Extend(dynamic)
776
777   delta = f.NonMatching(selected)
778   if delta:
779     raise errors.OpPrereqError("Unknown output fields selected: %s"
780                                % ",".join(delta), errors.ECODE_INVAL)
781
782
783 def _CheckGlobalHvParams(params):
784   """Validates that given hypervisor params are not global ones.
785
786   This will ensure that instances don't get customised versions of
787   global params.
788
789   """
790   used_globals = constants.HVC_GLOBALS.intersection(params)
791   if used_globals:
792     msg = ("The following hypervisor parameters are global and cannot"
793            " be customized at instance level, please modify them at"
794            " cluster level: %s" % utils.CommaJoin(used_globals))
795     raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
796
797
798 def _CheckNodeOnline(lu, node, msg=None):
799   """Ensure that a given node is online.
800
801   @param lu: the LU on behalf of which we make the check
802   @param node: the node to check
803   @param msg: if passed, should be a message to replace the default one
804   @raise errors.OpPrereqError: if the node is offline
805
806   """
807   if msg is None:
808     msg = "Can't use offline node"
809   if lu.cfg.GetNodeInfo(node).offline:
810     raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
811
812
813 def _CheckNodeNotDrained(lu, node):
814   """Ensure that a given node is not drained.
815
816   @param lu: the LU on behalf of which we make the check
817   @param node: the node to check
818   @raise errors.OpPrereqError: if the node is drained
819
820   """
821   if lu.cfg.GetNodeInfo(node).drained:
822     raise errors.OpPrereqError("Can't use drained node %s" % node,
823                                errors.ECODE_STATE)
824
825
826 def _CheckNodeVmCapable(lu, node):
827   """Ensure that a given node is vm capable.
828
829   @param lu: the LU on behalf of which we make the check
830   @param node: the node to check
831   @raise errors.OpPrereqError: if the node is not vm capable
832
833   """
834   if not lu.cfg.GetNodeInfo(node).vm_capable:
835     raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
836                                errors.ECODE_STATE)
837
838
839 def _CheckNodeHasOS(lu, node, os_name, force_variant):
840   """Ensure that a node supports a given OS.
841
842   @param lu: the LU on behalf of which we make the check
843   @param node: the node to check
844   @param os_name: the OS to query about
845   @param force_variant: whether to ignore variant errors
846   @raise errors.OpPrereqError: if the node is not supporting the OS
847
848   """
849   result = lu.rpc.call_os_get(node, os_name)
850   result.Raise("OS '%s' not in supported OS list for node %s" %
851                (os_name, node),
852                prereq=True, ecode=errors.ECODE_INVAL)
853   if not force_variant:
854     _CheckOSVariant(result.payload, os_name)
855
856
857 def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
858   """Ensure that a node has the given secondary ip.
859
860   @type lu: L{LogicalUnit}
861   @param lu: the LU on behalf of which we make the check
862   @type node: string
863   @param node: the node to check
864   @type secondary_ip: string
865   @param secondary_ip: the ip to check
866   @type prereq: boolean
867   @param prereq: whether to throw a prerequisite or an execute error
868   @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
869   @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
870
871   """
872   result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
873   result.Raise("Failure checking secondary ip on node %s" % node,
874                prereq=prereq, ecode=errors.ECODE_ENVIRON)
875   if not result.payload:
876     msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
877            " please fix and re-run this command" % secondary_ip)
878     if prereq:
879       raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
880     else:
881       raise errors.OpExecError(msg)
882
883
884 def _GetClusterDomainSecret():
885   """Reads the cluster domain secret.
886
887   """
888   return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
889                                strict=True)
890
891
892 def _CheckInstanceDown(lu, instance, reason):
893   """Ensure that an instance is not running."""
894   if instance.admin_up:
895     raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
896                                (instance.name, reason), errors.ECODE_STATE)
897
898   pnode = instance.primary_node
899   ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
900   ins_l.Raise("Can't contact node %s for instance information" % pnode,
901               prereq=True, ecode=errors.ECODE_ENVIRON)
902
903   if instance.name in ins_l.payload:
904     raise errors.OpPrereqError("Instance %s is running, %s" %
905                                (instance.name, reason), errors.ECODE_STATE)
906
907
908 def _ExpandItemName(fn, name, kind):
909   """Expand an item name.
910
911   @param fn: the function to use for expansion
912   @param name: requested item name
913   @param kind: text description ('Node' or 'Instance')
914   @return: the resolved (full) name
915   @raise errors.OpPrereqError: if the item is not found
916
917   """
918   full_name = fn(name)
919   if full_name is None:
920     raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
921                                errors.ECODE_NOENT)
922   return full_name
923
924
925 def _ExpandNodeName(cfg, name):
926   """Wrapper over L{_ExpandItemName} for nodes."""
927   return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
928
929
930 def _ExpandInstanceName(cfg, name):
931   """Wrapper over L{_ExpandItemName} for instance."""
932   return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
933
934
935 def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
936                           memory, vcpus, nics, disk_template, disks,
937                           bep, hvp, hypervisor_name, tags):
938   """Builds instance related env variables for hooks
939
940   This builds the hook environment from individual variables.
941
942   @type name: string
943   @param name: the name of the instance
944   @type primary_node: string
945   @param primary_node: the name of the instance's primary node
946   @type secondary_nodes: list
947   @param secondary_nodes: list of secondary nodes as strings
948   @type os_type: string
949   @param os_type: the name of the instance's OS
950   @type status: boolean
951   @param status: the should_run status of the instance
952   @type memory: string
953   @param memory: the memory size of the instance
954   @type vcpus: string
955   @param vcpus: the count of VCPUs the instance has
956   @type nics: list
957   @param nics: list of tuples (ip, mac, mode, link) representing
958       the NICs the instance has
959   @type disk_template: string
960   @param disk_template: the disk template of the instance
961   @type disks: list
962   @param disks: the list of (size, mode) pairs
963   @type bep: dict
964   @param bep: the backend parameters for the instance
965   @type hvp: dict
966   @param hvp: the hypervisor parameters for the instance
967   @type hypervisor_name: string
968   @param hypervisor_name: the hypervisor for the instance
969   @type tags: list
970   @param tags: list of instance tags as strings
971   @rtype: dict
972   @return: the hook environment for this instance
973
974   """
975   if status:
976     str_status = "up"
977   else:
978     str_status = "down"
979   env = {
980     "OP_TARGET": name,
981     "INSTANCE_NAME": name,
982     "INSTANCE_PRIMARY": primary_node,
983     "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
984     "INSTANCE_OS_TYPE": os_type,
985     "INSTANCE_STATUS": str_status,
986     "INSTANCE_MEMORY": memory,
987     "INSTANCE_VCPUS": vcpus,
988     "INSTANCE_DISK_TEMPLATE": disk_template,
989     "INSTANCE_HYPERVISOR": hypervisor_name,
990   }
991
992   if nics:
993     nic_count = len(nics)
994     for idx, (ip, mac, mode, link) in enumerate(nics):
995       if ip is None:
996         ip = ""
997       env["INSTANCE_NIC%d_IP" % idx] = ip
998       env["INSTANCE_NIC%d_MAC" % idx] = mac
999       env["INSTANCE_NIC%d_MODE" % idx] = mode
1000       env["INSTANCE_NIC%d_LINK" % idx] = link
1001       if mode == constants.NIC_MODE_BRIDGED:
1002         env["INSTANCE_NIC%d_BRIDGE" % idx] = link
1003   else:
1004     nic_count = 0
1005
1006   env["INSTANCE_NIC_COUNT"] = nic_count
1007
1008   if disks:
1009     disk_count = len(disks)
1010     for idx, (size, mode) in enumerate(disks):
1011       env["INSTANCE_DISK%d_SIZE" % idx] = size
1012       env["INSTANCE_DISK%d_MODE" % idx] = mode
1013   else:
1014     disk_count = 0
1015
1016   env["INSTANCE_DISK_COUNT"] = disk_count
1017
1018   if not tags:
1019     tags = []
1020
1021   env["INSTANCE_TAGS"] = " ".join(tags)
1022
1023   for source, kind in [(bep, "BE"), (hvp, "HV")]:
1024     for key, value in source.items():
1025       env["INSTANCE_%s_%s" % (kind, key)] = value
1026
1027   return env
1028
1029
1030 def _NICListToTuple(lu, nics):
1031   """Build a list of nic information tuples.
1032
1033   This list is suitable to be passed to _BuildInstanceHookEnv or as a return
1034   value in LUInstanceQueryData.
1035
1036   @type lu:  L{LogicalUnit}
1037   @param lu: the logical unit on whose behalf we execute
1038   @type nics: list of L{objects.NIC}
1039   @param nics: list of nics to convert to hooks tuples
1040
1041   """
1042   hooks_nics = []
1043   cluster = lu.cfg.GetClusterInfo()
1044   for nic in nics:
1045     ip = nic.ip
1046     mac = nic.mac
1047     filled_params = cluster.SimpleFillNIC(nic.nicparams)
1048     mode = filled_params[constants.NIC_MODE]
1049     link = filled_params[constants.NIC_LINK]
1050     hooks_nics.append((ip, mac, mode, link))
1051   return hooks_nics
1052
1053
1054 def _BuildInstanceHookEnvByObject(lu, instance, override=None):
1055   """Builds instance related env variables for hooks from an object.
1056
1057   @type lu: L{LogicalUnit}
1058   @param lu: the logical unit on whose behalf we execute
1059   @type instance: L{objects.Instance}
1060   @param instance: the instance for which we should build the
1061       environment
1062   @type override: dict
1063   @param override: dictionary with key/values that will override
1064       our values
1065   @rtype: dict
1066   @return: the hook environment dictionary
1067
1068   """
1069   cluster = lu.cfg.GetClusterInfo()
1070   bep = cluster.FillBE(instance)
1071   hvp = cluster.FillHV(instance)
1072   args = {
1073     "name": instance.name,
1074     "primary_node": instance.primary_node,
1075     "secondary_nodes": instance.secondary_nodes,
1076     "os_type": instance.os,
1077     "status": instance.admin_up,
1078     "memory": bep[constants.BE_MEMORY],
1079     "vcpus": bep[constants.BE_VCPUS],
1080     "nics": _NICListToTuple(lu, instance.nics),
1081     "disk_template": instance.disk_template,
1082     "disks": [(disk.size, disk.mode) for disk in instance.disks],
1083     "bep": bep,
1084     "hvp": hvp,
1085     "hypervisor_name": instance.hypervisor,
1086     "tags": instance.tags,
1087   }
1088   if override:
1089     args.update(override)
1090   return _BuildInstanceHookEnv(**args) # pylint: disable=W0142
1091
1092
1093 def _AdjustCandidatePool(lu, exceptions):
1094   """Adjust the candidate pool after node operations.
1095
1096   """
1097   mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1098   if mod_list:
1099     lu.LogInfo("Promoted nodes to master candidate role: %s",
1100                utils.CommaJoin(node.name for node in mod_list))
1101     for name in mod_list:
1102       lu.context.ReaddNode(name)
1103   mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1104   if mc_now > mc_max:
1105     lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1106                (mc_now, mc_max))
1107
1108
1109 def _DecideSelfPromotion(lu, exceptions=None):
1110   """Decide whether I should promote myself as a master candidate.
1111
1112   """
1113   cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1114   mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1115   # the new node will increase mc_max with one, so:
1116   mc_should = min(mc_should + 1, cp_size)
1117   return mc_now < mc_should
1118
1119
1120 def _CheckNicsBridgesExist(lu, target_nics, target_node):
1121   """Check that the brigdes needed by a list of nics exist.
1122
1123   """
1124   cluster = lu.cfg.GetClusterInfo()
1125   paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1126   brlist = [params[constants.NIC_LINK] for params in paramslist
1127             if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1128   if brlist:
1129     result = lu.rpc.call_bridges_exist(target_node, brlist)
1130     result.Raise("Error checking bridges on destination node '%s'" %
1131                  target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1132
1133
1134 def _CheckInstanceBridgesExist(lu, instance, node=None):
1135   """Check that the brigdes needed by an instance exist.
1136
1137   """
1138   if node is None:
1139     node = instance.primary_node
1140   _CheckNicsBridgesExist(lu, instance.nics, node)
1141
1142
1143 def _CheckOSVariant(os_obj, name):
1144   """Check whether an OS name conforms to the os variants specification.
1145
1146   @type os_obj: L{objects.OS}
1147   @param os_obj: OS object to check
1148   @type name: string
1149   @param name: OS name passed by the user, to check for validity
1150
1151   """
1152   variant = objects.OS.GetVariant(name)
1153   if not os_obj.supported_variants:
1154     if variant:
1155       raise errors.OpPrereqError("OS '%s' doesn't support variants ('%s'"
1156                                  " passed)" % (os_obj.name, variant),
1157                                  errors.ECODE_INVAL)
1158     return
1159   if not variant:
1160     raise errors.OpPrereqError("OS name must include a variant",
1161                                errors.ECODE_INVAL)
1162
1163   if variant not in os_obj.supported_variants:
1164     raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1165
1166
1167 def _GetNodeInstancesInner(cfg, fn):
1168   return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1169
1170
1171 def _GetNodeInstances(cfg, node_name):
1172   """Returns a list of all primary and secondary instances on a node.
1173
1174   """
1175
1176   return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1177
1178
1179 def _GetNodePrimaryInstances(cfg, node_name):
1180   """Returns primary instances on a node.
1181
1182   """
1183   return _GetNodeInstancesInner(cfg,
1184                                 lambda inst: node_name == inst.primary_node)
1185
1186
1187 def _GetNodeSecondaryInstances(cfg, node_name):
1188   """Returns secondary instances on a node.
1189
1190   """
1191   return _GetNodeInstancesInner(cfg,
1192                                 lambda inst: node_name in inst.secondary_nodes)
1193
1194
1195 def _GetStorageTypeArgs(cfg, storage_type):
1196   """Returns the arguments for a storage type.
1197
1198   """
1199   # Special case for file storage
1200   if storage_type == constants.ST_FILE:
1201     # storage.FileStorage wants a list of storage directories
1202     return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1203
1204   return []
1205
1206
1207 def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1208   faulty = []
1209
1210   for dev in instance.disks:
1211     cfg.SetDiskID(dev, node_name)
1212
1213   result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1214   result.Raise("Failed to get disk status from node %s" % node_name,
1215                prereq=prereq, ecode=errors.ECODE_ENVIRON)
1216
1217   for idx, bdev_status in enumerate(result.payload):
1218     if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1219       faulty.append(idx)
1220
1221   return faulty
1222
1223
1224 def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1225   """Check the sanity of iallocator and node arguments and use the
1226   cluster-wide iallocator if appropriate.
1227
1228   Check that at most one of (iallocator, node) is specified. If none is
1229   specified, then the LU's opcode's iallocator slot is filled with the
1230   cluster-wide default iallocator.
1231
1232   @type iallocator_slot: string
1233   @param iallocator_slot: the name of the opcode iallocator slot
1234   @type node_slot: string
1235   @param node_slot: the name of the opcode target node slot
1236
1237   """
1238   node = getattr(lu.op, node_slot, None)
1239   iallocator = getattr(lu.op, iallocator_slot, None)
1240
1241   if node is not None and iallocator is not None:
1242     raise errors.OpPrereqError("Do not specify both, iallocator and node",
1243                                errors.ECODE_INVAL)
1244   elif node is None and iallocator is None:
1245     default_iallocator = lu.cfg.GetDefaultIAllocator()
1246     if default_iallocator:
1247       setattr(lu.op, iallocator_slot, default_iallocator)
1248     else:
1249       raise errors.OpPrereqError("No iallocator or node given and no"
1250                                  " cluster-wide default iallocator found;"
1251                                  " please specify either an iallocator or a"
1252                                  " node, or set a cluster-wide default"
1253                                  " iallocator")
1254
1255
1256 def _GetDefaultIAllocator(cfg, iallocator):
1257   """Decides on which iallocator to use.
1258
1259   @type cfg: L{config.ConfigWriter}
1260   @param cfg: Cluster configuration object
1261   @type iallocator: string or None
1262   @param iallocator: Iallocator specified in opcode
1263   @rtype: string
1264   @return: Iallocator name
1265
1266   """
1267   if not iallocator:
1268     # Use default iallocator
1269     iallocator = cfg.GetDefaultIAllocator()
1270
1271   if not iallocator:
1272     raise errors.OpPrereqError("No iallocator was specified, neither in the"
1273                                " opcode nor as a cluster-wide default",
1274                                errors.ECODE_INVAL)
1275
1276   return iallocator
1277
1278
1279 class LUClusterPostInit(LogicalUnit):
1280   """Logical unit for running hooks after cluster initialization.
1281
1282   """
1283   HPATH = "cluster-init"
1284   HTYPE = constants.HTYPE_CLUSTER
1285
1286   def BuildHooksEnv(self):
1287     """Build hooks env.
1288
1289     """
1290     return {
1291       "OP_TARGET": self.cfg.GetClusterName(),
1292       }
1293
1294   def BuildHooksNodes(self):
1295     """Build hooks nodes.
1296
1297     """
1298     return ([], [self.cfg.GetMasterNode()])
1299
1300   def Exec(self, feedback_fn):
1301     """Nothing to do.
1302
1303     """
1304     return True
1305
1306
1307 class LUClusterDestroy(LogicalUnit):
1308   """Logical unit for destroying the cluster.
1309
1310   """
1311   HPATH = "cluster-destroy"
1312   HTYPE = constants.HTYPE_CLUSTER
1313
1314   def BuildHooksEnv(self):
1315     """Build hooks env.
1316
1317     """
1318     return {
1319       "OP_TARGET": self.cfg.GetClusterName(),
1320       }
1321
1322   def BuildHooksNodes(self):
1323     """Build hooks nodes.
1324
1325     """
1326     return ([], [])
1327
1328   def CheckPrereq(self):
1329     """Check prerequisites.
1330
1331     This checks whether the cluster is empty.
1332
1333     Any errors are signaled by raising errors.OpPrereqError.
1334
1335     """
1336     master = self.cfg.GetMasterNode()
1337
1338     nodelist = self.cfg.GetNodeList()
1339     if len(nodelist) != 1 or nodelist[0] != master:
1340       raise errors.OpPrereqError("There are still %d node(s) in"
1341                                  " this cluster." % (len(nodelist) - 1),
1342                                  errors.ECODE_INVAL)
1343     instancelist = self.cfg.GetInstanceList()
1344     if instancelist:
1345       raise errors.OpPrereqError("There are still %d instance(s) in"
1346                                  " this cluster." % len(instancelist),
1347                                  errors.ECODE_INVAL)
1348
1349   def Exec(self, feedback_fn):
1350     """Destroys the cluster.
1351
1352     """
1353     master = self.cfg.GetMasterNode()
1354
1355     # Run post hooks on master node before it's removed
1356     _RunPostHook(self, master)
1357
1358     result = self.rpc.call_node_stop_master(master, False)
1359     result.Raise("Could not disable the master role")
1360
1361     return master
1362
1363
1364 def _VerifyCertificate(filename):
1365   """Verifies a certificate for L{LUClusterVerifyConfig}.
1366
1367   @type filename: string
1368   @param filename: Path to PEM file
1369
1370   """
1371   try:
1372     cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1373                                            utils.ReadFile(filename))
1374   except Exception, err: # pylint: disable=W0703
1375     return (LUClusterVerifyConfig.ETYPE_ERROR,
1376             "Failed to load X509 certificate %s: %s" % (filename, err))
1377
1378   (errcode, msg) = \
1379     utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1380                                 constants.SSL_CERT_EXPIRATION_ERROR)
1381
1382   if msg:
1383     fnamemsg = "While verifying %s: %s" % (filename, msg)
1384   else:
1385     fnamemsg = None
1386
1387   if errcode is None:
1388     return (None, fnamemsg)
1389   elif errcode == utils.CERT_WARNING:
1390     return (LUClusterVerifyConfig.ETYPE_WARNING, fnamemsg)
1391   elif errcode == utils.CERT_ERROR:
1392     return (LUClusterVerifyConfig.ETYPE_ERROR, fnamemsg)
1393
1394   raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1395
1396
1397 def _GetAllHypervisorParameters(cluster, instances):
1398   """Compute the set of all hypervisor parameters.
1399
1400   @type cluster: L{objects.Cluster}
1401   @param cluster: the cluster object
1402   @param instances: list of L{objects.Instance}
1403   @param instances: additional instances from which to obtain parameters
1404   @rtype: list of (origin, hypervisor, parameters)
1405   @return: a list with all parameters found, indicating the hypervisor they
1406        apply to, and the origin (can be "cluster", "os X", or "instance Y")
1407
1408   """
1409   hvp_data = []
1410
1411   for hv_name in cluster.enabled_hypervisors:
1412     hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
1413
1414   for os_name, os_hvp in cluster.os_hvp.items():
1415     for hv_name, hv_params in os_hvp.items():
1416       if hv_params:
1417         full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
1418         hvp_data.append(("os %s" % os_name, hv_name, full_params))
1419
1420   # TODO: collapse identical parameter values in a single one
1421   for instance in instances:
1422     if instance.hvparams:
1423       hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
1424                        cluster.FillHV(instance)))
1425
1426   return hvp_data
1427
1428
1429 class _VerifyErrors(object):
1430   """Mix-in for cluster/group verify LUs.
1431
1432   It provides _Error and _ErrorIf, and updates the self.bad boolean. (Expects
1433   self.op and self._feedback_fn to be available.)
1434
1435   """
1436   TCLUSTER = "cluster"
1437   TNODE = "node"
1438   TINSTANCE = "instance"
1439
1440   ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1441   ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1442   ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1443   ECLUSTERDANGLINGNODES = (TNODE, "ECLUSTERDANGLINGNODES")
1444   ECLUSTERDANGLINGINST = (TNODE, "ECLUSTERDANGLINGINST")
1445   EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1446   EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1447   EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1448   EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1449   EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1450   EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1451   EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1452   ENODEDRBD = (TNODE, "ENODEDRBD")
1453   ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1454   ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1455   ENODEHOOKS = (TNODE, "ENODEHOOKS")
1456   ENODEHV = (TNODE, "ENODEHV")
1457   ENODELVM = (TNODE, "ENODELVM")
1458   ENODEN1 = (TNODE, "ENODEN1")
1459   ENODENET = (TNODE, "ENODENET")
1460   ENODEOS = (TNODE, "ENODEOS")
1461   ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1462   ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1463   ENODERPC = (TNODE, "ENODERPC")
1464   ENODESSH = (TNODE, "ENODESSH")
1465   ENODEVERSION = (TNODE, "ENODEVERSION")
1466   ENODESETUP = (TNODE, "ENODESETUP")
1467   ENODETIME = (TNODE, "ENODETIME")
1468   ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1469
1470   ETYPE_FIELD = "code"
1471   ETYPE_ERROR = "ERROR"
1472   ETYPE_WARNING = "WARNING"
1473
1474   def _Error(self, ecode, item, msg, *args, **kwargs):
1475     """Format an error message.
1476
1477     Based on the opcode's error_codes parameter, either format a
1478     parseable error code, or a simpler error string.
1479
1480     This must be called only from Exec and functions called from Exec.
1481
1482     """
1483     ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1484     itype, etxt = ecode
1485     # first complete the msg
1486     if args:
1487       msg = msg % args
1488     # then format the whole message
1489     if self.op.error_codes: # This is a mix-in. pylint: disable=E1101
1490       msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1491     else:
1492       if item:
1493         item = " " + item
1494       else:
1495         item = ""
1496       msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1497     # and finally report it via the feedback_fn
1498     self._feedback_fn("  - %s" % msg) # Mix-in. pylint: disable=E1101
1499
1500   def _ErrorIf(self, cond, *args, **kwargs):
1501     """Log an error message if the passed condition is True.
1502
1503     """
1504     cond = (bool(cond)
1505             or self.op.debug_simulate_errors) # pylint: disable=E1101
1506     if cond:
1507       self._Error(*args, **kwargs)
1508     # do not mark the operation as failed for WARN cases only
1509     if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1510       self.bad = self.bad or cond
1511
1512
1513 class LUClusterVerify(NoHooksLU):
1514   """Submits all jobs necessary to verify the cluster.
1515
1516   """
1517   REQ_BGL = False
1518
1519   def ExpandNames(self):
1520     self.needed_locks = {}
1521
1522   def Exec(self, feedback_fn):
1523     jobs = []
1524
1525     if self.op.group_name:
1526       groups = [self.op.group_name]
1527       depends_fn = lambda: None
1528     else:
1529       groups = self.cfg.GetNodeGroupList()
1530
1531       # Verify global configuration
1532       jobs.append([opcodes.OpClusterVerifyConfig()])
1533
1534       # Always depend on global verification
1535       depends_fn = lambda: [(-len(jobs), [])]
1536
1537     jobs.extend([opcodes.OpClusterVerifyGroup(group_name=group,
1538                                               depends=depends_fn())]
1539                 for group in groups)
1540
1541     # Fix up all parameters
1542     for op in itertools.chain(*jobs): # pylint: disable=W0142
1543       op.debug_simulate_errors = self.op.debug_simulate_errors
1544       op.verbose = self.op.verbose
1545       op.error_codes = self.op.error_codes
1546       try:
1547         op.skip_checks = self.op.skip_checks
1548       except AttributeError:
1549         assert not isinstance(op, opcodes.OpClusterVerifyGroup)
1550
1551     return ResultWithJobs(jobs)
1552
1553
1554 class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1555   """Verifies the cluster config.
1556
1557   """
1558   REQ_BGL = False
1559
1560   def _VerifyHVP(self, hvp_data):
1561     """Verifies locally the syntax of the hypervisor parameters.
1562
1563     """
1564     for item, hv_name, hv_params in hvp_data:
1565       msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
1566              (item, hv_name))
1567       try:
1568         hv_class = hypervisor.GetHypervisor(hv_name)
1569         utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1570         hv_class.CheckParameterSyntax(hv_params)
1571       except errors.GenericError, err:
1572         self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
1573
1574   def ExpandNames(self):
1575     self.needed_locks = dict.fromkeys(locking.LEVELS, locking.ALL_SET)
1576     self.share_locks = _ShareAll()
1577
1578   def CheckPrereq(self):
1579     """Check prerequisites.
1580
1581     """
1582     # Retrieve all information
1583     self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1584     self.all_node_info = self.cfg.GetAllNodesInfo()
1585     self.all_inst_info = self.cfg.GetAllInstancesInfo()
1586
1587   def Exec(self, feedback_fn):
1588     """Verify integrity of cluster, performing various test on nodes.
1589
1590     """
1591     self.bad = False
1592     self._feedback_fn = feedback_fn
1593
1594     feedback_fn("* Verifying cluster config")
1595
1596     for msg in self.cfg.VerifyConfig():
1597       self._ErrorIf(True, self.ECLUSTERCFG, None, msg)
1598
1599     feedback_fn("* Verifying cluster certificate files")
1600
1601     for cert_filename in constants.ALL_CERT_FILES:
1602       (errcode, msg) = _VerifyCertificate(cert_filename)
1603       self._ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1604
1605     feedback_fn("* Verifying hypervisor parameters")
1606
1607     self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1608                                                 self.all_inst_info.values()))
1609
1610     feedback_fn("* Verifying all nodes belong to an existing group")
1611
1612     # We do this verification here because, should this bogus circumstance
1613     # occur, it would never be caught by VerifyGroup, which only acts on
1614     # nodes/instances reachable from existing node groups.
1615
1616     dangling_nodes = set(node.name for node in self.all_node_info.values()
1617                          if node.group not in self.all_group_info)
1618
1619     dangling_instances = {}
1620     no_node_instances = []
1621
1622     for inst in self.all_inst_info.values():
1623       if inst.primary_node in dangling_nodes:
1624         dangling_instances.setdefault(inst.primary_node, []).append(inst.name)
1625       elif inst.primary_node not in self.all_node_info:
1626         no_node_instances.append(inst.name)
1627
1628     pretty_dangling = [
1629         "%s (%s)" %
1630         (node.name,
1631          utils.CommaJoin(dangling_instances.get(node.name,
1632                                                 ["no instances"])))
1633         for node in dangling_nodes]
1634
1635     self._ErrorIf(bool(dangling_nodes), self.ECLUSTERDANGLINGNODES, None,
1636                   "the following nodes (and their instances) belong to a non"
1637                   " existing group: %s", utils.CommaJoin(pretty_dangling))
1638
1639     self._ErrorIf(bool(no_node_instances), self.ECLUSTERDANGLINGINST, None,
1640                   "the following instances have a non-existing primary-node:"
1641                   " %s", utils.CommaJoin(no_node_instances))
1642
1643     return not self.bad
1644
1645
1646 class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1647   """Verifies the status of a node group.
1648
1649   """
1650   HPATH = "cluster-verify"
1651   HTYPE = constants.HTYPE_CLUSTER
1652   REQ_BGL = False
1653
1654   _HOOKS_INDENT_RE = re.compile("^", re.M)
1655
1656   class NodeImage(object):
1657     """A class representing the logical and physical status of a node.
1658
1659     @type name: string
1660     @ivar name: the node name to which this object refers
1661     @ivar volumes: a structure as returned from
1662         L{ganeti.backend.GetVolumeList} (runtime)
1663     @ivar instances: a list of running instances (runtime)
1664     @ivar pinst: list of configured primary instances (config)
1665     @ivar sinst: list of configured secondary instances (config)
1666     @ivar sbp: dictionary of {primary-node: list of instances} for all
1667         instances for which this node is secondary (config)
1668     @ivar mfree: free memory, as reported by hypervisor (runtime)
1669     @ivar dfree: free disk, as reported by the node (runtime)
1670     @ivar offline: the offline status (config)
1671     @type rpc_fail: boolean
1672     @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1673         not whether the individual keys were correct) (runtime)
1674     @type lvm_fail: boolean
1675     @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1676     @type hyp_fail: boolean
1677     @ivar hyp_fail: whether the RPC call didn't return the instance list
1678     @type ghost: boolean
1679     @ivar ghost: whether this is a known node or not (config)
1680     @type os_fail: boolean
1681     @ivar os_fail: whether the RPC call didn't return valid OS data
1682     @type oslist: list
1683     @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1684     @type vm_capable: boolean
1685     @ivar vm_capable: whether the node can host instances
1686
1687     """
1688     def __init__(self, offline=False, name=None, vm_capable=True):
1689       self.name = name
1690       self.volumes = {}
1691       self.instances = []
1692       self.pinst = []
1693       self.sinst = []
1694       self.sbp = {}
1695       self.mfree = 0
1696       self.dfree = 0
1697       self.offline = offline
1698       self.vm_capable = vm_capable
1699       self.rpc_fail = False
1700       self.lvm_fail = False
1701       self.hyp_fail = False
1702       self.ghost = False
1703       self.os_fail = False
1704       self.oslist = {}
1705
1706   def ExpandNames(self):
1707     # This raises errors.OpPrereqError on its own:
1708     self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1709
1710     # Get instances in node group; this is unsafe and needs verification later
1711     inst_names = \
1712       self.cfg.GetNodeGroupInstances(self.group_uuid, primary_only=True)
1713
1714     self.needed_locks = {
1715       locking.LEVEL_INSTANCE: inst_names,
1716       locking.LEVEL_NODEGROUP: [self.group_uuid],
1717       locking.LEVEL_NODE: [],
1718       }
1719
1720     self.share_locks = _ShareAll()
1721
1722   def DeclareLocks(self, level):
1723     if level == locking.LEVEL_NODE:
1724       # Get members of node group; this is unsafe and needs verification later
1725       nodes = set(self.cfg.GetNodeGroup(self.group_uuid).members)
1726
1727       all_inst_info = self.cfg.GetAllInstancesInfo()
1728
1729       # In Exec(), we warn about mirrored instances that have primary and
1730       # secondary living in separate node groups. To fully verify that
1731       # volumes for these instances are healthy, we will need to do an
1732       # extra call to their secondaries. We ensure here those nodes will
1733       # be locked.
1734       for inst in self.owned_locks(locking.LEVEL_INSTANCE):
1735         # Important: access only the instances whose lock is owned
1736         if all_inst_info[inst].disk_template in constants.DTS_INT_MIRROR:
1737           nodes.update(all_inst_info[inst].secondary_nodes)
1738
1739       self.needed_locks[locking.LEVEL_NODE] = nodes
1740
1741   def CheckPrereq(self):
1742     assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
1743     self.group_info = self.cfg.GetNodeGroup(self.group_uuid)
1744
1745     group_nodes = set(self.group_info.members)
1746     group_instances = \
1747       self.cfg.GetNodeGroupInstances(self.group_uuid, primary_only=True)
1748
1749     unlocked_nodes = \
1750         group_nodes.difference(self.owned_locks(locking.LEVEL_NODE))
1751
1752     unlocked_instances = \
1753         group_instances.difference(self.owned_locks(locking.LEVEL_INSTANCE))
1754
1755     if unlocked_nodes:
1756       raise errors.OpPrereqError("Missing lock for nodes: %s" %
1757                                  utils.CommaJoin(unlocked_nodes),
1758                                  errors.ECODE_STATE)
1759
1760     if unlocked_instances:
1761       raise errors.OpPrereqError("Missing lock for instances: %s" %
1762                                  utils.CommaJoin(unlocked_instances),
1763                                  errors.ECODE_STATE)
1764
1765     self.all_node_info = self.cfg.GetAllNodesInfo()
1766     self.all_inst_info = self.cfg.GetAllInstancesInfo()
1767
1768     self.my_node_names = utils.NiceSort(group_nodes)
1769     self.my_inst_names = utils.NiceSort(group_instances)
1770
1771     self.my_node_info = dict((name, self.all_node_info[name])
1772                              for name in self.my_node_names)
1773
1774     self.my_inst_info = dict((name, self.all_inst_info[name])
1775                              for name in self.my_inst_names)
1776
1777     # We detect here the nodes that will need the extra RPC calls for verifying
1778     # split LV volumes; they should be locked.
1779     extra_lv_nodes = set()
1780
1781     for inst in self.my_inst_info.values():
1782       if inst.disk_template in constants.DTS_INT_MIRROR:
1783         for nname in inst.all_nodes:
1784           if self.all_node_info[nname].group != self.group_uuid:
1785             extra_lv_nodes.add(nname)
1786
1787     unlocked_lv_nodes = \
1788         extra_lv_nodes.difference(self.owned_locks(locking.LEVEL_NODE))
1789
1790     if unlocked_lv_nodes:
1791       raise errors.OpPrereqError("Missing node locks for LV check: %s" %
1792                                  utils.CommaJoin(unlocked_lv_nodes),
1793                                  errors.ECODE_STATE)
1794     self.extra_lv_nodes = list(extra_lv_nodes)
1795
1796   def _VerifyNode(self, ninfo, nresult):
1797     """Perform some basic validation on data returned from a node.
1798
1799       - check the result data structure is well formed and has all the
1800         mandatory fields
1801       - check ganeti version
1802
1803     @type ninfo: L{objects.Node}
1804     @param ninfo: the node to check
1805     @param nresult: the results from the node
1806     @rtype: boolean
1807     @return: whether overall this call was successful (and we can expect
1808          reasonable values in the respose)
1809
1810     """
1811     node = ninfo.name
1812     _ErrorIf = self._ErrorIf # pylint: disable=C0103
1813
1814     # main result, nresult should be a non-empty dict
1815     test = not nresult or not isinstance(nresult, dict)
1816     _ErrorIf(test, self.ENODERPC, node,
1817                   "unable to verify node: no data returned")
1818     if test:
1819       return False
1820
1821     # compares ganeti version
1822     local_version = constants.PROTOCOL_VERSION
1823     remote_version = nresult.get("version", None)
1824     test = not (remote_version and
1825                 isinstance(remote_version, (list, tuple)) and
1826                 len(remote_version) == 2)
1827     _ErrorIf(test, self.ENODERPC, node,
1828              "connection to node returned invalid data")
1829     if test:
1830       return False
1831
1832     test = local_version != remote_version[0]
1833     _ErrorIf(test, self.ENODEVERSION, node,
1834              "incompatible protocol versions: master %s,"
1835              " node %s", local_version, remote_version[0])
1836     if test:
1837       return False
1838
1839     # node seems compatible, we can actually try to look into its results
1840
1841     # full package version
1842     self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1843                   self.ENODEVERSION, node,
1844                   "software version mismatch: master %s, node %s",
1845                   constants.RELEASE_VERSION, remote_version[1],
1846                   code=self.ETYPE_WARNING)
1847
1848     hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1849     if ninfo.vm_capable and isinstance(hyp_result, dict):
1850       for hv_name, hv_result in hyp_result.iteritems():
1851         test = hv_result is not None
1852         _ErrorIf(test, self.ENODEHV, node,
1853                  "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1854
1855     hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1856     if ninfo.vm_capable and isinstance(hvp_result, list):
1857       for item, hv_name, hv_result in hvp_result:
1858         _ErrorIf(True, self.ENODEHV, node,
1859                  "hypervisor %s parameter verify failure (source %s): %s",
1860                  hv_name, item, hv_result)
1861
1862     test = nresult.get(constants.NV_NODESETUP,
1863                        ["Missing NODESETUP results"])
1864     _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1865              "; ".join(test))
1866
1867     return True
1868
1869   def _VerifyNodeTime(self, ninfo, nresult,
1870                       nvinfo_starttime, nvinfo_endtime):
1871     """Check the node time.
1872
1873     @type ninfo: L{objects.Node}
1874     @param ninfo: the node to check
1875     @param nresult: the remote results for the node
1876     @param nvinfo_starttime: the start time of the RPC call
1877     @param nvinfo_endtime: the end time of the RPC call
1878
1879     """
1880     node = ninfo.name
1881     _ErrorIf = self._ErrorIf # pylint: disable=C0103
1882
1883     ntime = nresult.get(constants.NV_TIME, None)
1884     try:
1885       ntime_merged = utils.MergeTime(ntime)
1886     except (ValueError, TypeError):
1887       _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1888       return
1889
1890     if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1891       ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1892     elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1893       ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1894     else:
1895       ntime_diff = None
1896
1897     _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1898              "Node time diverges by at least %s from master node time",
1899              ntime_diff)
1900
1901   def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1902     """Check the node LVM results.
1903
1904     @type ninfo: L{objects.Node}
1905     @param ninfo: the node to check
1906     @param nresult: the remote results for the node
1907     @param vg_name: the configured VG name
1908
1909     """
1910     if vg_name is None:
1911       return
1912
1913     node = ninfo.name
1914     _ErrorIf = self._ErrorIf # pylint: disable=C0103
1915
1916     # checks vg existence and size > 20G
1917     vglist = nresult.get(constants.NV_VGLIST, None)
1918     test = not vglist
1919     _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1920     if not test:
1921       vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1922                                             constants.MIN_VG_SIZE)
1923       _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1924
1925     # check pv names
1926     pvlist = nresult.get(constants.NV_PVLIST, None)
1927     test = pvlist is None
1928     _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1929     if not test:
1930       # check that ':' is not present in PV names, since it's a
1931       # special character for lvcreate (denotes the range of PEs to
1932       # use on the PV)
1933       for _, pvname, owner_vg in pvlist:
1934         test = ":" in pvname
1935         _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1936                  " '%s' of VG '%s'", pvname, owner_vg)
1937
1938   def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1939     """Check the node bridges.
1940
1941     @type ninfo: L{objects.Node}
1942     @param ninfo: the node to check
1943     @param nresult: the remote results for the node
1944     @param bridges: the expected list of bridges
1945
1946     """
1947     if not bridges:
1948       return
1949
1950     node = ninfo.name
1951     _ErrorIf = self._ErrorIf # pylint: disable=C0103
1952
1953     missing = nresult.get(constants.NV_BRIDGES, None)
1954     test = not isinstance(missing, list)
1955     _ErrorIf(test, self.ENODENET, node,
1956              "did not return valid bridge information")
1957     if not test:
1958       _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1959                utils.CommaJoin(sorted(missing)))
1960
1961   def _VerifyNodeNetwork(self, ninfo, nresult):
1962     """Check the node network connectivity results.
1963
1964     @type ninfo: L{objects.Node}
1965     @param ninfo: the node to check
1966     @param nresult: the remote results for the node
1967
1968     """
1969     node = ninfo.name
1970     _ErrorIf = self._ErrorIf # pylint: disable=C0103
1971
1972     test = constants.NV_NODELIST not in nresult
1973     _ErrorIf(test, self.ENODESSH, node,
1974              "node hasn't returned node ssh connectivity data")
1975     if not test:
1976       if nresult[constants.NV_NODELIST]:
1977         for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1978           _ErrorIf(True, self.ENODESSH, node,
1979                    "ssh communication with node '%s': %s", a_node, a_msg)
1980
1981     test = constants.NV_NODENETTEST not in nresult
1982     _ErrorIf(test, self.ENODENET, node,
1983              "node hasn't returned node tcp connectivity data")
1984     if not test:
1985       if nresult[constants.NV_NODENETTEST]:
1986         nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1987         for anode in nlist:
1988           _ErrorIf(True, self.ENODENET, node,
1989                    "tcp communication with node '%s': %s",
1990                    anode, nresult[constants.NV_NODENETTEST][anode])
1991
1992     test = constants.NV_MASTERIP not in nresult
1993     _ErrorIf(test, self.ENODENET, node,
1994              "node hasn't returned node master IP reachability data")
1995     if not test:
1996       if not nresult[constants.NV_MASTERIP]:
1997         if node == self.master_node:
1998           msg = "the master node cannot reach the master IP (not configured?)"
1999         else:
2000           msg = "cannot reach the master IP"
2001         _ErrorIf(True, self.ENODENET, node, msg)
2002
2003   def _VerifyInstance(self, instance, instanceconfig, node_image,
2004                       diskstatus):
2005     """Verify an instance.
2006
2007     This function checks to see if the required block devices are
2008     available on the instance's node.
2009
2010     """
2011     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2012     node_current = instanceconfig.primary_node
2013
2014     node_vol_should = {}
2015     instanceconfig.MapLVsByNode(node_vol_should)
2016
2017     for node in node_vol_should:
2018       n_img = node_image[node]
2019       if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
2020         # ignore missing volumes on offline or broken nodes
2021         continue
2022       for volume in node_vol_should[node]:
2023         test = volume not in n_img.volumes
2024         _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
2025                  "volume %s missing on node %s", volume, node)
2026
2027     if instanceconfig.admin_up:
2028       pri_img = node_image[node_current]
2029       test = instance not in pri_img.instances and not pri_img.offline
2030       _ErrorIf(test, self.EINSTANCEDOWN, instance,
2031                "instance not running on its primary node %s",
2032                node_current)
2033
2034     diskdata = [(nname, success, status, idx)
2035                 for (nname, disks) in diskstatus.items()
2036                 for idx, (success, status) in enumerate(disks)]
2037
2038     for nname, success, bdev_status, idx in diskdata:
2039       # the 'ghost node' construction in Exec() ensures that we have a
2040       # node here
2041       snode = node_image[nname]
2042       bad_snode = snode.ghost or snode.offline
2043       _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
2044                self.EINSTANCEFAULTYDISK, instance,
2045                "couldn't retrieve status for disk/%s on %s: %s",
2046                idx, nname, bdev_status)
2047       _ErrorIf((instanceconfig.admin_up and success and
2048                 bdev_status.ldisk_status == constants.LDS_FAULTY),
2049                self.EINSTANCEFAULTYDISK, instance,
2050                "disk/%s on %s is faulty", idx, nname)
2051
2052   def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
2053     """Verify if there are any unknown volumes in the cluster.
2054
2055     The .os, .swap and backup volumes are ignored. All other volumes are
2056     reported as unknown.
2057
2058     @type reserved: L{ganeti.utils.FieldSet}
2059     @param reserved: a FieldSet of reserved volume names
2060
2061     """
2062     for node, n_img in node_image.items():
2063       if (n_img.offline or n_img.rpc_fail or n_img.lvm_fail or
2064           self.all_node_info[node].group != self.group_uuid):
2065         # skip non-healthy nodes
2066         continue
2067       for volume in n_img.volumes:
2068         test = ((node not in node_vol_should or
2069                 volume not in node_vol_should[node]) and
2070                 not reserved.Matches(volume))
2071         self._ErrorIf(test, self.ENODEORPHANLV, node,
2072                       "volume %s is unknown", volume)
2073
2074   def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
2075     """Verify N+1 Memory Resilience.
2076
2077     Check that if one single node dies we can still start all the
2078     instances it was primary for.
2079
2080     """
2081     cluster_info = self.cfg.GetClusterInfo()
2082     for node, n_img in node_image.items():
2083       # This code checks that every node which is now listed as
2084       # secondary has enough memory to host all instances it is
2085       # supposed to should a single other node in the cluster fail.
2086       # FIXME: not ready for failover to an arbitrary node
2087       # FIXME: does not support file-backed instances
2088       # WARNING: we currently take into account down instances as well
2089       # as up ones, considering that even if they're down someone
2090       # might want to start them even in the event of a node failure.
2091       if n_img.offline or self.all_node_info[node].group != self.group_uuid:
2092         # we're skipping nodes marked offline and nodes in other groups from
2093         # the N+1 warning, since most likely we don't have good memory
2094         # infromation from them; we already list instances living on such
2095         # nodes, and that's enough warning
2096         continue
2097       for prinode, instances in n_img.sbp.items():
2098         needed_mem = 0
2099         for instance in instances:
2100           bep = cluster_info.FillBE(instance_cfg[instance])
2101           if bep[constants.BE_AUTO_BALANCE]:
2102             needed_mem += bep[constants.BE_MEMORY]
2103         test = n_img.mfree < needed_mem
2104         self._ErrorIf(test, self.ENODEN1, node,
2105                       "not enough memory to accomodate instance failovers"
2106                       " should node %s fail (%dMiB needed, %dMiB available)",
2107                       prinode, needed_mem, n_img.mfree)
2108
2109   @classmethod
2110   def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
2111                    (files_all, files_all_opt, files_mc, files_vm)):
2112     """Verifies file checksums collected from all nodes.
2113
2114     @param errorif: Callback for reporting errors
2115     @param nodeinfo: List of L{objects.Node} objects
2116     @param master_node: Name of master node
2117     @param all_nvinfo: RPC results
2118
2119     """
2120     assert (len(files_all | files_all_opt | files_mc | files_vm) ==
2121             sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
2122            "Found file listed in more than one file list"
2123
2124     # Define functions determining which nodes to consider for a file
2125     files2nodefn = [
2126       (files_all, None),
2127       (files_all_opt, None),
2128       (files_mc, lambda node: (node.master_candidate or
2129                                node.name == master_node)),
2130       (files_vm, lambda node: node.vm_capable),
2131       ]
2132
2133     # Build mapping from filename to list of nodes which should have the file
2134     nodefiles = {}
2135     for (files, fn) in files2nodefn:
2136       if fn is None:
2137         filenodes = nodeinfo
2138       else:
2139         filenodes = filter(fn, nodeinfo)
2140       nodefiles.update((filename,
2141                         frozenset(map(operator.attrgetter("name"), filenodes)))
2142                        for filename in files)
2143
2144     assert set(nodefiles) == (files_all | files_all_opt | files_mc | files_vm)
2145
2146     fileinfo = dict((filename, {}) for filename in nodefiles)
2147     ignore_nodes = set()
2148
2149     for node in nodeinfo:
2150       if node.offline:
2151         ignore_nodes.add(node.name)
2152         continue
2153
2154       nresult = all_nvinfo[node.name]
2155
2156       if nresult.fail_msg or not nresult.payload:
2157         node_files = None
2158       else:
2159         node_files = nresult.payload.get(constants.NV_FILELIST, None)
2160
2161       test = not (node_files and isinstance(node_files, dict))
2162       errorif(test, cls.ENODEFILECHECK, node.name,
2163               "Node did not return file checksum data")
2164       if test:
2165         ignore_nodes.add(node.name)
2166         continue
2167
2168       # Build per-checksum mapping from filename to nodes having it
2169       for (filename, checksum) in node_files.items():
2170         assert filename in nodefiles
2171         fileinfo[filename].setdefault(checksum, set()).add(node.name)
2172
2173     for (filename, checksums) in fileinfo.items():
2174       assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
2175
2176       # Nodes having the file
2177       with_file = frozenset(node_name
2178                             for nodes in fileinfo[filename].values()
2179                             for node_name in nodes) - ignore_nodes
2180
2181       expected_nodes = nodefiles[filename] - ignore_nodes
2182
2183       # Nodes missing file
2184       missing_file = expected_nodes - with_file
2185
2186       if filename in files_all_opt:
2187         # All or no nodes
2188         errorif(missing_file and missing_file != expected_nodes,
2189                 cls.ECLUSTERFILECHECK, None,
2190                 "File %s is optional, but it must exist on all or no"
2191                 " nodes (not found on %s)",
2192                 filename, utils.CommaJoin(utils.NiceSort(missing_file)))
2193       else:
2194         # Non-optional files
2195         errorif(missing_file, cls.ECLUSTERFILECHECK, None,
2196                 "File %s is missing from node(s) %s", filename,
2197                 utils.CommaJoin(utils.NiceSort(missing_file)))
2198
2199         # Warn if a node has a file it shouldn't
2200         unexpected = with_file - expected_nodes
2201         errorif(unexpected,
2202                 cls.ECLUSTERFILECHECK, None,
2203                 "File %s should not exist on node(s) %s",
2204                 filename, utils.CommaJoin(utils.NiceSort(unexpected)))
2205
2206       # See if there are multiple versions of the file
2207       test = len(checksums) > 1
2208       if test:
2209         variants = ["variant %s on %s" %
2210                     (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
2211                     for (idx, (checksum, nodes)) in
2212                       enumerate(sorted(checksums.items()))]
2213       else:
2214         variants = []
2215
2216       errorif(test, cls.ECLUSTERFILECHECK, None,
2217               "File %s found with %s different checksums (%s)",
2218               filename, len(checksums), "; ".join(variants))
2219
2220   def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
2221                       drbd_map):
2222     """Verifies and the node DRBD status.
2223
2224     @type ninfo: L{objects.Node}
2225     @param ninfo: the node to check
2226     @param nresult: the remote results for the node
2227     @param instanceinfo: the dict of instances
2228     @param drbd_helper: the configured DRBD usermode helper
2229     @param drbd_map: the DRBD map as returned by
2230         L{ganeti.config.ConfigWriter.ComputeDRBDMap}
2231
2232     """
2233     node = ninfo.name
2234     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2235
2236     if drbd_helper:
2237       helper_result = nresult.get(constants.NV_DRBDHELPER, None)
2238       test = (helper_result == None)
2239       _ErrorIf(test, self.ENODEDRBDHELPER, node,
2240                "no drbd usermode helper returned")
2241       if helper_result:
2242         status, payload = helper_result
2243         test = not status
2244         _ErrorIf(test, self.ENODEDRBDHELPER, node,
2245                  "drbd usermode helper check unsuccessful: %s", payload)
2246         test = status and (payload != drbd_helper)
2247         _ErrorIf(test, self.ENODEDRBDHELPER, node,
2248                  "wrong drbd usermode helper: %s", payload)
2249
2250     # compute the DRBD minors
2251     node_drbd = {}
2252     for minor, instance in drbd_map[node].items():
2253       test = instance not in instanceinfo
2254       _ErrorIf(test, self.ECLUSTERCFG, None,
2255                "ghost instance '%s' in temporary DRBD map", instance)
2256         # ghost instance should not be running, but otherwise we
2257         # don't give double warnings (both ghost instance and
2258         # unallocated minor in use)
2259       if test:
2260         node_drbd[minor] = (instance, False)
2261       else:
2262         instance = instanceinfo[instance]
2263         node_drbd[minor] = (instance.name, instance.admin_up)
2264
2265     # and now check them
2266     used_minors = nresult.get(constants.NV_DRBDLIST, [])
2267     test = not isinstance(used_minors, (tuple, list))
2268     _ErrorIf(test, self.ENODEDRBD, node,
2269              "cannot parse drbd status file: %s", str(used_minors))
2270     if test:
2271       # we cannot check drbd status
2272       return
2273
2274     for minor, (iname, must_exist) in node_drbd.items():
2275       test = minor not in used_minors and must_exist
2276       _ErrorIf(test, self.ENODEDRBD, node,
2277                "drbd minor %d of instance %s is not active", minor, iname)
2278     for minor in used_minors:
2279       test = minor not in node_drbd
2280       _ErrorIf(test, self.ENODEDRBD, node,
2281                "unallocated drbd minor %d is in use", minor)
2282
2283   def _UpdateNodeOS(self, ninfo, nresult, nimg):
2284     """Builds the node OS structures.
2285
2286     @type ninfo: L{objects.Node}
2287     @param ninfo: the node to check
2288     @param nresult: the remote results for the node
2289     @param nimg: the node image object
2290
2291     """
2292     node = ninfo.name
2293     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2294
2295     remote_os = nresult.get(constants.NV_OSLIST, None)
2296     test = (not isinstance(remote_os, list) or
2297             not compat.all(isinstance(v, list) and len(v) == 7
2298                            for v in remote_os))
2299
2300     _ErrorIf(test, self.ENODEOS, node,
2301              "node hasn't returned valid OS data")
2302
2303     nimg.os_fail = test
2304
2305     if test:
2306       return
2307
2308     os_dict = {}
2309
2310     for (name, os_path, status, diagnose,
2311          variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2312
2313       if name not in os_dict:
2314         os_dict[name] = []
2315
2316       # parameters is a list of lists instead of list of tuples due to
2317       # JSON lacking a real tuple type, fix it:
2318       parameters = [tuple(v) for v in parameters]
2319       os_dict[name].append((os_path, status, diagnose,
2320                             set(variants), set(parameters), set(api_ver)))
2321
2322     nimg.oslist = os_dict
2323
2324   def _VerifyNodeOS(self, ninfo, nimg, base):
2325     """Verifies the node OS list.
2326
2327     @type ninfo: L{objects.Node}
2328     @param ninfo: the node to check
2329     @param nimg: the node image object
2330     @param base: the 'template' node we match against (e.g. from the master)
2331
2332     """
2333     node = ninfo.name
2334     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2335
2336     assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2337
2338     beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
2339     for os_name, os_data in nimg.oslist.items():
2340       assert os_data, "Empty OS status for OS %s?!" % os_name
2341       f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
2342       _ErrorIf(not f_status, self.ENODEOS, node,
2343                "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
2344       _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
2345                "OS '%s' has multiple entries (first one shadows the rest): %s",
2346                os_name, utils.CommaJoin([v[0] for v in os_data]))
2347       # comparisons with the 'base' image
2348       test = os_name not in base.oslist
2349       _ErrorIf(test, self.ENODEOS, node,
2350                "Extra OS %s not present on reference node (%s)",
2351                os_name, base.name)
2352       if test:
2353         continue
2354       assert base.oslist[os_name], "Base node has empty OS status?"
2355       _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
2356       if not b_status:
2357         # base OS is invalid, skipping
2358         continue
2359       for kind, a, b in [("API version", f_api, b_api),
2360                          ("variants list", f_var, b_var),
2361                          ("parameters", beautify_params(f_param),
2362                           beautify_params(b_param))]:
2363         _ErrorIf(a != b, self.ENODEOS, node,
2364                  "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2365                  kind, os_name, base.name,
2366                  utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2367
2368     # check any missing OSes
2369     missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2370     _ErrorIf(missing, self.ENODEOS, node,
2371              "OSes present on reference node %s but missing on this node: %s",
2372              base.name, utils.CommaJoin(missing))
2373
2374   def _VerifyOob(self, ninfo, nresult):
2375     """Verifies out of band functionality of a node.
2376
2377     @type ninfo: L{objects.Node}
2378     @param ninfo: the node to check
2379     @param nresult: the remote results for the node
2380
2381     """
2382     node = ninfo.name
2383     # We just have to verify the paths on master and/or master candidates
2384     # as the oob helper is invoked on the master
2385     if ((ninfo.master_candidate or ninfo.master_capable) and
2386         constants.NV_OOB_PATHS in nresult):
2387       for path_result in nresult[constants.NV_OOB_PATHS]:
2388         self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2389
2390   def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2391     """Verifies and updates the node volume data.
2392
2393     This function will update a L{NodeImage}'s internal structures
2394     with data from the remote call.
2395
2396     @type ninfo: L{objects.Node}
2397     @param ninfo: the node to check
2398     @param nresult: the remote results for the node
2399     @param nimg: the node image object
2400     @param vg_name: the configured VG name
2401
2402     """
2403     node = ninfo.name
2404     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2405
2406     nimg.lvm_fail = True
2407     lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2408     if vg_name is None:
2409       pass
2410     elif isinstance(lvdata, basestring):
2411       _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2412                utils.SafeEncode(lvdata))
2413     elif not isinstance(lvdata, dict):
2414       _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2415     else:
2416       nimg.volumes = lvdata
2417       nimg.lvm_fail = False
2418
2419   def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2420     """Verifies and updates the node instance list.
2421
2422     If the listing was successful, then updates this node's instance
2423     list. Otherwise, it marks the RPC call as failed for the instance
2424     list key.
2425
2426     @type ninfo: L{objects.Node}
2427     @param ninfo: the node to check
2428     @param nresult: the remote results for the node
2429     @param nimg: the node image object
2430
2431     """
2432     idata = nresult.get(constants.NV_INSTANCELIST, None)
2433     test = not isinstance(idata, list)
2434     self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2435                   " (instancelist): %s", utils.SafeEncode(str(idata)))
2436     if test:
2437       nimg.hyp_fail = True
2438     else:
2439       nimg.instances = idata
2440
2441   def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2442     """Verifies and computes a node information map
2443
2444     @type ninfo: L{objects.Node}
2445     @param ninfo: the node to check
2446     @param nresult: the remote results for the node
2447     @param nimg: the node image object
2448     @param vg_name: the configured VG name
2449
2450     """
2451     node = ninfo.name
2452     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2453
2454     # try to read free memory (from the hypervisor)
2455     hv_info = nresult.get(constants.NV_HVINFO, None)
2456     test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2457     _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2458     if not test:
2459       try:
2460         nimg.mfree = int(hv_info["memory_free"])
2461       except (ValueError, TypeError):
2462         _ErrorIf(True, self.ENODERPC, node,
2463                  "node returned invalid nodeinfo, check hypervisor")
2464
2465     # FIXME: devise a free space model for file based instances as well
2466     if vg_name is not None:
2467       test = (constants.NV_VGLIST not in nresult or
2468               vg_name not in nresult[constants.NV_VGLIST])
2469       _ErrorIf(test, self.ENODELVM, node,
2470                "node didn't return data for the volume group '%s'"
2471                " - it is either missing or broken", vg_name)
2472       if not test:
2473         try:
2474           nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2475         except (ValueError, TypeError):
2476           _ErrorIf(True, self.ENODERPC, node,
2477                    "node returned invalid LVM info, check LVM status")
2478
2479   def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2480     """Gets per-disk status information for all instances.
2481
2482     @type nodelist: list of strings
2483     @param nodelist: Node names
2484     @type node_image: dict of (name, L{objects.Node})
2485     @param node_image: Node objects
2486     @type instanceinfo: dict of (name, L{objects.Instance})
2487     @param instanceinfo: Instance objects
2488     @rtype: {instance: {node: [(succes, payload)]}}
2489     @return: a dictionary of per-instance dictionaries with nodes as
2490         keys and disk information as values; the disk information is a
2491         list of tuples (success, payload)
2492
2493     """
2494     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2495
2496     node_disks = {}
2497     node_disks_devonly = {}
2498     diskless_instances = set()
2499     diskless = constants.DT_DISKLESS
2500
2501     for nname in nodelist:
2502       node_instances = list(itertools.chain(node_image[nname].pinst,
2503                                             node_image[nname].sinst))
2504       diskless_instances.update(inst for inst in node_instances
2505                                 if instanceinfo[inst].disk_template == diskless)
2506       disks = [(inst, disk)
2507                for inst in node_instances
2508                for disk in instanceinfo[inst].disks]
2509
2510       if not disks:
2511         # No need to collect data
2512         continue
2513
2514       node_disks[nname] = disks
2515
2516       # Creating copies as SetDiskID below will modify the objects and that can
2517       # lead to incorrect data returned from nodes
2518       devonly = [dev.Copy() for (_, dev) in disks]
2519
2520       for dev in devonly:
2521         self.cfg.SetDiskID(dev, nname)
2522
2523       node_disks_devonly[nname] = devonly
2524
2525     assert len(node_disks) == len(node_disks_devonly)
2526
2527     # Collect data from all nodes with disks
2528     result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2529                                                           node_disks_devonly)
2530
2531     assert len(result) == len(node_disks)
2532
2533     instdisk = {}
2534
2535     for (nname, nres) in result.items():
2536       disks = node_disks[nname]
2537
2538       if nres.offline:
2539         # No data from this node
2540         data = len(disks) * [(False, "node offline")]
2541       else:
2542         msg = nres.fail_msg
2543         _ErrorIf(msg, self.ENODERPC, nname,
2544                  "while getting disk information: %s", msg)
2545         if msg:
2546           # No data from this node
2547           data = len(disks) * [(False, msg)]
2548         else:
2549           data = []
2550           for idx, i in enumerate(nres.payload):
2551             if isinstance(i, (tuple, list)) and len(i) == 2:
2552               data.append(i)
2553             else:
2554               logging.warning("Invalid result from node %s, entry %d: %s",
2555                               nname, idx, i)
2556               data.append((False, "Invalid result from the remote node"))
2557
2558       for ((inst, _), status) in zip(disks, data):
2559         instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2560
2561     # Add empty entries for diskless instances.
2562     for inst in diskless_instances:
2563       assert inst not in instdisk
2564       instdisk[inst] = {}
2565
2566     assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2567                       len(nnames) <= len(instanceinfo[inst].all_nodes) and
2568                       compat.all(isinstance(s, (tuple, list)) and
2569                                  len(s) == 2 for s in statuses)
2570                       for inst, nnames in instdisk.items()
2571                       for nname, statuses in nnames.items())
2572     assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2573
2574     return instdisk
2575
2576   @staticmethod
2577   def _SshNodeSelector(group_uuid, all_nodes):
2578     """Create endless iterators for all potential SSH check hosts.
2579
2580     """
2581     nodes = [node for node in all_nodes
2582              if (node.group != group_uuid and
2583                  not node.offline)]
2584     keyfunc = operator.attrgetter("group")
2585
2586     return map(itertools.cycle,
2587                [sorted(map(operator.attrgetter("name"), names))
2588                 for _, names in itertools.groupby(sorted(nodes, key=keyfunc),
2589                                                   keyfunc)])
2590
2591   @classmethod
2592   def _SelectSshCheckNodes(cls, group_nodes, group_uuid, all_nodes):
2593     """Choose which nodes should talk to which other nodes.
2594
2595     We will make nodes contact all nodes in their group, and one node from
2596     every other group.
2597
2598     @warning: This algorithm has a known issue if one node group is much
2599       smaller than others (e.g. just one node). In such a case all other
2600       nodes will talk to the single node.
2601
2602     """
2603     online_nodes = sorted(node.name for node in group_nodes if not node.offline)
2604     sel = cls._SshNodeSelector(group_uuid, all_nodes)
2605
2606     return (online_nodes,
2607             dict((name, sorted([i.next() for i in sel]))
2608                  for name in online_nodes))
2609
2610   def BuildHooksEnv(self):
2611     """Build hooks env.
2612
2613     Cluster-Verify hooks just ran in the post phase and their failure makes
2614     the output be logged in the verify output and the verification to fail.
2615
2616     """
2617     env = {
2618       "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2619       }
2620
2621     env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2622                for node in self.my_node_info.values())
2623
2624     return env
2625
2626   def BuildHooksNodes(self):
2627     """Build hooks nodes.
2628
2629     """
2630     return ([], self.my_node_names)
2631
2632   def Exec(self, feedback_fn):
2633     """Verify integrity of the node group, performing various test on nodes.
2634
2635     """
2636     # This method has too many local variables. pylint: disable=R0914
2637     feedback_fn("* Verifying group '%s'" % self.group_info.name)
2638
2639     if not self.my_node_names:
2640       # empty node group
2641       feedback_fn("* Empty node group, skipping verification")
2642       return True
2643
2644     self.bad = False
2645     _ErrorIf = self._ErrorIf # pylint: disable=C0103
2646     verbose = self.op.verbose
2647     self._feedback_fn = feedback_fn
2648
2649     vg_name = self.cfg.GetVGName()
2650     drbd_helper = self.cfg.GetDRBDHelper()
2651     cluster = self.cfg.GetClusterInfo()
2652     groupinfo = self.cfg.GetAllNodeGroupsInfo()
2653     hypervisors = cluster.enabled_hypervisors
2654     node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2655
2656     i_non_redundant = [] # Non redundant instances
2657     i_non_a_balanced = [] # Non auto-balanced instances
2658     n_offline = 0 # Count of offline nodes
2659     n_drained = 0 # Count of nodes being drained
2660     node_vol_should = {}
2661
2662     # FIXME: verify OS list
2663
2664     # File verification
2665     filemap = _ComputeAncillaryFiles(cluster, False)
2666
2667     # do local checksums
2668     master_node = self.master_node = self.cfg.GetMasterNode()
2669     master_ip = self.cfg.GetMasterIP()
2670
2671     feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2672
2673     node_verify_param = {
2674       constants.NV_FILELIST:
2675         utils.UniqueSequence(filename
2676                              for files in filemap
2677                              for filename in files),
2678       constants.NV_NODELIST:
2679         self._SelectSshCheckNodes(node_data_list, self.group_uuid,
2680                                   self.all_node_info.values()),
2681       constants.NV_HYPERVISOR: hypervisors,
2682       constants.NV_HVPARAMS:
2683         _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2684       constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2685                                  for node in node_data_list
2686                                  if not node.offline],
2687       constants.NV_INSTANCELIST: hypervisors,
2688       constants.NV_VERSION: None,
2689       constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2690       constants.NV_NODESETUP: None,
2691       constants.NV_TIME: None,
2692       constants.NV_MASTERIP: (master_node, master_ip),
2693       constants.NV_OSLIST: None,
2694       constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2695       }
2696
2697     if vg_name is not None:
2698       node_verify_param[constants.NV_VGLIST] = None
2699       node_verify_param[constants.NV_LVLIST] = vg_name
2700       node_verify_param[constants.NV_PVLIST] = [vg_name]
2701       node_verify_param[constants.NV_DRBDLIST] = None
2702
2703     if drbd_helper:
2704       node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2705
2706     # bridge checks
2707     # FIXME: this needs to be changed per node-group, not cluster-wide
2708     bridges = set()
2709     default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2710     if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2711       bridges.add(default_nicpp[constants.NIC_LINK])
2712     for instance in self.my_inst_info.values():
2713       for nic in instance.nics:
2714         full_nic = cluster.SimpleFillNIC(nic.nicparams)
2715         if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2716           bridges.add(full_nic[constants.NIC_LINK])
2717
2718     if bridges:
2719       node_verify_param[constants.NV_BRIDGES] = list(bridges)
2720
2721     # Build our expected cluster state
2722     node_image = dict((node.name, self.NodeImage(offline=node.offline,
2723                                                  name=node.name,
2724                                                  vm_capable=node.vm_capable))
2725                       for node in node_data_list)
2726
2727     # Gather OOB paths
2728     oob_paths = []
2729     for node in self.all_node_info.values():
2730       path = _SupportsOob(self.cfg, node)
2731       if path and path not in oob_paths:
2732         oob_paths.append(path)
2733
2734     if oob_paths:
2735       node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2736
2737     for instance in self.my_inst_names:
2738       inst_config = self.my_inst_info[instance]
2739
2740       for nname in inst_config.all_nodes:
2741         if nname not in node_image:
2742           gnode = self.NodeImage(name=nname)
2743           gnode.ghost = (nname not in self.all_node_info)
2744           node_image[nname] = gnode
2745
2746       inst_config.MapLVsByNode(node_vol_should)
2747
2748       pnode = inst_config.primary_node
2749       node_image[pnode].pinst.append(instance)
2750
2751       for snode in inst_config.secondary_nodes:
2752         nimg = node_image[snode]
2753         nimg.sinst.append(instance)
2754         if pnode not in nimg.sbp:
2755           nimg.sbp[pnode] = []
2756         nimg.sbp[pnode].append(instance)
2757
2758     # At this point, we have the in-memory data structures complete,
2759     # except for the runtime information, which we'll gather next
2760
2761     # Due to the way our RPC system works, exact response times cannot be
2762     # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2763     # time before and after executing the request, we can at least have a time
2764     # window.
2765     nvinfo_starttime = time.time()
2766     all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2767                                            node_verify_param,
2768                                            self.cfg.GetClusterName())
2769     nvinfo_endtime = time.time()
2770
2771     if self.extra_lv_nodes and vg_name is not None:
2772       extra_lv_nvinfo = \
2773           self.rpc.call_node_verify(self.extra_lv_nodes,
2774                                     {constants.NV_LVLIST: vg_name},
2775                                     self.cfg.GetClusterName())
2776     else:
2777       extra_lv_nvinfo = {}
2778
2779     all_drbd_map = self.cfg.ComputeDRBDMap()
2780
2781     feedback_fn("* Gathering disk information (%s nodes)" %
2782                 len(self.my_node_names))
2783     instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2784                                      self.my_inst_info)
2785
2786     feedback_fn("* Verifying configuration file consistency")
2787
2788     # If not all nodes are being checked, we need to make sure the master node
2789     # and a non-checked vm_capable node are in the list.
2790     absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2791     if absent_nodes:
2792       vf_nvinfo = all_nvinfo.copy()
2793       vf_node_info = list(self.my_node_info.values())
2794       additional_nodes = []
2795       if master_node not in self.my_node_info:
2796         additional_nodes.append(master_node)
2797         vf_node_info.append(self.all_node_info[master_node])
2798       # Add the first vm_capable node we find which is not included
2799       for node in absent_nodes:
2800         nodeinfo = self.all_node_info[node]
2801         if nodeinfo.vm_capable and not nodeinfo.offline:
2802           additional_nodes.append(node)
2803           vf_node_info.append(self.all_node_info[node])
2804           break
2805       key = constants.NV_FILELIST
2806       vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2807                                                  {key: node_verify_param[key]},
2808                                                  self.cfg.GetClusterName()))
2809     else:
2810       vf_nvinfo = all_nvinfo
2811       vf_node_info = self.my_node_info.values()
2812
2813     self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2814
2815     feedback_fn("* Verifying node status")
2816
2817     refos_img = None
2818
2819     for node_i in node_data_list:
2820       node = node_i.name
2821       nimg = node_image[node]
2822
2823       if node_i.offline:
2824         if verbose:
2825           feedback_fn("* Skipping offline node %s" % (node,))
2826         n_offline += 1
2827         continue
2828
2829       if node == master_node:
2830         ntype = "master"
2831       elif node_i.master_candidate:
2832         ntype = "master candidate"
2833       elif node_i.drained:
2834         ntype = "drained"
2835         n_drained += 1
2836       else:
2837         ntype = "regular"
2838       if verbose:
2839         feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2840
2841       msg = all_nvinfo[node].fail_msg
2842       _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2843       if msg:
2844         nimg.rpc_fail = True
2845         continue
2846
2847       nresult = all_nvinfo[node].payload
2848
2849       nimg.call_ok = self._VerifyNode(node_i, nresult)
2850       self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2851       self._VerifyNodeNetwork(node_i, nresult)
2852       self._VerifyOob(node_i, nresult)
2853
2854       if nimg.vm_capable:
2855         self._VerifyNodeLVM(node_i, nresult, vg_name)
2856         self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2857                              all_drbd_map)
2858
2859         self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2860         self._UpdateNodeInstances(node_i, nresult, nimg)
2861         self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2862         self._UpdateNodeOS(node_i, nresult, nimg)
2863
2864         if not nimg.os_fail:
2865           if refos_img is None:
2866             refos_img = nimg
2867           self._VerifyNodeOS(node_i, nimg, refos_img)
2868         self._VerifyNodeBridges(node_i, nresult, bridges)
2869
2870         # Check whether all running instancies are primary for the node. (This
2871         # can no longer be done from _VerifyInstance below, since some of the
2872         # wrong instances could be from other node groups.)
2873         non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2874
2875         for inst in non_primary_inst:
2876           test = inst in self.all_inst_info
2877           _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2878                    "instance should not run on node %s", node_i.name)
2879           _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2880                    "node is running unknown instance %s", inst)
2881
2882     for node, result in extra_lv_nvinfo.items():
2883       self._UpdateNodeVolumes(self.all_node_info[node], result.payload,
2884                               node_image[node], vg_name)
2885
2886     feedback_fn("* Verifying instance status")
2887     for instance in self.my_inst_names:
2888       if verbose:
2889         feedback_fn("* Verifying instance %s" % instance)
2890       inst_config = self.my_inst_info[instance]
2891       self._VerifyInstance(instance, inst_config, node_image,
2892                            instdisk[instance])
2893       inst_nodes_offline = []
2894
2895       pnode = inst_config.primary_node
2896       pnode_img = node_image[pnode]
2897       _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2898                self.ENODERPC, pnode, "instance %s, connection to"
2899                " primary node failed", instance)
2900
2901       _ErrorIf(inst_config.admin_up and pnode_img.offline,
2902                self.EINSTANCEBADNODE, instance,
2903                "instance is marked as running and lives on offline node %s",
2904                inst_config.primary_node)
2905
2906       # If the instance is non-redundant we cannot survive losing its primary
2907       # node, so we are not N+1 compliant. On the other hand we have no disk
2908       # templates with more than one secondary so that situation is not well
2909       # supported either.
2910       # FIXME: does not support file-backed instances
2911       if not inst_config.secondary_nodes:
2912         i_non_redundant.append(instance)
2913
2914       _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2915                instance, "instance has multiple secondary nodes: %s",
2916                utils.CommaJoin(inst_config.secondary_nodes),
2917                code=self.ETYPE_WARNING)
2918
2919       if inst_config.disk_template in constants.DTS_INT_MIRROR:
2920         pnode = inst_config.primary_node
2921         instance_nodes = utils.NiceSort(inst_config.all_nodes)
2922         instance_groups = {}
2923
2924         for node in instance_nodes:
2925           instance_groups.setdefault(self.all_node_info[node].group,
2926                                      []).append(node)
2927
2928         pretty_list = [
2929           "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2930           # Sort so that we always list the primary node first.
2931           for group, nodes in sorted(instance_groups.items(),
2932                                      key=lambda (_, nodes): pnode in nodes,
2933                                      reverse=True)]
2934
2935         self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2936                       instance, "instance has primary and secondary nodes in"
2937                       " different groups: %s", utils.CommaJoin(pretty_list),
2938                       code=self.ETYPE_WARNING)
2939
2940       if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2941         i_non_a_balanced.append(instance)
2942
2943       for snode in inst_config.secondary_nodes:
2944         s_img = node_image[snode]
2945         _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2946                  "instance %s, connection to secondary node failed", instance)
2947
2948         if s_img.offline:
2949           inst_nodes_offline.append(snode)
2950
2951       # warn that the instance lives on offline nodes
2952       _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2953                "instance has offline secondary node(s) %s",
2954                utils.CommaJoin(inst_nodes_offline))
2955       # ... or ghost/non-vm_capable nodes
2956       for node in inst_config.all_nodes:
2957         _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2958                  "instance lives on ghost node %s", node)
2959         _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2960                  instance, "instance lives on non-vm_capable node %s", node)
2961
2962     feedback_fn("* Verifying orphan volumes")
2963     reserved = utils.FieldSet(*cluster.reserved_lvs)
2964
2965     # We will get spurious "unknown volume" warnings if any node of this group
2966     # is secondary for an instance whose primary is in another group. To avoid
2967     # them, we find these instances and add their volumes to node_vol_should.
2968     for inst in self.all_inst_info.values():
2969       for secondary in inst.secondary_nodes:
2970         if (secondary in self.my_node_info
2971             and inst.name not in self.my_inst_info):
2972           inst.MapLVsByNode(node_vol_should)
2973           break
2974
2975     self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2976
2977     if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2978       feedback_fn("* Verifying N+1 Memory redundancy")
2979       self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2980
2981     feedback_fn("* Other Notes")
2982     if i_non_redundant:
2983       feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2984                   % len(i_non_redundant))
2985
2986     if i_non_a_balanced:
2987       feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2988                   % len(i_non_a_balanced))
2989
2990     if n_offline:
2991       feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2992
2993     if n_drained:
2994       feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2995
2996     return not self.bad
2997
2998   def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2999     """Analyze the post-hooks' result
3000
3001     This method analyses the hook result, handles it, and sends some
3002     nicely-formatted feedback back to the user.
3003
3004     @param phase: one of L{constants.HOOKS_PHASE_POST} or
3005         L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
3006     @param hooks_results: the results of the multi-node hooks rpc call
3007     @param feedback_fn: function used send feedback back to the caller
3008     @param lu_result: previous Exec result
3009     @return: the new Exec result, based on the previous result
3010         and hook results
3011
3012     """
3013     # We only really run POST phase hooks, only for non-empty groups,
3014     # and are only interested in their results
3015     if not self.my_node_names:
3016       # empty node group
3017       pass
3018     elif phase == constants.HOOKS_PHASE_POST:
3019       # Used to change hooks' output to proper indentation
3020       feedback_fn("* Hooks Results")
3021       assert hooks_results, "invalid result from hooks"
3022
3023       for node_name in hooks_results:
3024         res = hooks_results[node_name]
3025         msg = res.fail_msg
3026         test = msg and not res.offline
3027         self._ErrorIf(test, self.ENODEHOOKS, node_name,
3028                       "Communication failure in hooks execution: %s", msg)
3029         if res.offline or msg:
3030           # No need to investigate payload if node is offline or gave
3031           # an error.
3032           continue
3033         for script, hkr, output in res.payload:
3034           test = hkr == constants.HKR_FAIL
3035           self._ErrorIf(test, self.ENODEHOOKS, node_name,
3036                         "Script %s failed, output:", script)
3037           if test:
3038             output = self._HOOKS_INDENT_RE.sub("      ", output)
3039             feedback_fn("%s" % output)
3040             lu_result = False
3041
3042     return lu_result
3043
3044
3045 class LUClusterVerifyDisks(NoHooksLU):
3046   """Verifies the cluster disks status.
3047
3048   """
3049   REQ_BGL = False
3050
3051   def ExpandNames(self):
3052     self.share_locks = _ShareAll()
3053     self.needed_locks = {
3054       locking.LEVEL_NODEGROUP: locking.ALL_SET,
3055       }
3056
3057   def Exec(self, feedback_fn):
3058     group_names = self.owned_locks(locking.LEVEL_NODEGROUP)
3059
3060     # Submit one instance of L{opcodes.OpGroupVerifyDisks} per node group
3061     return ResultWithJobs([[opcodes.OpGroupVerifyDisks(group_name=group)]
3062                            for group in group_names])
3063
3064
3065 class LUGroupVerifyDisks(NoHooksLU):
3066   """Verifies the status of all disks in a node group.
3067
3068   """
3069   REQ_BGL = False
3070
3071   def ExpandNames(self):
3072     # Raises errors.OpPrereqError on its own if group can't be found
3073     self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
3074
3075     self.share_locks = _ShareAll()
3076     self.needed_locks = {
3077       locking.LEVEL_INSTANCE: [],
3078       locking.LEVEL_NODEGROUP: [],
3079       locking.LEVEL_NODE: [],
3080       }
3081
3082   def DeclareLocks(self, level):
3083     if level == locking.LEVEL_INSTANCE:
3084       assert not self.needed_locks[locking.LEVEL_INSTANCE]
3085
3086       # Lock instances optimistically, needs verification once node and group
3087       # locks have been acquired
3088       self.needed_locks[locking.LEVEL_INSTANCE] = \
3089         self.cfg.GetNodeGroupInstances(self.group_uuid)
3090
3091     elif level == locking.LEVEL_NODEGROUP:
3092       assert not self.needed_locks[locking.LEVEL_NODEGROUP]
3093
3094       self.needed_locks[locking.LEVEL_NODEGROUP] = \
3095         set([self.group_uuid] +
3096             # Lock all groups used by instances optimistically; this requires
3097             # going via the node before it's locked, requiring verification
3098             # later on
3099             [group_uuid
3100              for instance_name in self.owned_locks(locking.LEVEL_INSTANCE)
3101              for group_uuid in self.cfg.GetInstanceNodeGroups(instance_name)])
3102
3103     elif level == locking.LEVEL_NODE:
3104       # This will only lock the nodes in the group to be verified which contain
3105       # actual instances
3106       self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
3107       self._LockInstancesNodes()
3108
3109       # Lock all nodes in group to be verified
3110       assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
3111       member_nodes = self.cfg.GetNodeGroup(self.group_uuid).members
3112       self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
3113
3114   def CheckPrereq(self):
3115     owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
3116     owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
3117     owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
3118
3119     assert self.group_uuid in owned_groups
3120
3121     # Check if locked instances are still correct
3122     _CheckNodeGroupInstances(self.cfg, self.group_uuid, owned_instances)
3123
3124     # Get instance information
3125     self.instances = dict(self.cfg.GetMultiInstanceInfo(owned_instances))
3126
3127     # Check if node groups for locked instances are still correct
3128     for (instance_name, inst) in self.instances.items():
3129       assert owned_nodes.issuperset(inst.all_nodes), \
3130         "Instance %s's nodes changed while we kept the lock" % instance_name
3131
3132       inst_groups = _CheckInstanceNodeGroups(self.cfg, instance_name,
3133                                              owned_groups)
3134
3135       assert self.group_uuid in inst_groups, \
3136         "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
3137
3138   def Exec(self, feedback_fn):
3139     """Verify integrity of cluster disks.
3140
3141     @rtype: tuple of three items
3142     @return: a tuple of (dict of node-to-node_error, list of instances
3143         which need activate-disks, dict of instance: (node, volume) for
3144         missing volumes
3145
3146     """
3147     res_nodes = {}
3148     res_instances = set()
3149     res_missing = {}
3150
3151     nv_dict = _MapInstanceDisksToNodes([inst
3152                                         for inst in self.instances.values()
3153                                         if inst.admin_up])
3154
3155     if nv_dict:
3156       nodes = utils.NiceSort(set(self.owned_locks(locking.LEVEL_NODE)) &
3157                              set(self.cfg.GetVmCapableNodeList()))
3158
3159       node_lvs = self.rpc.call_lv_list(nodes, [])
3160
3161       for (node, node_res) in node_lvs.items():
3162         if node_res.offline:
3163           continue
3164
3165         msg = node_res.fail_msg
3166         if msg:
3167           logging.warning("Error enumerating LVs on node %s: %s", node, msg)
3168           res_nodes[node] = msg
3169           continue
3170
3171         for lv_name, (_, _, lv_online) in node_res.payload.items():
3172           inst = nv_dict.pop((node, lv_name), None)
3173           if not (lv_online or inst is None):
3174             res_instances.add(inst)
3175
3176       # any leftover items in nv_dict are missing LVs, let's arrange the data
3177       # better
3178       for key, inst in nv_dict.iteritems():
3179         res_missing.setdefault(inst, []).append(list(key))
3180
3181     return (res_nodes, list(res_instances), res_missing)
3182
3183
3184 class LUClusterRepairDiskSizes(NoHooksLU):
3185   """Verifies the cluster disks sizes.
3186
3187   """
3188   REQ_BGL = False
3189
3190   def ExpandNames(self):
3191     if self.op.instances:
3192       self.wanted_names = _GetWantedInstances(self, self.op.instances)
3193       self.needed_locks = {
3194         locking.LEVEL_NODE: [],
3195         locking.LEVEL_INSTANCE: self.wanted_names,
3196         }
3197       self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3198     else:
3199       self.wanted_names = None
3200       self.needed_locks = {
3201         locking.LEVEL_NODE: locking.ALL_SET,
3202         locking.LEVEL_INSTANCE: locking.ALL_SET,
3203         }
3204     self.share_locks = {
3205       locking.LEVEL_NODE: 1,
3206       locking.LEVEL_INSTANCE: 0,
3207       }
3208
3209   def DeclareLocks(self, level):
3210     if level == locking.LEVEL_NODE and self.wanted_names is not None:
3211       self._LockInstancesNodes(primary_only=True)
3212
3213   def CheckPrereq(self):
3214     """Check prerequisites.
3215
3216     This only checks the optional instance list against the existing names.
3217
3218     """
3219     if self.wanted_names is None:
3220       self.wanted_names = self.owned_locks(locking.LEVEL_INSTANCE)
3221
3222     self.wanted_instances = \
3223         map(compat.snd, self.cfg.GetMultiInstanceInfo(self.wanted_names))
3224
3225   def _EnsureChildSizes(self, disk):
3226     """Ensure children of the disk have the needed disk size.
3227
3228     This is valid mainly for DRBD8 and fixes an issue where the
3229     children have smaller disk size.
3230
3231     @param disk: an L{ganeti.objects.Disk} object
3232
3233     """
3234     if disk.dev_type == constants.LD_DRBD8:
3235       assert disk.children, "Empty children for DRBD8?"
3236       fchild = disk.children[0]
3237       mismatch = fchild.size < disk.size
3238       if mismatch:
3239         self.LogInfo("Child disk has size %d, parent %d, fixing",
3240                      fchild.size, disk.size)
3241         fchild.size = disk.size
3242
3243       # and we recurse on this child only, not on the metadev
3244       return self._EnsureChildSizes(fchild) or mismatch
3245     else:
3246       return False
3247
3248   def Exec(self, feedback_fn):
3249     """Verify the size of cluster disks.
3250
3251     """
3252     # TODO: check child disks too
3253     # TODO: check differences in size between primary/secondary nodes
3254     per_node_disks = {}
3255     for instance in self.wanted_instances:
3256       pnode = instance.primary_node
3257       if pnode not in per_node_disks:
3258         per_node_disks[pnode] = []
3259       for idx, disk in enumerate(instance.disks):
3260         per_node_disks[pnode].append((instance, idx, disk))
3261
3262     changed = []
3263     for node, dskl in per_node_disks.items():
3264       newl = [v[2].Copy() for v in dskl]
3265       for dsk in newl:
3266         self.cfg.SetDiskID(dsk, node)
3267       result = self.rpc.call_blockdev_getsize(node, newl)
3268       if result.fail_msg:
3269         self.LogWarning("Failure in blockdev_getsize call to node"
3270                         " %s, ignoring", node)
3271         continue
3272       if len(result.payload) != len(dskl):
3273         logging.warning("Invalid result from node %s: len(dksl)=%d,"
3274                         " result.payload=%s", node, len(dskl), result.payload)
3275         self.LogWarning("Invalid result from node %s, ignoring node results",
3276                         node)
3277         continue
3278       for ((instance, idx, disk), size) in zip(dskl, result.payload):
3279         if size is None:
3280           self.LogWarning("Disk %d of instance %s did not return size"
3281                           " information, ignoring", idx, instance.name)
3282           continue
3283         if not isinstance(size, (int, long)):
3284           self.LogWarning("Disk %d of instance %s did not return valid"
3285                           " size information, ignoring", idx, instance.name)
3286           continue
3287         size = size >> 20
3288         if size != disk.size:
3289           self.LogInfo("Disk %d of instance %s has mismatched size,"
3290                        " correcting: recorded %d, actual %d", idx,
3291                        instance.name, disk.size, size)
3292           disk.size = size
3293           self.cfg.Update(instance, feedback_fn)
3294           changed.append((instance.name, idx, size))
3295         if self._EnsureChildSizes(disk):
3296           self.cfg.Update(instance, feedback_fn)
3297           changed.append((instance.name, idx, disk.size))
3298     return changed
3299
3300
3301 class LUClusterRename(LogicalUnit):
3302   """Rename the cluster.
3303
3304   """
3305   HPATH = "cluster-rename"
3306   HTYPE = constants.HTYPE_CLUSTER
3307
3308   def BuildHooksEnv(self):
3309     """Build hooks env.
3310
3311     """
3312     return {
3313       "OP_TARGET": self.cfg.GetClusterName(),
3314       "NEW_NAME": self.op.name,
3315       }
3316
3317   def BuildHooksNodes(self):
3318     """Build hooks nodes.
3319
3320     """
3321     return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
3322
3323   def CheckPrereq(self):
3324     """Verify that the passed name is a valid one.
3325
3326     """
3327     hostname = netutils.GetHostname(name=self.op.name,
3328                                     family=self.cfg.GetPrimaryIPFamily())
3329
3330     new_name = hostname.name
3331     self.ip = new_ip = hostname.ip
3332     old_name = self.cfg.GetClusterName()
3333     old_ip = self.cfg.GetMasterIP()
3334     if new_name == old_name and new_ip == old_ip:
3335       raise errors.OpPrereqError("Neither the name nor the IP address of the"
3336                                  " cluster has changed",
3337                                  errors.ECODE_INVAL)
3338     if new_ip != old_ip:
3339       if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
3340         raise errors.OpPrereqError("The given cluster IP address (%s) is"
3341                                    " reachable on the network" %
3342                                    new_ip, errors.ECODE_NOTUNIQUE)
3343
3344     self.op.name = new_name
3345
3346   def Exec(self, feedback_fn):
3347     """Rename the cluster.
3348
3349     """
3350     clustername = self.op.name
3351     ip = self.ip
3352
3353     # shutdown the master IP
3354     master = self.cfg.GetMasterNode()
3355     result = self.rpc.call_node_stop_master(master, False)
3356     result.Raise("Could not disable the master role")
3357
3358     try:
3359       cluster = self.cfg.GetClusterInfo()
3360       cluster.cluster_name = clustername
3361       cluster.master_ip = ip
3362       self.cfg.Update(cluster, feedback_fn)
3363
3364       # update the known hosts file
3365       ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
3366       node_list = self.cfg.GetOnlineNodeList()
3367       try:
3368         node_list.remove(master)
3369       except ValueError:
3370         pass
3371       _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3372     finally:
3373       result = self.rpc.call_node_start_master(master, False, False)
3374       msg = result.fail_msg
3375       if msg:
3376         self.LogWarning("Could not re-enable the master role on"
3377                         " the master, please restart manually: %s", msg)
3378
3379     return clustername
3380
3381
3382 class LUClusterSetParams(LogicalUnit):
3383   """Change the parameters of the cluster.
3384
3385   """
3386   HPATH = "cluster-modify"
3387   HTYPE = constants.HTYPE_CLUSTER
3388   REQ_BGL = False
3389
3390   def CheckArguments(self):
3391     """Check parameters
3392
3393     """
3394     if self.op.uid_pool:
3395       uidpool.CheckUidPool(self.op.uid_pool)
3396
3397     if self.op.add_uids:
3398       uidpool.CheckUidPool(self.op.add_uids)
3399
3400     if self.op.remove_uids:
3401       uidpool.CheckUidPool(self.op.remove_uids)
3402
3403   def ExpandNames(self):
3404     # FIXME: in the future maybe other cluster params won't require checking on
3405     # all nodes to be modified.
3406     self.needed_locks = {
3407       locking.LEVEL_NODE: locking.ALL_SET,
3408     }
3409     self.share_locks[locking.LEVEL_NODE] = 1
3410
3411   def BuildHooksEnv(self):
3412     """Build hooks env.
3413
3414     """
3415     return {
3416       "OP_TARGET": self.cfg.GetClusterName(),
3417       "NEW_VG_NAME": self.op.vg_name,
3418       }
3419
3420   def BuildHooksNodes(self):
3421     """Build hooks nodes.
3422
3423     """
3424     mn = self.cfg.GetMasterNode()
3425     return ([mn], [mn])
3426
3427   def CheckPrereq(self):
3428     """Check prerequisites.
3429
3430     This checks whether the given params don't conflict and
3431     if the given volume group is valid.
3432
3433     """
3434     if self.op.vg_name is not None and not self.op.vg_name:
3435       if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3436         raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3437                                    " instances exist", errors.ECODE_INVAL)
3438
3439     if self.op.drbd_helper is not None and not self.op.drbd_helper:
3440       if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3441         raise errors.OpPrereqError("Cannot disable drbd helper while"
3442                                    " drbd-based instances exist",
3443                                    errors.ECODE_INVAL)
3444
3445     node_list = self.owned_locks(locking.LEVEL_NODE)
3446
3447     # if vg_name not None, checks given volume group on all nodes
3448     if self.op.vg_name:
3449       vglist = self.rpc.call_vg_list(node_list)
3450       for node in node_list:
3451         msg = vglist[node].fail_msg
3452         if msg:
3453           # ignoring down node
3454           self.LogWarning("Error while gathering data on node %s"
3455                           " (ignoring node): %s", node, msg)
3456           continue
3457         vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3458                                               self.op.vg_name,
3459                                               constants.MIN_VG_SIZE)
3460         if vgstatus:
3461           raise errors.OpPrereqError("Error on node '%s': %s" %
3462                                      (node, vgstatus), errors.ECODE_ENVIRON)
3463
3464     if self.op.drbd_helper:
3465       # checks given drbd helper on all nodes
3466       helpers = self.rpc.call_drbd_helper(node_list)
3467       for (node, ninfo) in self.cfg.GetMultiNodeInfo(node_list):
3468         if ninfo.offline:
3469           self.LogInfo("Not checking drbd helper on offline node %s", node)
3470           continue
3471         msg = helpers[node].fail_msg
3472         if msg:
3473           raise errors.OpPrereqError("Error checking drbd helper on node"
3474                                      " '%s': %s" % (node, msg),
3475                                      errors.ECODE_ENVIRON)
3476         node_helper = helpers[node].payload
3477         if node_helper != self.op.drbd_helper:
3478           raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3479                                      (node, node_helper), errors.ECODE_ENVIRON)
3480
3481     self.cluster = cluster = self.cfg.GetClusterInfo()
3482     # validate params changes
3483     if self.op.beparams:
3484       utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3485       self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3486
3487     if self.op.ndparams:
3488       utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3489       self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3490
3491       # TODO: we need a more general way to handle resetting
3492       # cluster-level parameters to default values
3493       if self.new_ndparams["oob_program"] == "":
3494         self.new_ndparams["oob_program"] = \
3495             constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3496
3497     if self.op.nicparams:
3498       utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3499       self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3500       objects.NIC.CheckParameterSyntax(self.new_nicparams)
3501       nic_errors = []
3502
3503       # check all instances for consistency
3504       for instance in self.cfg.GetAllInstancesInfo().values():
3505         for nic_idx, nic in enumerate(instance.nics):
3506           params_copy = copy.deepcopy(nic.nicparams)
3507           params_filled = objects.FillDict(self.new_nicparams, params_copy)
3508
3509           # check parameter syntax
3510           try:
3511             objects.NIC.CheckParameterSyntax(params_filled)
3512           except errors.ConfigurationError, err:
3513             nic_errors.append("Instance %s, nic/%d: %s" %
3514                               (instance.name, nic_idx, err))
3515
3516           # if we're moving instances to routed, check that they have an ip
3517           target_mode = params_filled[constants.NIC_MODE]
3518           if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3519             nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3520                               " address" % (instance.name, nic_idx))
3521       if nic_errors:
3522         raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3523                                    "\n".join(nic_errors))
3524
3525     # hypervisor list/parameters
3526     self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3527     if self.op.hvparams:
3528       for hv_name, hv_dict in self.op.hvparams.items():
3529         if hv_name not in self.new_hvparams:
3530           self.new_hvparams[hv_name] = hv_dict
3531         else:
3532           self.new_hvparams[hv_name].update(hv_dict)
3533
3534     # os hypervisor parameters
3535     self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3536     if self.op.os_hvp:
3537       for os_name, hvs in self.op.os_hvp.items():
3538         if os_name not in self.new_os_hvp:
3539           self.new_os_hvp[os_name] = hvs
3540         else:
3541           for hv_name, hv_dict in hvs.items():
3542             if hv_name not in self.new_os_hvp[os_name]:
3543               self.new_os_hvp[os_name][hv_name] = hv_dict
3544             else:
3545               self.new_os_hvp[os_name][hv_name].update(hv_dict)
3546
3547     # os parameters
3548     self.new_osp = objects.FillDict(cluster.osparams, {})
3549     if self.op.osparams:
3550       for os_name, osp in self.op.osparams.items():
3551         if os_name not in self.new_osp:
3552           self.new_osp[os_name] = {}
3553
3554         self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3555                                                   use_none=True)
3556
3557         if not self.new_osp[os_name]:
3558           # we removed all parameters
3559           del self.new_osp[os_name]
3560         else:
3561           # check the parameter validity (remote check)
3562           _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3563                          os_name, self.new_osp[os_name])
3564
3565     # changes to the hypervisor list
3566     if self.op.enabled_hypervisors is not None:
3567       self.hv_list = self.op.enabled_hypervisors
3568       for hv in self.hv_list:
3569         # if the hypervisor doesn't already exist in the cluster
3570         # hvparams, we initialize it to empty, and then (in both
3571         # cases) we make sure to fill the defaults, as we might not
3572         # have a complete defaults list if the hypervisor wasn't
3573         # enabled before
3574         if hv not in new_hvp:
3575           new_hvp[hv] = {}
3576         new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3577         utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3578     else:
3579       self.hv_list = cluster.enabled_hypervisors
3580
3581     if self.op.hvparams or self.op.enabled_hypervisors is not None:
3582       # either the enabled list has changed, or the parameters have, validate
3583       for hv_name, hv_params in self.new_hvparams.items():
3584         if ((self.op.hvparams and hv_name in self.op.hvparams) or
3585             (self.op.enabled_hypervisors and
3586              hv_name in self.op.enabled_hypervisors)):
3587           # either this is a new hypervisor, or its parameters have changed
3588           hv_class = hypervisor.GetHypervisor(hv_name)
3589           utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3590           hv_class.CheckParameterSyntax(hv_params)
3591           _CheckHVParams(self, node_list, hv_name, hv_params)
3592
3593     if self.op.os_hvp:
3594       # no need to check any newly-enabled hypervisors, since the
3595       # defaults have already been checked in the above code-block
3596       for os_name, os_hvp in self.new_os_hvp.items():
3597         for hv_name, hv_params in os_hvp.items():
3598           utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3599           # we need to fill in the new os_hvp on top of the actual hv_p
3600           cluster_defaults = self.new_hvparams.get(hv_name, {})
3601           new_osp = objects.FillDict(cluster_defaults, hv_params)
3602           hv_class = hypervisor.GetHypervisor(hv_name)
3603           hv_class.CheckParameterSyntax(new_osp)
3604           _CheckHVParams(self, node_list, hv_name, new_osp)
3605
3606     if self.op.default_iallocator:
3607       alloc_script = utils.FindFile(self.op.default_iallocator,
3608                                     constants.IALLOCATOR_SEARCH_PATH,
3609                                     os.path.isfile)
3610       if alloc_script is None:
3611         raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3612                                    " specified" % self.op.default_iallocator,
3613                                    errors.ECODE_INVAL)
3614
3615   def Exec(self, feedback_fn):
3616     """Change the parameters of the cluster.
3617
3618     """
3619     if self.op.vg_name is not None:
3620       new_volume = self.op.vg_name
3621       if not new_volume:
3622         new_volume = None
3623       if new_volume != self.cfg.GetVGName():
3624         self.cfg.SetVGName(new_volume)
3625       else:
3626         feedback_fn("Cluster LVM configuration already in desired"
3627                     " state, not changing")
3628     if self.op.drbd_helper is not None:
3629       new_helper = self.op.drbd_helper
3630       if not new_helper:
3631         new_helper = None
3632       if new_helper != self.cfg.GetDRBDHelper():
3633         self.cfg.SetDRBDHelper(new_helper)
3634       else:
3635         feedback_fn("Cluster DRBD helper already in desired state,"
3636                     " not changing")
3637     if self.op.hvparams:
3638       self.cluster.hvparams = self.new_hvparams
3639     if self.op.os_hvp:
3640       self.cluster.os_hvp = self.new_os_hvp
3641     if self.op.enabled_hypervisors is not None:
3642       self.cluster.hvparams = self.new_hvparams
3643       self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3644     if self.op.beparams:
3645       self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3646     if self.op.nicparams:
3647       self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3648     if self.op.osparams:
3649       self.cluster.osparams = self.new_osp
3650     if self.op.ndparams:
3651       self.cluster.ndparams = self.new_ndparams
3652
3653     if self.op.candidate_pool_size is not None:
3654       self.cluster.candidate_pool_size = self.op.candidate_pool_size
3655       # we need to update the pool size here, otherwise the save will fail
3656       _AdjustCandidatePool(self, [])
3657
3658     if self.op.maintain_node_health is not None:
3659       self.cluster.maintain_node_health = self.op.maintain_node_health
3660
3661     if self.op.prealloc_wipe_disks is not None:
3662       self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3663
3664     if self.op.add_uids is not None:
3665       uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3666
3667     if self.op.remove_uids is not None:
3668       uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3669
3670     if self.op.uid_pool is not None:
3671       self.cluster.uid_pool = self.op.uid_pool
3672
3673     if self.op.default_iallocator is not None:
3674       self.cluster.default_iallocator = self.op.default_iallocator
3675
3676     if self.op.reserved_lvs is not None:
3677       self.cluster.reserved_lvs = self.op.reserved_lvs
3678
3679     def helper_os(aname, mods, desc):
3680       desc += " OS list"
3681       lst = getattr(self.cluster, aname)
3682       for key, val in mods:
3683         if key == constants.DDM_ADD:
3684           if val in lst:
3685             feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3686           else:
3687             lst.append(val)
3688         elif key == constants.DDM_REMOVE:
3689           if val in lst:
3690             lst.remove(val)
3691           else:
3692             feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3693         else:
3694           raise errors.ProgrammerError("Invalid modification '%s'" % key)
3695
3696     if self.op.hidden_os:
3697       helper_os("hidden_os", self.op.hidden_os, "hidden")
3698
3699     if self.op.blacklisted_os:
3700       helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3701
3702     if self.op.master_netdev:
3703       master = self.cfg.GetMasterNode()
3704       feedback_fn("Shutting down master ip on the current netdev (%s)" %
3705                   self.cluster.master_netdev)
3706       result = self.rpc.call_node_stop_master(master, False)
3707       result.Raise("Could not disable the master ip")
3708       feedback_fn("Changing master_netdev from %s to %s" %
3709                   (self.cluster.master_netdev, self.op.master_netdev))
3710       self.cluster.master_netdev = self.op.master_netdev
3711
3712     self.cfg.Update(self.cluster, feedback_fn)
3713
3714     if self.op.master_netdev:
3715       feedback_fn("Starting the master ip on the new master netdev (%s)" %
3716                   self.op.master_netdev)
3717       result = self.rpc.call_node_start_master(master, False, False)
3718       if result.fail_msg:
3719         self.LogWarning("Could not re-enable the master ip on"
3720                         " the master, please restart manually: %s",
3721                         result.fail_msg)
3722
3723
3724 def _UploadHelper(lu, nodes, fname):
3725   """Helper for uploading a file and showing warnings.
3726
3727   """
3728   if os.path.exists(fname):
3729     result = lu.rpc.call_upload_file(nodes, fname)
3730     for to_node, to_result in result.items():
3731       msg = to_result.fail_msg
3732       if msg:
3733         msg = ("Copy of file %s to node %s failed: %s" %
3734                (fname, to_node, msg))
3735         lu.proc.LogWarning(msg)
3736
3737
3738 def _ComputeAncillaryFiles(cluster, redist):
3739   """Compute files external to Ganeti which need to be consistent.
3740
3741   @type redist: boolean
3742   @param redist: Whether to include files which need to be redistributed
3743
3744   """
3745   # Compute files for all nodes
3746   files_all = set([
3747     constants.SSH_KNOWN_HOSTS_FILE,
3748     constants.CONFD_HMAC_KEY,
3749     constants.CLUSTER_DOMAIN_SECRET_FILE,
3750     ])
3751
3752   if not redist:
3753     files_all.update(constants.ALL_CERT_FILES)
3754     files_all.update(ssconf.SimpleStore().GetFileList())
3755   else:
3756     # we need to ship at least the RAPI certificate
3757     files_all.add(constants.RAPI_CERT_FILE)
3758
3759   if cluster.modify_etc_hosts:
3760     files_all.add(constants.ETC_HOSTS)
3761
3762   # Files which must either exist on all nodes or on none
3763   files_all_opt = set([
3764     constants.RAPI_USERS_FILE,
3765     ])
3766
3767   # Files which should only be on master candidates
3768   files_mc = set()
3769   if not redist:
3770     files_mc.add(constants.CLUSTER_CONF_FILE)
3771
3772   # Files which should only be on VM-capable nodes
3773   files_vm = set(filename
3774     for hv_name in cluster.enabled_hypervisors
3775     for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3776
3777   # Filenames must be unique
3778   assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3779           sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3780          "Found file listed in more than one file list"
3781
3782   return (files_all, files_all_opt, files_mc, files_vm)
3783
3784
3785 def _RedistributeAncillaryFiles(lu, additional_nodes=None, additional_vm=True):
3786   """Distribute additional files which are part of the cluster configuration.
3787
3788   ConfigWriter takes care of distributing the config and ssconf files, but
3789   there are more files which should be distributed to all nodes. This function
3790   makes sure those are copied.
3791
3792   @param lu: calling logical unit
3793   @param additional_nodes: list of nodes not in the config to distribute to
3794   @type additional_vm: boolean
3795   @param additional_vm: whether the additional nodes are vm-capable or not
3796
3797   """
3798   # Gather target nodes
3799   cluster = lu.cfg.GetClusterInfo()
3800   master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3801
3802   online_nodes = lu.cfg.GetOnlineNodeList()
3803   vm_nodes = lu.cfg.GetVmCapableNodeList()
3804
3805   if additional_nodes is not None:
3806     online_nodes.extend(additional_nodes)
3807     if additional_vm:
3808       vm_nodes.extend(additional_nodes)
3809
3810   # Never distribute to master node
3811   for nodelist in [online_nodes, vm_nodes]:
3812     if master_info.name in nodelist:
3813       nodelist.remove(master_info.name)
3814
3815   # Gather file lists
3816   (files_all, files_all_opt, files_mc, files_vm) = \
3817     _ComputeAncillaryFiles(cluster, True)
3818
3819   # Never re-distribute configuration file from here
3820   assert not (constants.CLUSTER_CONF_FILE in files_all or
3821               constants.CLUSTER_CONF_FILE in files_vm)
3822   assert not files_mc, "Master candidates not handled in this function"
3823
3824   filemap = [
3825     (online_nodes, files_all),
3826     (online_nodes, files_all_opt),
3827     (vm_nodes, files_vm),
3828     ]
3829
3830   # Upload the files
3831   for (node_list, files) in filemap:
3832     for fname in files:
3833       _UploadHelper(lu, node_list, fname)
3834
3835
3836 class LUClusterRedistConf(NoHooksLU):
3837   """Force the redistribution of cluster configuration.
3838
3839   This is a very simple LU.
3840
3841   """
3842   REQ_BGL = False
3843
3844   def ExpandNames(self):
3845     self.needed_locks = {
3846       locking.LEVEL_NODE: locking.ALL_SET,
3847     }
3848     self.share_locks[locking.LEVEL_NODE] = 1
3849
3850   def Exec(self, feedback_fn):
3851     """Redistribute the configuration.
3852
3853     """
3854     self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3855     _RedistributeAncillaryFiles(self)
3856
3857
3858 def _WaitForSync(lu, instance, disks=None, oneshot=False):
3859   """Sleep and poll for an instance's disk to sync.
3860
3861   """
3862   if not instance.disks or disks is not None and not disks:
3863     return True
3864
3865   disks = _ExpandCheckDisks(instance, disks)
3866
3867   if not oneshot:
3868     lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3869
3870   node = instance.primary_node
3871
3872   for dev in disks:
3873     lu.cfg.SetDiskID(dev, node)
3874
3875   # TODO: Convert to utils.Retry
3876
3877   retries = 0
3878   degr_retries = 10 # in seconds, as we sleep 1 second each time
3879   while True:
3880     max_time = 0
3881     done = True
3882     cumul_degraded = False
3883     rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3884     msg = rstats.fail_msg
3885     if msg:
3886       lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3887       retries += 1
3888       if retries >= 10:
3889         raise errors.RemoteError("Can't contact node %s for mirror data,"
3890                                  " aborting." % node)
3891       time.sleep(6)
3892       continue
3893     rstats = rstats.payload
3894     retries = 0
3895     for i, mstat in enumerate(rstats):
3896       if mstat is None:
3897         lu.LogWarning("Can't compute data for node %s/%s",
3898                            node, disks[i].iv_name)
3899         continue
3900
3901       cumul_degraded = (cumul_degraded or
3902                         (mstat.is_degraded and mstat.sync_percent is None))
3903       if mstat.sync_percent is not None:
3904         done = False
3905         if mstat.estimated_time is not None:
3906           rem_time = ("%s remaining (estimated)" %
3907                       utils.FormatSeconds(mstat.estimated_time))
3908           max_time = mstat.estimated_time
3909         else:
3910           rem_time = "no time estimate"
3911         lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3912                         (disks[i].iv_name, mstat.sync_percent, rem_time))
3913
3914     # if we're done but degraded, let's do a few small retries, to
3915     # make sure we see a stable and not transient situation; therefore
3916     # we force restart of the loop
3917     if (done or oneshot) and cumul_degraded and degr_retries > 0:
3918       logging.info("Degraded disks found, %d retries left", degr_retries)
3919       degr_retries -= 1
3920       time.sleep(1)
3921       continue
3922
3923     if done or oneshot:
3924       break
3925
3926     time.sleep(min(60, max_time))
3927
3928   if done:
3929     lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3930   return not cumul_degraded
3931
3932
3933 def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3934   """Check that mirrors are not degraded.
3935
3936   The ldisk parameter, if True, will change the test from the
3937   is_degraded attribute (which represents overall non-ok status for
3938   the device(s)) to the ldisk (representing the local storage status).
3939
3940   """
3941   lu.cfg.SetDiskID(dev, node)
3942
3943   result = True
3944
3945   if on_primary or dev.AssembleOnSecondary():
3946     rstats = lu.rpc.call_blockdev_find(node, dev)
3947     msg = rstats.fail_msg
3948     if msg:
3949       lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3950       result = False
3951     elif not rstats.payload:
3952       lu.LogWarning("Can't find disk on node %s", node)
3953       result = False
3954     else:
3955       if ldisk:
3956         result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3957       else:
3958         result = result and not rstats.payload.is_degraded
3959
3960   if dev.children:
3961     for child in dev.children:
3962       result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3963
3964   return result
3965
3966
3967 class LUOobCommand(NoHooksLU):
3968   """Logical unit for OOB handling.
3969
3970   """
3971   REG_BGL = False
3972   _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3973
3974   def ExpandNames(self):
3975     """Gather locks we need.
3976
3977     """
3978     if self.op.node_names:
3979       self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3980       lock_names = self.op.node_names
3981     else:
3982       lock_names = locking.ALL_SET
3983
3984     self.needed_locks = {
3985       locking.LEVEL_NODE: lock_names,
3986       }
3987
3988   def CheckPrereq(self):
3989     """Check prerequisites.
3990
3991     This checks:
3992      - the node exists in the configuration
3993      - OOB is supported
3994
3995     Any errors are signaled by raising errors.OpPrereqError.
3996
3997     """
3998     self.nodes = []
3999     self.master_node = self.cfg.GetMasterNode()
4000
4001     assert self.op.power_delay >= 0.0
4002
4003     if self.op.node_names:
4004       if (self.op.command in self._SKIP_MASTER and
4005           self.master_node in self.op.node_names):
4006         master_node_obj = self.cfg.GetNodeInfo(self.master_node)
4007         master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
4008
4009         if master_oob_handler:
4010           additional_text = ("run '%s %s %s' if you want to operate on the"
4011                              " master regardless") % (master_oob_handler,
4012                                                       self.op.command,
4013                                                       self.master_node)
4014         else:
4015           additional_text = "it does not support out-of-band operations"
4016
4017         raise errors.OpPrereqError(("Operating on the master node %s is not"
4018                                     " allowed for %s; %s") %
4019                                    (self.master_node, self.op.command,
4020                                     additional_text), errors.ECODE_INVAL)
4021     else:
4022       self.op.node_names = self.cfg.GetNodeList()
4023       if self.op.command in self._SKIP_MASTER:
4024         self.op.node_names.remove(self.master_node)
4025
4026     if self.op.command in self._SKIP_MASTER:
4027       assert self.master_node not in self.op.node_names
4028
4029     for (node_name, node) in self.cfg.GetMultiNodeInfo(self.op.node_names):
4030       if node is None:
4031         raise errors.OpPrereqError("Node %s not found" % node_name,
4032                                    errors.ECODE_NOENT)
4033       else:
4034         self.nodes.append(node)
4035
4036       if (not self.op.ignore_status and
4037           (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
4038         raise errors.OpPrereqError(("Cannot power off node %s because it is"
4039                                     " not marked offline") % node_name,
4040                                    errors.ECODE_STATE)
4041
4042   def Exec(self, feedback_fn):
4043     """Execute OOB and return result if we expect any.
4044
4045     """
4046     master_node = self.master_node
4047     ret = []
4048
4049     for idx, node in enumerate(utils.NiceSort(self.nodes,
4050                                               key=lambda node: node.name)):
4051       node_entry = [(constants.RS_NORMAL, node.name)]
4052       ret.append(node_entry)
4053
4054       oob_program = _SupportsOob(self.cfg, node)
4055
4056       if not oob_program:
4057         node_entry.append((constants.RS_UNAVAIL, None))
4058         continue
4059
4060       logging.info("Executing out-of-band command '%s' using '%s' on %s",
4061                    self.op.command, oob_program, node.name)
4062       result = self.rpc.call_run_oob(master_node, oob_program,
4063                                      self.op.command, node.name,
4064                                      self.op.timeout)
4065
4066       if result.fail_msg:
4067         self.LogWarning("Out-of-band RPC failed on node '%s': %s",
4068                         node.name, result.fail_msg)
4069         node_entry.append((constants.RS_NODATA, None))
4070       else:
4071         try:
4072           self._CheckPayload(result)
4073         except errors.OpExecError, err:
4074           self.LogWarning("Payload returned by node '%s' is not valid: %s",
4075                           node.name, err)
4076           node_entry.append((constants.RS_NODATA, None))
4077         else:
4078           if self.op.command == constants.OOB_HEALTH:
4079             # For health we should log important events
4080             for item, status in result.payload:
4081               if status in [constants.OOB_STATUS_WARNING,
4082                             constants.OOB_STATUS_CRITICAL]:
4083                 self.LogWarning("Item '%s' on node '%s' has status '%s'",
4084                                 item, node.name, status)
4085
4086           if self.op.command == constants.OOB_POWER_ON:
4087             node.powered = True
4088           elif self.op.command == constants.OOB_POWER_OFF:
4089             node.powered = False
4090           elif self.op.command == constants.OOB_POWER_STATUS:
4091             powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
4092             if powered != node.powered:
4093               logging.warning(("Recorded power state (%s) of node '%s' does not"
4094                                " match actual power state (%s)"), node.powered,
4095                               node.name, powered)
4096
4097           # For configuration changing commands we should update the node
4098           if self.op.command in (constants.OOB_POWER_ON,
4099                                  constants.OOB_POWER_OFF):
4100             self.cfg.Update(node, feedback_fn)
4101
4102           node_entry.append((constants.RS_NORMAL, result.payload))
4103
4104           if (self.op.command == constants.OOB_POWER_ON and
4105               idx < len(self.nodes) - 1):
4106             time.sleep(self.op.power_delay)
4107
4108     return ret
4109
4110   def _CheckPayload(self, result):
4111     """Checks if the payload is valid.
4112
4113     @param result: RPC result
4114     @raises errors.OpExecError: If payload is not valid
4115
4116     """
4117     errs = []
4118     if self.op.command == constants.OOB_HEALTH:
4119       if not isinstance(result.payload, list):
4120         errs.append("command 'health' is expected to return a list but got %s" %
4121                     type(result.payload))
4122       else:
4123         for item, status in result.payload:
4124           if status not in constants.OOB_STATUSES:
4125             errs.append("health item '%s' has invalid status '%s'" %
4126                         (item, status))
4127
4128     if self.op.command == constants.OOB_POWER_STATUS:
4129       if not isinstance(result.payload, dict):
4130         errs.append("power-status is expected to return a dict but got %s" %
4131                     type(result.payload))
4132
4133     if self.op.command in [
4134         constants.OOB_POWER_ON,
4135         constants.OOB_POWER_OFF,
4136         constants.OOB_POWER_CYCLE,
4137         ]:
4138       if result.payload is not None:
4139         errs.append("%s is expected to not return payload but got '%s'" %
4140                     (self.op.command, result.payload))
4141
4142     if errs:
4143       raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
4144                                utils.CommaJoin(errs))
4145
4146
4147 class _OsQuery(_QueryBase):
4148   FIELDS = query.OS_FIELDS
4149
4150   def ExpandNames(self, lu):
4151     # Lock all nodes in shared mode
4152     # Temporary removal of locks, should be reverted later
4153     # TODO: reintroduce locks when they are lighter-weight
4154     lu.needed_locks = {}
4155     #self.share_locks[locking.LEVEL_NODE] = 1
4156     #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4157
4158     # The following variables interact with _QueryBase._GetNames
4159     if self.names:
4160       self.wanted = self.names
4161     else:
4162       self.wanted = locking.ALL_SET
4163
4164     self.do_locking = self.use_locking
4165
4166   def DeclareLocks(self, lu, level):
4167     pass
4168
4169   @staticmethod
4170   def _DiagnoseByOS(rlist):
4171     """Remaps a per-node return list into an a per-os per-node dictionary
4172
4173     @param rlist: a map with node names as keys and OS objects as values
4174
4175     @rtype: dict
4176     @return: a dictionary with osnames as keys and as value another
4177         map, with nodes as keys and tuples of (path, status, diagnose,
4178         variants, parameters, api_versions) as values, eg::
4179
4180           {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
4181                                      (/srv/..., False, "invalid api")],
4182                            "node2": [(/srv/..., True, "", [], [])]}
4183           }
4184
4185     """
4186     all_os = {}
4187     # we build here the list of nodes that didn't fail the RPC (at RPC
4188     # level), so that nodes with a non-responding node daemon don't
4189     # make all OSes invalid
4190     good_nodes = [node_name for node_name in rlist
4191                   if not rlist[node_name].fail_msg]
4192     for node_name, nr in rlist.items():
4193       if nr.fail_msg or not nr.payload:
4194         continue
4195       for (name, path, status, diagnose, variants,
4196            params, api_versions) in nr.payload:
4197         if name not in all_os:
4198           # build a list of nodes for this os containing empty lists
4199           # for each node in node_list
4200           all_os[name] = {}
4201           for nname in good_nodes:
4202             all_os[name][nname] = []
4203         # convert params from [name, help] to (name, help)
4204         params = [tuple(v) for v in params]
4205         all_os[name][node_name].append((path, status, diagnose,
4206                                         variants, params, api_versions))
4207     return all_os
4208
4209   def _GetQueryData(self, lu):
4210     """Computes the list of nodes and their attributes.
4211
4212     """
4213     # Locking is not used
4214     assert not (compat.any(lu.glm.is_owned(level)
4215                            for level in locking.LEVELS
4216                            if level != locking.LEVEL_CLUSTER) or
4217                 self.do_locking or self.use_locking)
4218
4219     valid_nodes = [node.name
4220                    for node in lu.cfg.GetAllNodesInfo().values()
4221                    if not node.offline and node.vm_capable]
4222     pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
4223     cluster = lu.cfg.GetClusterInfo()
4224
4225     data = {}
4226
4227     for (os_name, os_data) in pol.items():
4228       info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
4229                           hidden=(os_name in cluster.hidden_os),
4230                           blacklisted=(os_name in cluster.blacklisted_os))
4231
4232       variants = set()
4233       parameters = set()
4234       api_versions = set()
4235
4236       for idx, osl in enumerate(os_data.values()):
4237         info.valid = bool(info.valid and osl and osl[0][1])
4238         if not info.valid:
4239           break
4240
4241         (node_variants, node_params, node_api) = osl[0][3:6]
4242         if idx == 0:
4243           # First entry
4244           variants.update(node_variants)
4245           parameters.update(node_params)
4246           api_versions.update(node_api)
4247         else:
4248           # Filter out inconsistent values
4249           variants.intersection_update(node_variants)
4250           parameters.intersection_update(node_params)
4251           api_versions.intersection_update(node_api)
4252
4253       info.variants = list(variants)
4254       info.parameters = list(parameters)
4255       info.api_versions = list(api_versions)
4256
4257       data[os_name] = info
4258
4259     # Prepare data in requested order
4260     return [data[name] for name in self._GetNames(lu, pol.keys(), None)
4261             if name in data]
4262
4263
4264 class LUOsDiagnose(NoHooksLU):
4265   """Logical unit for OS diagnose/query.
4266
4267   """
4268   REQ_BGL = False
4269
4270   @staticmethod
4271   def _BuildFilter(fields, names):
4272     """Builds a filter for querying OSes.
4273
4274     """
4275     name_filter = qlang.MakeSimpleFilter("name", names)
4276
4277     # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
4278     # respective field is not requested
4279     status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
4280                      for fname in ["hidden", "blacklisted"]
4281                      if fname not in fields]
4282     if "valid" not in fields:
4283       status_filter.append([qlang.OP_TRUE, "valid"])
4284
4285     if status_filter:
4286       status_filter.insert(0, qlang.OP_AND)
4287     else:
4288       status_filter = None
4289
4290     if name_filter and status_filter:
4291       return [qlang.OP_AND, name_filter, status_filter]
4292     elif name_filter:
4293       return name_filter
4294     else:
4295       return status_filter
4296
4297   def CheckArguments(self):
4298     self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
4299                        self.op.output_fields, False)
4300
4301   def ExpandNames(self):
4302     self.oq.ExpandNames(self)
4303
4304   def Exec(self, feedback_fn):
4305     return self.oq.OldStyleQuery(self)
4306
4307
4308 class LUNodeRemove(LogicalUnit):
4309   """Logical unit for removing a node.
4310
4311   """
4312   HPATH = "node-remove"
4313   HTYPE = constants.HTYPE_NODE
4314
4315   def BuildHooksEnv(self):
4316     """Build hooks env.
4317
4318     This doesn't run on the target node in the pre phase as a failed
4319     node would then be impossible to remove.
4320
4321     """
4322     return {
4323       "OP_TARGET": self.op.node_name,
4324       "NODE_NAME": self.op.node_name,
4325       }
4326
4327   def BuildHooksNodes(self):
4328     """Build hooks nodes.
4329
4330     """
4331     all_nodes = self.cfg.GetNodeList()
4332     try:
4333       all_nodes.remove(self.op.node_name)
4334     except ValueError:
4335       logging.warning("Node '%s', which is about to be removed, was not found"
4336                       " in the list of all nodes", self.op.node_name)
4337     return (all_nodes, all_nodes)
4338
4339   def CheckPrereq(self):
4340     """Check prerequisites.
4341
4342     This checks:
4343      - the node exists in the configuration
4344      - it does not have primary or secondary instances
4345      - it's not the master
4346
4347     Any errors are signaled by raising errors.OpPrereqError.
4348
4349     """
4350     self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4351     node = self.cfg.GetNodeInfo(self.op.node_name)
4352     assert node is not None
4353
4354     masternode = self.cfg.GetMasterNode()
4355     if node.name == masternode:
4356       raise errors.OpPrereqError("Node is the master node, failover to another"
4357                                  " node is required", errors.ECODE_INVAL)
4358
4359     for instance_name, instance in self.cfg.GetAllInstancesInfo().items():
4360       if node.name in instance.all_nodes:
4361         raise errors.OpPrereqError("Instance %s is still running on the node,"
4362                                    " please remove first" % instance_name,
4363                                    errors.ECODE_INVAL)
4364     self.op.node_name = node.name
4365     self.node = node
4366
4367   def Exec(self, feedback_fn):
4368     """Removes the node from the cluster.
4369
4370     """
4371     node = self.node
4372     logging.info("Stopping the node daemon and removing configs from node %s",
4373                  node.name)
4374
4375     modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
4376
4377     # Promote nodes to master candidate as needed
4378     _AdjustCandidatePool(self, exceptions=[node.name])
4379     self.context.RemoveNode(node.name)
4380
4381     # Run post hooks on the node before it's removed
4382     _RunPostHook(self, node.name)
4383
4384     result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
4385     msg = result.fail_msg
4386     if msg:
4387       self.LogWarning("Errors encountered on the remote node while leaving"
4388                       " the cluster: %s", msg)
4389
4390     # Remove node from our /etc/hosts
4391     if self.cfg.GetClusterInfo().modify_etc_hosts:
4392       master_node = self.cfg.GetMasterNode()
4393       result = self.rpc.call_etc_hosts_modify(master_node,
4394                                               constants.ETC_HOSTS_REMOVE,
4395                                               node.name, None)
4396       result.Raise("Can't update hosts file with new host data")
4397       _RedistributeAncillaryFiles(self)
4398
4399
4400 class _NodeQuery(_QueryBase):
4401   FIELDS = query.NODE_FIELDS
4402
4403   def ExpandNames(self, lu):
4404     lu.needed_locks = {}
4405     lu.share_locks = _ShareAll()
4406
4407     if self.names:
4408       self.wanted = _GetWantedNodes(lu, self.names)
4409     else:
4410       self.wanted = locking.ALL_SET
4411
4412     self.do_locking = (self.use_locking and
4413                        query.NQ_LIVE in self.requested_data)
4414
4415     if self.do_locking:
4416       # If any non-static field is requested we need to lock the nodes
4417       lu.needed_locks[locking.LEVEL_NODE] = self.wanted
4418
4419   def DeclareLocks(self, lu, level):
4420     pass
4421
4422   def _GetQueryData(self, lu):
4423     """Computes the list of nodes and their attributes.
4424
4425     """
4426     all_info = lu.cfg.GetAllNodesInfo()
4427
4428     nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
4429
4430     # Gather data as requested
4431     if query.NQ_LIVE in self.requested_data:
4432       # filter out non-vm_capable nodes
4433       toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
4434
4435       node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
4436                                         lu.cfg.GetHypervisorType())
4437       live_data = dict((name, nresult.payload)
4438                        for (name, nresult) in node_data.items()
4439                        if not nresult.fail_msg and nresult.payload)
4440     else:
4441       live_data = None
4442
4443     if query.NQ_INST in self.requested_data:
4444       node_to_primary = dict([(name, set()) for name in nodenames])
4445       node_to_secondary = dict([(name, set()) for name in nodenames])
4446
4447       inst_data = lu.cfg.GetAllInstancesInfo()
4448
4449       for inst in inst_data.values():
4450         if inst.primary_node in node_to_primary:
4451           node_to_primary[inst.primary_node].add(inst.name)
4452         for secnode in inst.secondary_nodes:
4453           if secnode in node_to_secondary:
4454             node_to_secondary[secnode].add(inst.name)
4455     else:
4456       node_to_primary = None
4457       node_to_secondary = None
4458
4459     if query.NQ_OOB in self.requested_data:
4460       oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
4461                          for name, node in all_info.iteritems())
4462     else:
4463       oob_support = None
4464
4465     if query.NQ_GROUP in self.requested_data:
4466       groups = lu.cfg.GetAllNodeGroupsInfo()
4467     else:
4468       groups = {}
4469
4470     return query.NodeQueryData([all_info[name] for name in nodenames],
4471                                live_data, lu.cfg.GetMasterNode(),
4472                                node_to_primary, node_to_secondary, groups,
4473                                oob_support, lu.cfg.GetClusterInfo())
4474
4475
4476 class LUNodeQuery(NoHooksLU):
4477   """Logical unit for querying nodes.
4478
4479   """
4480   # pylint: disable=W0142
4481   REQ_BGL = False
4482
4483   def CheckArguments(self):
4484     self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4485                          self.op.output_fields, self.op.use_locking)
4486
4487   def ExpandNames(self):
4488     self.nq.ExpandNames(self)
4489
4490   def Exec(self, feedback_fn):
4491     return self.nq.OldStyleQuery(self)
4492
4493
4494 class LUNodeQueryvols(NoHooksLU):
4495   """Logical unit for getting volumes on node(s).
4496
4497   """
4498   REQ_BGL = False
4499   _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4500   _FIELDS_STATIC = utils.FieldSet("node")
4501
4502   def CheckArguments(self):
4503     _CheckOutputFields(static=self._FIELDS_STATIC,
4504                        dynamic=self._FIELDS_DYNAMIC,
4505                        selected=self.op.output_fields)
4506
4507   def ExpandNames(self):
4508     self.needed_locks = {}
4509     self.share_locks[locking.LEVEL_NODE] = 1
4510     if not self.op.nodes:
4511       self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4512     else:
4513       self.needed_locks[locking.LEVEL_NODE] = \
4514         _GetWantedNodes(self, self.op.nodes)
4515
4516   def Exec(self, feedback_fn):
4517     """Computes the list of nodes and their attributes.
4518
4519     """
4520     nodenames = self.owned_locks(locking.LEVEL_NODE)
4521     volumes = self.rpc.call_node_volumes(nodenames)
4522
4523     ilist = self.cfg.GetAllInstancesInfo()
4524     vol2inst = _MapInstanceDisksToNodes(ilist.values())
4525
4526     output = []
4527     for node in nodenames:
4528       nresult = volumes[node]
4529       if nresult.offline:
4530         continue
4531       msg = nresult.fail_msg
4532       if msg:
4533         self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4534         continue
4535
4536       node_vols = sorted(nresult.payload,
4537                          key=operator.itemgetter("dev"))
4538
4539       for vol in node_vols:
4540         node_output = []
4541         for field in self.op.output_fields:
4542           if field == "node":
4543             val = node
4544           elif field == "phys":
4545             val = vol["dev"]
4546           elif field == "vg":
4547             val = vol["vg"]
4548           elif field == "name":
4549             val = vol["name"]
4550           elif field == "size":
4551             val = int(float(vol["size"]))
4552           elif field == "instance":
4553             val = vol2inst.get((node, vol["vg"] + "/" + vol["name"]), "-")
4554           else:
4555             raise errors.ParameterError(field)
4556           node_output.append(str(val))
4557
4558         output.append(node_output)
4559
4560     return output
4561
4562
4563 class LUNodeQueryStorage(NoHooksLU):
4564   """Logical unit for getting information on storage units on node(s).
4565
4566   """
4567   _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4568   REQ_BGL = False
4569
4570   def CheckArguments(self):
4571     _CheckOutputFields(static=self._FIELDS_STATIC,
4572                        dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4573                        selected=self.op.output_fields)
4574
4575   def ExpandNames(self):
4576     self.needed_locks = {}
4577     self.share_locks[locking.LEVEL_NODE] = 1
4578
4579     if self.op.nodes:
4580       self.needed_locks[locking.LEVEL_NODE] = \
4581         _GetWantedNodes(self, self.op.nodes)
4582     else:
4583       self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4584
4585   def Exec(self, feedback_fn):
4586     """Computes the list of nodes and their attributes.
4587
4588     """
4589     self.nodes = self.owned_locks(locking.LEVEL_NODE)
4590
4591     # Always get name to sort by
4592     if constants.SF_NAME in self.op.output_fields:
4593       fields = self.op.output_fields[:]
4594     else:
4595       fields = [constants.SF_NAME] + self.op.output_fields
4596
4597     # Never ask for node or type as it's only known to the LU
4598     for extra in [constants.SF_NODE, constants.SF_TYPE]:
4599       while extra in fields:
4600         fields.remove(extra)
4601
4602     field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4603     name_idx = field_idx[constants.SF_NAME]
4604
4605     st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4606     data = self.rpc.call_storage_list(self.nodes,
4607                                       self.op.storage_type, st_args,
4608                                       self.op.name, fields)
4609
4610     result = []
4611
4612     for node in utils.NiceSort(self.nodes):
4613       nresult = data[node]
4614       if nresult.offline:
4615         continue
4616
4617       msg = nresult.fail_msg
4618       if msg:
4619         self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4620         continue
4621
4622       rows = dict([(row[name_idx], row) for row in nresult.payload])
4623
4624       for name in utils.NiceSort(rows.keys()):
4625         row = rows[name]
4626
4627         out = []
4628
4629         for field in self.op.output_fields:
4630           if field == constants.SF_NODE:
4631             val = node
4632           elif field == constants.SF_TYPE:
4633             val = self.op.storage_type
4634           elif field in field_idx:
4635             val = row[field_idx[field]]
4636           else:
4637             raise errors.ParameterError(field)
4638
4639           out.append(val)
4640
4641         result.append(out)
4642
4643     return result
4644
4645
4646 class _InstanceQuery(_QueryBase):
4647   FIELDS = query.INSTANCE_FIELDS
4648
4649   def ExpandNames(self, lu):
4650     lu.needed_locks = {}
4651     lu.share_locks = _ShareAll()
4652
4653     if self.names:
4654       self.wanted = _GetWantedInstances(lu, self.names)
4655     else:
4656       self.wanted = locking.ALL_SET
4657
4658     self.do_locking = (self.use_locking and
4659                        query.IQ_LIVE in self.requested_data)
4660     if self.do_locking:
4661       lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4662       lu.needed_locks[locking.LEVEL_NODEGROUP] = []
4663       lu.needed_locks[locking.LEVEL_NODE] = []
4664       lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4665
4666     self.do_grouplocks = (self.do_locking and
4667                           query.IQ_NODES in self.requested_data)
4668
4669   def DeclareLocks(self, lu, level):
4670     if self.do_locking:
4671       if level == locking.LEVEL_NODEGROUP and self.do_grouplocks:
4672         assert not lu.needed_locks[locking.LEVEL_NODEGROUP]
4673
4674         # Lock all groups used by instances optimistically; this requires going
4675         # via the node before it's locked, requiring verification later on
4676         lu.needed_locks[locking.LEVEL_NODEGROUP] = \
4677           set(group_uuid
4678               for instance_name in lu.owned_locks(locking.LEVEL_INSTANCE)
4679               for group_uuid in lu.cfg.GetInstanceNodeGroups(instance_name))
4680       elif level == locking.LEVEL_NODE:
4681         lu._LockInstancesNodes() # pylint: disable=W0212
4682
4683   @staticmethod
4684   def _CheckGroupLocks(lu):
4685     owned_instances = frozenset(lu.owned_locks(locking.LEVEL_INSTANCE))
4686     owned_groups = frozenset(lu.owned_locks(locking.LEVEL_NODEGROUP))
4687
4688     # Check if node groups for locked instances are still correct
4689     for instance_name in owned_instances:
4690       _CheckInstanceNodeGroups(lu.cfg, instance_name, owned_groups)
4691
4692   def _GetQueryData(self, lu):
4693     """Computes the list of instances and their attributes.
4694
4695     """
4696     if self.do_grouplocks:
4697       self._CheckGroupLocks(lu)
4698
4699     cluster = lu.cfg.GetClusterInfo()
4700     all_info = lu.cfg.GetAllInstancesInfo()
4701
4702     instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4703
4704     instance_list = [all_info[name] for name in instance_names]
4705     nodes = frozenset(itertools.chain(*(inst.all_nodes
4706                                         for inst in instance_list)))
4707     hv_list = list(set([inst.hypervisor for inst in instance_list]))
4708     bad_nodes = []
4709     offline_nodes = []
4710     wrongnode_inst = set()
4711
4712     # Gather data as requested
4713     if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4714       live_data = {}
4715       node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4716       for name in nodes:
4717         result = node_data[name]
4718         if result.offline:
4719           # offline nodes will be in both lists
4720           assert result.fail_msg
4721           offline_nodes.append(name)
4722         if result.fail_msg:
4723           bad_nodes.append(name)
4724         elif result.payload:
4725           for inst in result.payload:
4726             if inst in all_info:
4727               if all_info[inst].primary_node == name:
4728                 live_data.update(result.payload)
4729               else:
4730                 wrongnode_inst.add(inst)
4731             else:
4732               # orphan instance; we don't list it here as we don't
4733               # handle this case yet in the output of instance listing
4734               logging.warning("Orphan instance '%s' found on node %s",
4735                               inst, name)
4736         # else no instance is alive
4737     else:
4738       live_data = {}
4739
4740     if query.IQ_DISKUSAGE in self.requested_data:
4741       disk_usage = dict((inst.name,
4742                          _ComputeDiskSize(inst.disk_template,
4743                                           [{constants.IDISK_SIZE: disk.size}
4744                                            for disk in inst.disks]))
4745                         for inst in instance_list)
4746     else:
4747       disk_usage = None
4748
4749     if query.IQ_CONSOLE in self.requested_data:
4750       consinfo = {}
4751       for inst in instance_list:
4752         if inst.name in live_data:
4753           # Instance is running
4754           consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4755         else:
4756           consinfo[inst.name] = None
4757       assert set(consinfo.keys()) == set(instance_names)
4758     else:
4759       consinfo = None
4760
4761     if query.IQ_NODES in self.requested_data:
4762       node_names = set(itertools.chain(*map(operator.attrgetter("all_nodes"),
4763                                             instance_list)))
4764       nodes = dict(lu.cfg.GetMultiNodeInfo(node_names))
4765       groups = dict((uuid, lu.cfg.GetNodeGroup(uuid))
4766                     for uuid in set(map(operator.attrgetter("group"),
4767                                         nodes.values())))
4768     else:
4769       nodes = None
4770       groups = None
4771
4772     return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4773                                    disk_usage, offline_nodes, bad_nodes,
4774                                    live_data, wrongnode_inst, consinfo,
4775                                    nodes, groups)
4776
4777
4778 class LUQuery(NoHooksLU):
4779   """Query for resources/items of a certain kind.
4780
4781   """
4782   # pylint: disable=W0142
4783   REQ_BGL = False
4784
4785   def CheckArguments(self):
4786     qcls = _GetQueryImplementation(self.op.what)
4787
4788     self.impl = qcls(self.op.filter, self.op.fields, self.op.use_locking)
4789
4790   def ExpandNames(self):
4791     self.impl.ExpandNames(self)
4792
4793   def DeclareLocks(self, level):
4794     self.impl.DeclareLocks(self, level)
4795
4796   def Exec(self, feedback_fn):
4797     return self.impl.NewStyleQuery(self)
4798
4799
4800 class LUQueryFields(NoHooksLU):
4801   """Query for resources/items of a certain kind.
4802
4803   """
4804   # pylint: disable=W0142
4805   REQ_BGL = False
4806
4807   def CheckArguments(self):
4808     self.qcls = _GetQueryImplementation(self.op.what)
4809
4810   def ExpandNames(self):
4811     self.needed_locks = {}
4812
4813   def Exec(self, feedback_fn):
4814     return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4815
4816
4817 class LUNodeModifyStorage(NoHooksLU):
4818   """Logical unit for modifying a storage volume on a node.
4819
4820   """
4821   REQ_BGL = False
4822
4823   def CheckArguments(self):
4824     self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4825
4826     storage_type = self.op.storage_type
4827
4828     try:
4829       modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4830     except KeyError:
4831       raise errors.OpPrereqError("Storage units of type '%s' can not be"
4832                                  " modified" % storage_type,
4833                                  errors.ECODE_INVAL)
4834
4835     diff = set(self.op.changes.keys()) - modifiable
4836     if diff:
4837       raise errors.OpPrereqError("The following fields can not be modified for"
4838                                  " storage units of type '%s': %r" %
4839                                  (storage_type, list(diff)),
4840                                  errors.ECODE_INVAL)
4841
4842   def ExpandNames(self):
4843     self.needed_locks = {
4844       locking.LEVEL_NODE: self.op.node_name,
4845       }
4846
4847   def Exec(self, feedback_fn):
4848     """Computes the list of nodes and their attributes.
4849
4850     """
4851     st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4852     result = self.rpc.call_storage_modify(self.op.node_name,
4853                                           self.op.storage_type, st_args,
4854                                           self.op.name, self.op.changes)
4855     result.Raise("Failed to modify storage unit '%s' on %s" %
4856                  (self.op.name, self.op.node_name))
4857
4858
4859 class LUNodeAdd(LogicalUnit):
4860   """Logical unit for adding node to the cluster.
4861
4862   """
4863   HPATH = "node-add"
4864   HTYPE = constants.HTYPE_NODE
4865   _NFLAGS = ["master_capable", "vm_capable"]
4866
4867   def CheckArguments(self):
4868     self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4869     # validate/normalize the node name
4870     self.hostname = netutils.GetHostname(name=self.op.node_name,
4871                                          family=self.primary_ip_family)
4872     self.op.node_name = self.hostname.name
4873
4874     if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4875       raise errors.OpPrereqError("Cannot readd the master node",
4876                                  errors.ECODE_STATE)
4877
4878     if self.op.readd and self.op.group:
4879       raise errors.OpPrereqError("Cannot pass a node group when a node is"
4880                                  " being readded", errors.ECODE_INVAL)
4881
4882   def BuildHooksEnv(self):
4883     """Build hooks env.
4884
4885     This will run on all nodes before, and on all nodes + the new node after.
4886
4887     """
4888     return {
4889       "OP_TARGET": self.op.node_name,
4890       "NODE_NAME": self.op.node_name,
4891       "NODE_PIP": self.op.primary_ip,
4892       "NODE_SIP": self.op.secondary_ip,
4893       "MASTER_CAPABLE": str(self.op.master_capable),
4894       "VM_CAPABLE": str(self.op.vm_capable),
4895       }
4896
4897   def BuildHooksNodes(self):
4898     """Build hooks nodes.
4899
4900     """
4901     # Exclude added node
4902     pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4903     post_nodes = pre_nodes + [self.op.node_name, ]
4904
4905     return (pre_nodes, post_nodes)
4906
4907   def CheckPrereq(self):
4908     """Check prerequisites.
4909
4910     This checks:
4911      - the new node is not already in the config
4912      - it is resolvable
4913      - its parameters (single/dual homed) matches the cluster
4914
4915     Any errors are signaled by raising errors.OpPrereqError.
4916
4917     """
4918     cfg = self.cfg
4919     hostname = self.hostname
4920     node = hostname.name
4921     primary_ip = self.op.primary_ip = hostname.ip
4922     if self.op.secondary_ip is None:
4923       if self.primary_ip_family == netutils.IP6Address.family:
4924         raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4925                                    " IPv4 address must be given as secondary",
4926                                    errors.ECODE_INVAL)
4927       self.op.secondary_ip = primary_ip
4928
4929     secondary_ip = self.op.secondary_ip
4930     if not netutils.IP4Address.IsValid(secondary_ip):
4931       raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4932                                  " address" % secondary_ip, errors.ECODE_INVAL)
4933
4934     node_list = cfg.GetNodeList()
4935     if not self.op.readd and node in node_list:
4936       raise errors.OpPrereqError("Node %s is already in the configuration" %
4937                                  node, errors.ECODE_EXISTS)
4938     elif self.op.readd and node not in node_list:
4939       raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4940                                  errors.ECODE_NOENT)
4941
4942     self.changed_primary_ip = False
4943
4944     for existing_node_name, existing_node in cfg.GetMultiNodeInfo(node_list):
4945       if self.op.readd and node == existing_node_name:
4946         if existing_node.secondary_ip != secondary_ip:
4947           raise errors.OpPrereqError("Readded node doesn't have the same IP"
4948                                      " address configuration as before",
4949                                      errors.ECODE_INVAL)
4950         if existing_node.primary_ip != primary_ip:
4951           self.changed_primary_ip = True
4952
4953         continue
4954
4955       if (existing_node.primary_ip == primary_ip or
4956           existing_node.secondary_ip == primary_ip or
4957           existing_node.primary_ip == secondary_ip or
4958           existing_node.secondary_ip == secondary_ip):
4959         raise errors.OpPrereqError("New node ip address(es) conflict with"
4960                                    " existing node %s" % existing_node.name,
4961                                    errors.ECODE_NOTUNIQUE)
4962
4963     # After this 'if' block, None is no longer a valid value for the
4964     # _capable op attributes
4965     if self.op.readd:
4966       old_node = self.cfg.GetNodeInfo(node)
4967       assert old_node is not None, "Can't retrieve locked node %s" % node
4968       for attr in self._NFLAGS:
4969         if getattr(self.op, attr) is None:
4970           setattr(self.op, attr, getattr(old_node, attr))
4971     else:
4972       for attr in self._NFLAGS:
4973         if getattr(self.op, attr) is None:
4974           setattr(self.op, attr, True)
4975
4976     if self.op.readd and not self.op.vm_capable:
4977       pri, sec = cfg.GetNodeInstances(node)
4978       if pri or sec:
4979         raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4980                                    " flag set to false, but it already holds"
4981                                    " instances" % node,
4982                                    errors.ECODE_STATE)
4983
4984     # check that the type of the node (single versus dual homed) is the
4985     # same as for the master
4986     myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4987     master_singlehomed = myself.secondary_ip == myself.primary_ip
4988     newbie_singlehomed = secondary_ip == primary_ip
4989     if master_singlehomed != newbie_singlehomed:
4990       if master_singlehomed:
4991         raise errors.OpPrereqError("The master has no secondary ip but the"
4992                                    " new node has one",
4993                                    errors.ECODE_INVAL)
4994       else:
4995         raise errors.OpPrereqError("The master has a secondary ip but the"
4996                                    " new node doesn't have one",
4997                                    errors.ECODE_INVAL)
4998
4999     # checks reachability
5000     if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
5001       raise errors.OpPrereqError("Node not reachable by ping",
5002                                  errors.ECODE_ENVIRON)
5003
5004     if not newbie_singlehomed:
5005       # check reachability from my secondary ip to newbie's secondary ip
5006       if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
5007                            source=myself.secondary_ip):
5008         raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5009                                    " based ping to node daemon port",
5010                                    errors.ECODE_ENVIRON)
5011
5012     if self.op.readd:
5013       exceptions = [node]
5014     else:
5015       exceptions = []
5016
5017     if self.op.master_capable:
5018       self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
5019     else:
5020       self.master_candidate = False
5021
5022     if self.op.readd:
5023       self.new_node = old_node
5024     else:
5025       node_group = cfg.LookupNodeGroup(self.op.group)
5026       self.new_node = objects.Node(name=node,
5027                                    primary_ip=primary_ip,
5028                                    secondary_ip=secondary_ip,
5029                                    master_candidate=self.master_candidate,
5030                                    offline=False, drained=False,
5031                                    group=node_group)
5032
5033     if self.op.ndparams:
5034       utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
5035
5036   def Exec(self, feedback_fn):
5037     """Adds the new node to the cluster.
5038
5039     """
5040     new_node = self.new_node
5041     node = new_node.name
5042
5043     # We adding a new node so we assume it's powered
5044     new_node.powered = True
5045
5046     # for re-adds, reset the offline/drained/master-candidate flags;
5047     # we need to reset here, otherwise offline would prevent RPC calls
5048     # later in the procedure; this also means that if the re-add
5049     # fails, we are left with a non-offlined, broken node
5050     if self.op.readd:
5051       new_node.drained = new_node.offline = False # pylint: disable=W0201
5052       self.LogInfo("Readding a node, the offline/drained flags were reset")
5053       # if we demote the node, we do cleanup later in the procedure
5054       new_node.master_candidate = self.master_candidate
5055       if self.changed_primary_ip:
5056         new_node.primary_ip = self.op.primary_ip
5057
5058     # copy the master/vm_capable flags
5059     for attr in self._NFLAGS:
5060       setattr(new_node, attr, getattr(self.op, attr))
5061
5062     # notify the user about any possible mc promotion
5063     if new_node.master_candidate:
5064       self.LogInfo("Node will be a master candidate")
5065
5066     if self.op.ndparams:
5067       new_node.ndparams = self.op.ndparams
5068     else:
5069       new_node.ndparams = {}
5070
5071     # check connectivity
5072     result = self.rpc.call_version([node])[node]
5073     result.Raise("Can't get version information from node %s" % node)
5074     if constants.PROTOCOL_VERSION == result.payload:
5075       logging.info("Communication to node %s fine, sw version %s match",
5076                    node, result.payload)
5077     else:
5078       raise errors.OpExecError("Version mismatch master version %s,"
5079                                " node version %s" %
5080                                (constants.PROTOCOL_VERSION, result.payload))
5081
5082     # Add node to our /etc/hosts, and add key to known_hosts
5083     if self.cfg.GetClusterInfo().modify_etc_hosts:
5084       master_node = self.cfg.GetMasterNode()
5085       result = self.rpc.call_etc_hosts_modify(master_node,
5086                                               constants.ETC_HOSTS_ADD,
5087                                               self.hostname.name,
5088                                               self.hostname.ip)
5089       result.Raise("Can't update hosts file with new host data")
5090
5091     if new_node.secondary_ip != new_node.primary_ip:
5092       _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
5093                                False)
5094
5095     node_verify_list = [self.cfg.GetMasterNode()]
5096     node_verify_param = {
5097       constants.NV_NODELIST: ([node], {}),
5098       # TODO: do a node-net-test as well?
5099     }
5100
5101     result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
5102                                        self.cfg.GetClusterName())
5103     for verifier in node_verify_list:
5104       result[verifier].Raise("Cannot communicate with node %s" % verifier)
5105       nl_payload = result[verifier].payload[constants.NV_NODELIST]
5106       if nl_payload:
5107         for failed in nl_payload:
5108           feedback_fn("ssh/hostname verification failed"
5109                       " (checking from %s): %s" %
5110                       (verifier, nl_payload[failed]))
5111         raise errors.OpExecError("ssh/hostname verification failed")
5112
5113     if self.op.readd:
5114       _RedistributeAncillaryFiles(self)
5115       self.context.ReaddNode(new_node)
5116       # make sure we redistribute the config
5117       self.cfg.Update(new_node, feedback_fn)
5118       # and make sure the new node will not have old files around
5119       if not new_node.master_candidate:
5120         result = self.rpc.call_node_demote_from_mc(new_node.name)
5121         msg = result.fail_msg
5122         if msg:
5123           self.LogWarning("Node failed to demote itself from master"
5124                           " candidate status: %s" % msg)
5125     else:
5126       _RedistributeAncillaryFiles(self, additional_nodes=[node],
5127                                   additional_vm=self.op.vm_capable)
5128       self.context.AddNode(new_node, self.proc.GetECId())
5129
5130
5131 class LUNodeSetParams(LogicalUnit):
5132   """Modifies the parameters of a node.
5133
5134   @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
5135       to the node role (as _ROLE_*)
5136   @cvar _R2F: a dictionary from node role to tuples of flags
5137   @cvar _FLAGS: a list of attribute names corresponding to the flags
5138
5139   """
5140   HPATH = "node-modify"
5141   HTYPE = constants.HTYPE_NODE
5142   REQ_BGL = False
5143   (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
5144   _F2R = {
5145     (True, False, False): _ROLE_CANDIDATE,
5146     (False, True, False): _ROLE_DRAINED,
5147     (False, False, True): _ROLE_OFFLINE,
5148     (False, False, False): _ROLE_REGULAR,
5149     }
5150   _R2F = dict((v, k) for k, v in _F2R.items())
5151   _FLAGS = ["master_candidate", "drained", "offline"]
5152
5153   def CheckArguments(self):
5154     self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5155     all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
5156                 self.op.master_capable, self.op.vm_capable,
5157                 self.op.secondary_ip, self.op.ndparams]
5158     if all_mods.count(None) == len(all_mods):
5159       raise errors.OpPrereqError("Please pass at least one modification",
5160                                  errors.ECODE_INVAL)
5161     if all_mods.count(True) > 1:
5162       raise errors.OpPrereqError("Can't set the node into more than one"
5163                                  " state at the same time",
5164                                  errors.ECODE_INVAL)
5165
5166     # Boolean value that tells us whether we might be demoting from MC
5167     self.might_demote = (self.op.master_candidate == False or
5168                          self.op.offline == True or
5169                          self.op.drained == True or
5170                          self.op.master_capable == False)
5171
5172     if self.op.secondary_ip:
5173       if not netutils.IP4Address.IsValid(self.op.secondary_ip):
5174         raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
5175                                    " address" % self.op.secondary_ip,
5176                                    errors.ECODE_INVAL)
5177
5178     self.lock_all = self.op.auto_promote and self.might_demote
5179     self.lock_instances = self.op.secondary_ip is not None
5180
5181   def ExpandNames(self):
5182     if self.lock_all:
5183       self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
5184     else:
5185       self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
5186
5187     if self.lock_instances:
5188       self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5189
5190   def DeclareLocks(self, level):
5191     # If we have locked all instances, before waiting to lock nodes, release
5192     # all the ones living on nodes unrelated to the current operation.
5193     if level == locking.LEVEL_NODE and self.lock_instances:
5194       self.affected_instances = []
5195       if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5196         instances_keep = []
5197
5198         # Build list of instances to release
5199         locked_i = self.owned_locks(locking.LEVEL_INSTANCE)
5200         for instance_name, instance in self.cfg.GetMultiInstanceInfo(locked_i):
5201           if (instance.disk_template in constants.DTS_INT_MIRROR and
5202               self.op.node_name in instance.all_nodes):
5203             instances_keep.append(instance_name)
5204             self.affected_instances.append(instance)
5205
5206         _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
5207
5208         assert (set(self.owned_locks(locking.LEVEL_INSTANCE)) ==
5209                 set(instances_keep))
5210
5211   def BuildHooksEnv(self):
5212     """Build hooks env.
5213
5214     This runs on the master node.
5215
5216     """
5217     return {
5218       "OP_TARGET": self.op.node_name,
5219       "MASTER_CANDIDATE": str(self.op.master_candidate),
5220       "OFFLINE": str(self.op.offline),
5221       "DRAINED": str(self.op.drained),
5222       "MASTER_CAPABLE": str(self.op.master_capable),
5223       "VM_CAPABLE": str(self.op.vm_capable),
5224       }
5225
5226   def BuildHooksNodes(self):
5227     """Build hooks nodes.
5228
5229     """
5230     nl = [self.cfg.GetMasterNode(), self.op.node_name]
5231     return (nl, nl)
5232
5233   def CheckPrereq(self):
5234     """Check prerequisites.
5235
5236     This only checks the instance list against the existing names.
5237
5238     """
5239     node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
5240
5241     if (self.op.master_candidate is not None or
5242         self.op.drained is not None or
5243         self.op.offline is not None):
5244       # we can't change the master's node flags
5245       if self.op.node_name == self.cfg.GetMasterNode():
5246         raise errors.OpPrereqError("The master role can be changed"
5247                                    " only via master-failover",
5248                                    errors.ECODE_INVAL)
5249
5250     if self.op.master_candidate and not node.master_capable:
5251       raise errors.OpPrereqError("Node %s is not master capable, cannot make"
5252                                  " it a master candidate" % node.name,
5253                                  errors.ECODE_STATE)
5254
5255     if self.op.vm_capable == False:
5256       (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
5257       if ipri or isec:
5258         raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
5259                                    " the vm_capable flag" % node.name,
5260                                    errors.ECODE_STATE)
5261
5262     if node.master_candidate and self.might_demote and not self.lock_all:
5263       assert not self.op.auto_promote, "auto_promote set but lock_all not"
5264       # check if after removing the current node, we're missing master
5265       # candidates
5266       (mc_remaining, mc_should, _) = \
5267           self.cfg.GetMasterCandidateStats(exceptions=[node.name])
5268       if mc_remaining < mc_should:
5269         raise errors.OpPrereqError("Not enough master candidates, please"
5270                                    " pass auto promote option to allow"
5271                                    " promotion", errors.ECODE_STATE)
5272
5273     self.old_flags = old_flags = (node.master_candidate,
5274                                   node.drained, node.offline)
5275     assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
5276     self.old_role = old_role = self._F2R[old_flags]
5277
5278     # Check for ineffective changes
5279     for attr in self._FLAGS:
5280       if (getattr(self.op, attr) == False and getattr(node, attr) == False):
5281         self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
5282         setattr(self.op, attr, None)
5283
5284     # Past this point, any flag change to False means a transition
5285     # away from the respective state, as only real changes are kept
5286
5287     # TODO: We might query the real power state if it supports OOB
5288     if _SupportsOob(self.cfg, node):
5289       if self.op.offline is False and not (node.powered or
5290                                            self.op.powered == True):
5291         raise errors.OpPrereqError(("Node %s needs to be turned on before its"
5292                                     " offline status can be reset") %
5293                                    self.op.node_name)
5294     elif self.op.powered is not None:
5295       raise errors.OpPrereqError(("Unable to change powered state for node %s"
5296                                   " as it does not support out-of-band"
5297                                   " handling") % self.op.node_name)
5298
5299     # If we're being deofflined/drained, we'll MC ourself if needed
5300     if (self.op.drained == False or self.op.offline == False or
5301         (self.op.master_capable and not node.master_capable)):
5302       if _DecideSelfPromotion(self):
5303         self.op.master_candidate = True
5304         self.LogInfo("Auto-promoting node to master candidate")
5305
5306     # If we're no longer master capable, we'll demote ourselves from MC
5307     if self.op.master_capable == False and node.master_candidate:
5308       self.LogInfo("Demoting from master candidate")
5309       self.op.master_candidate = False
5310
5311     # Compute new role
5312     assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
5313     if self.op.master_candidate:
5314       new_role = self._ROLE_CANDIDATE
5315     elif self.op.drained:
5316       new_role = self._ROLE_DRAINED
5317     elif self.op.offline:
5318       new_role = self._ROLE_OFFLINE
5319     elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
5320       # False is still in new flags, which means we're un-setting (the
5321       # only) True flag
5322       new_role = self._ROLE_REGULAR
5323     else: # no new flags, nothing, keep old role
5324       new_role = old_role
5325
5326     self.new_role = new_role
5327
5328     if old_role == self._ROLE_OFFLINE and new_role != old_role:
5329       # Trying to transition out of offline status
5330       result = self.rpc.call_version([node.name])[node.name]
5331       if result.fail_msg:
5332         raise errors.OpPrereqError("Node %s is being de-offlined but fails"
5333                                    " to report its version: %s" %
5334                                    (node.name, result.fail_msg),
5335                                    errors.ECODE_STATE)
5336       else:
5337         self.LogWarning("Transitioning node from offline to online state"
5338                         " without using re-add. Please make sure the node"
5339                         " is healthy!")
5340
5341     if self.op.secondary_ip:
5342       # Ok even without locking, because this can't be changed by any LU
5343       master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
5344       master_singlehomed = master.secondary_ip == master.primary_ip
5345       if master_singlehomed and self.op.secondary_ip:
5346         raise errors.OpPrereqError("Cannot change the secondary ip on a single"
5347                                    " homed cluster", errors.ECODE_INVAL)
5348
5349       if node.offline:
5350         if self.affected_instances:
5351           raise errors.OpPrereqError("Cannot change secondary ip: offline"
5352                                      " node has instances (%s) configured"
5353                                      " to use it" % self.affected_instances)
5354       else:
5355         # On online nodes, check that no instances are running, and that
5356         # the node has the new ip and we can reach it.
5357         for instance in self.affected_instances:
5358           _CheckInstanceDown(self, instance, "cannot change secondary ip")
5359
5360         _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
5361         if master.name != node.name:
5362           # check reachability from master secondary ip to new secondary ip
5363           if not netutils.TcpPing(self.op.secondary_ip,
5364                                   constants.DEFAULT_NODED_PORT,
5365                                   source=master.secondary_ip):
5366             raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5367                                        " based ping to node daemon port",
5368                                        errors.ECODE_ENVIRON)
5369
5370     if self.op.ndparams:
5371       new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
5372       utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
5373       self.new_ndparams = new_ndparams
5374
5375   def Exec(self, feedback_fn):
5376     """Modifies a node.
5377
5378     """
5379     node = self.node
5380     old_role = self.old_role
5381     new_role = self.new_role
5382
5383     result = []
5384
5385     if self.op.ndparams:
5386       node.ndparams = self.new_ndparams
5387
5388     if self.op.powered is not None:
5389       node.powered = self.op.powered
5390
5391     for attr in ["master_capable", "vm_capable"]:
5392       val = getattr(self.op, attr)
5393       if val is not None:
5394         setattr(node, attr, val)
5395         result.append((attr, str(val)))
5396
5397     if new_role != old_role:
5398       # Tell the node to demote itself, if no longer MC and not offline
5399       if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5400         msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5401         if msg:
5402           self.LogWarning("Node failed to demote itself: %s", msg)
5403
5404       new_flags = self._R2F[new_role]
5405       for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5406         if of != nf:
5407           result.append((desc, str(nf)))
5408       (node.master_candidate, node.drained, node.offline) = new_flags
5409
5410       # we locked all nodes, we adjust the CP before updating this node
5411       if self.lock_all:
5412         _AdjustCandidatePool(self, [node.name])
5413
5414     if self.op.secondary_ip:
5415       node.secondary_ip = self.op.secondary_ip
5416       result.append(("secondary_ip", self.op.secondary_ip))
5417
5418     # this will trigger configuration file update, if needed
5419     self.cfg.Update(node, feedback_fn)
5420
5421     # this will trigger job queue propagation or cleanup if the mc
5422     # flag changed
5423     if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5424       self.context.ReaddNode(node)
5425
5426     return result
5427
5428
5429 class LUNodePowercycle(NoHooksLU):
5430   """Powercycles a node.
5431
5432   """
5433   REQ_BGL = False
5434
5435   def CheckArguments(self):
5436     self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5437     if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5438       raise errors.OpPrereqError("The node is the master and the force"
5439                                  " parameter was not set",
5440                                  errors.ECODE_INVAL)
5441
5442   def ExpandNames(self):
5443     """Locking for PowercycleNode.
5444
5445     This is a last-resort option and shouldn't block on other
5446     jobs. Therefore, we grab no locks.
5447
5448     """
5449     self.needed_locks = {}
5450
5451   def Exec(self, feedback_fn):
5452     """Reboots a node.
5453
5454     """
5455     result = self.rpc.call_node_powercycle(self.op.node_name,
5456                                            self.cfg.GetHypervisorType())
5457     result.Raise("Failed to schedule the reboot")
5458     return result.payload
5459
5460
5461 class LUClusterQuery(NoHooksLU):
5462   """Query cluster configuration.
5463
5464   """
5465   REQ_BGL = False
5466
5467   def ExpandNames(self):
5468     self.needed_locks = {}
5469
5470   def Exec(self, feedback_fn):
5471     """Return cluster config.
5472
5473     """
5474     cluster = self.cfg.GetClusterInfo()
5475     os_hvp = {}
5476
5477     # Filter just for enabled hypervisors
5478     for os_name, hv_dict in cluster.os_hvp.items():
5479       os_hvp[os_name] = {}
5480       for hv_name, hv_params in hv_dict.items():
5481         if hv_name in cluster.enabled_hypervisors:
5482           os_hvp[os_name][hv_name] = hv_params
5483
5484     # Convert ip_family to ip_version
5485     primary_ip_version = constants.IP4_VERSION
5486     if cluster.primary_ip_family == netutils.IP6Address.family:
5487       primary_ip_version = constants.IP6_VERSION
5488
5489     result = {
5490       "software_version": constants.RELEASE_VERSION,
5491       "protocol_version": constants.PROTOCOL_VERSION,
5492       "config_version": constants.CONFIG_VERSION,
5493       "os_api_version": max(constants.OS_API_VERSIONS),
5494       "export_version": constants.EXPORT_VERSION,
5495       "architecture": (platform.architecture()[0], platform.machine()),
5496       "name": cluster.cluster_name,
5497       "master": cluster.master_node,
5498       "default_hypervisor": cluster.enabled_hypervisors[0],
5499       "enabled_hypervisors": cluster.enabled_hypervisors,
5500       "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5501                         for hypervisor_name in cluster.enabled_hypervisors]),
5502       "os_hvp": os_hvp,
5503       "beparams": cluster.beparams,
5504       "osparams": cluster.osparams,
5505       "nicparams": cluster.nicparams,
5506       "ndparams": cluster.ndparams,
5507       "candidate_pool_size": cluster.candidate_pool_size,
5508       "master_netdev": cluster.master_netdev,
5509       "volume_group_name": cluster.volume_group_name,
5510       "drbd_usermode_helper": cluster.drbd_usermode_helper,
5511       "file_storage_dir": cluster.file_storage_dir,
5512       "shared_file_storage_dir": cluster.shared_file_storage_dir,
5513       "maintain_node_health": cluster.maintain_node_health,
5514       "ctime": cluster.ctime,
5515       "mtime": cluster.mtime,
5516       "uuid": cluster.uuid,
5517       "tags": list(cluster.GetTags()),
5518       "uid_pool": cluster.uid_pool,
5519       "default_iallocator": cluster.default_iallocator,
5520       "reserved_lvs": cluster.reserved_lvs,
5521       "primary_ip_version": primary_ip_version,
5522       "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5523       "hidden_os": cluster.hidden_os,
5524       "blacklisted_os": cluster.blacklisted_os,
5525       }
5526
5527     return result
5528
5529
5530 class LUClusterConfigQuery(NoHooksLU):
5531   """Return configuration values.
5532
5533   """
5534   REQ_BGL = False
5535   _FIELDS_DYNAMIC = utils.FieldSet()
5536   _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5537                                   "watcher_pause", "volume_group_name")
5538
5539   def CheckArguments(self):
5540     _CheckOutputFields(static=self._FIELDS_STATIC,
5541                        dynamic=self._FIELDS_DYNAMIC,
5542                        selected=self.op.output_fields)
5543
5544   def ExpandNames(self):
5545     self.needed_locks = {}
5546
5547   def Exec(self, feedback_fn):
5548     """Dump a representation of the cluster config to the standard output.
5549
5550     """
5551     values = []
5552     for field in self.op.output_fields:
5553       if field == "cluster_name":
5554         entry = self.cfg.GetClusterName()
5555       elif field == "master_node":
5556         entry = self.cfg.GetMasterNode()
5557       elif field == "drain_flag":
5558         entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5559       elif field == "watcher_pause":
5560         entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5561       elif field == "volume_group_name":
5562         entry = self.cfg.GetVGName()
5563       else:
5564         raise errors.ParameterError(field)
5565       values.append(entry)
5566     return values
5567
5568
5569 class LUInstanceActivateDisks(NoHooksLU):
5570   """Bring up an instance's disks.
5571
5572   """
5573   REQ_BGL = False
5574
5575   def ExpandNames(self):
5576     self._ExpandAndLockInstance()
5577     self.needed_locks[locking.LEVEL_NODE] = []
5578     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5579
5580   def DeclareLocks(self, level):
5581     if level == locking.LEVEL_NODE:
5582       self._LockInstancesNodes()
5583
5584   def CheckPrereq(self):
5585     """Check prerequisites.
5586
5587     This checks that the instance is in the cluster.
5588
5589     """
5590     self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5591     assert self.instance is not None, \
5592       "Cannot retrieve locked instance %s" % self.op.instance_name
5593     _CheckNodeOnline(self, self.instance.primary_node)
5594
5595   def Exec(self, feedback_fn):
5596     """Activate the disks.
5597
5598     """
5599     disks_ok, disks_info = \
5600               _AssembleInstanceDisks(self, self.instance,
5601                                      ignore_size=self.op.ignore_size)
5602     if not disks_ok:
5603       raise errors.OpExecError("Cannot activate block devices")
5604
5605     return disks_info
5606
5607
5608 def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5609                            ignore_size=False):
5610   """Prepare the block devices for an instance.
5611
5612   This sets up the block devices on all nodes.
5613
5614   @type lu: L{LogicalUnit}
5615   @param lu: the logical unit on whose behalf we execute
5616   @type instance: L{objects.Instance}
5617   @param instance: the instance for whose disks we assemble
5618   @type disks: list of L{objects.Disk} or None
5619   @param disks: which disks to assemble (or all, if None)
5620   @type ignore_secondaries: boolean
5621   @param ignore_secondaries: if true, errors on secondary nodes
5622       won't result in an error return from the function
5623   @type ignore_size: boolean
5624   @param ignore_size: if true, the current known size of the disk
5625       will not be used during the disk activation, useful for cases
5626       when the size is wrong
5627   @return: False if the operation failed, otherwise a list of
5628       (host, instance_visible_name, node_visible_name)
5629       with the mapping from node devices to instance devices
5630
5631   """
5632   device_info = []
5633   disks_ok = True
5634   iname = instance.name
5635   disks = _ExpandCheckDisks(instance, disks)
5636
5637   # With the two passes mechanism we try to reduce the window of
5638   # opportunity for the race condition of switching DRBD to primary
5639   # before handshaking occured, but we do not eliminate it
5640
5641   # The proper fix would be to wait (with some limits) until the
5642   # connection has been made and drbd transitions from WFConnection
5643   # into any other network-connected state (Connected, SyncTarget,
5644   # SyncSource, etc.)
5645
5646   # 1st pass, assemble on all nodes in secondary mode
5647   for idx, inst_disk in enumerate(disks):
5648     for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5649       if ignore_size:
5650         node_disk = node_disk.Copy()
5651         node_disk.UnsetSize()
5652       lu.cfg.SetDiskID(node_disk, node)
5653       result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5654       msg = result.fail_msg
5655       if msg:
5656         lu.proc.LogWarning("Could not prepare block device %s on node %s"
5657                            " (is_primary=False, pass=1): %s",
5658                            inst_disk.iv_name, node, msg)
5659         if not ignore_secondaries:
5660           disks_ok = False
5661
5662   # FIXME: race condition on drbd migration to primary
5663
5664   # 2nd pass, do only the primary node
5665   for idx, inst_disk in enumerate(disks):
5666     dev_path = None
5667
5668     for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5669       if node != instance.primary_node:
5670         continue
5671       if ignore_size:
5672         node_disk = node_disk.Copy()
5673         node_disk.UnsetSize()
5674       lu.cfg.SetDiskID(node_disk, node)
5675       result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5676       msg = result.fail_msg
5677       if msg:
5678         lu.proc.LogWarning("Could not prepare block device %s on node %s"
5679                            " (is_primary=True, pass=2): %s",
5680                            inst_disk.iv_name, node, msg)
5681         disks_ok = False
5682       else:
5683         dev_path = result.payload
5684
5685     device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5686
5687   # leave the disks configured for the primary node
5688   # this is a workaround that would be fixed better by
5689   # improving the logical/physical id handling
5690   for disk in disks:
5691     lu.cfg.SetDiskID(disk, instance.primary_node)
5692
5693   return disks_ok, device_info
5694
5695
5696 def _StartInstanceDisks(lu, instance, force):
5697   """Start the disks of an instance.
5698
5699   """
5700   disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5701                                            ignore_secondaries=force)
5702   if not disks_ok:
5703     _ShutdownInstanceDisks(lu, instance)
5704     if force is not None and not force:
5705       lu.proc.LogWarning("", hint="If the message above refers to a"
5706                          " secondary node,"
5707                          " you can retry the operation using '--force'.")
5708     raise errors.OpExecError("Disk consistency error")
5709
5710
5711 class LUInstanceDeactivateDisks(NoHooksLU):
5712   """Shutdown an instance's disks.
5713
5714   """
5715   REQ_BGL = False
5716
5717   def ExpandNames(self):
5718     self._ExpandAndLockInstance()
5719     self.needed_locks[locking.LEVEL_NODE] = []
5720     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5721
5722   def DeclareLocks(self, level):
5723     if level == locking.LEVEL_NODE:
5724       self._LockInstancesNodes()
5725
5726   def CheckPrereq(self):
5727     """Check prerequisites.
5728
5729     This checks that the instance is in the cluster.
5730
5731     """
5732     self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5733     assert self.instance is not None, \
5734       "Cannot retrieve locked instance %s" % self.op.instance_name
5735
5736   def Exec(self, feedback_fn):
5737     """Deactivate the disks
5738
5739     """
5740     instance = self.instance
5741     if self.op.force:
5742       _ShutdownInstanceDisks(self, instance)
5743     else:
5744       _SafeShutdownInstanceDisks(self, instance)
5745
5746
5747 def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5748   """Shutdown block devices of an instance.
5749
5750   This function checks if an instance is running, before calling
5751   _ShutdownInstanceDisks.
5752
5753   """
5754   _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5755   _ShutdownInstanceDisks(lu, instance, disks=disks)
5756
5757
5758 def _ExpandCheckDisks(instance, disks):
5759   """Return the instance disks selected by the disks list
5760
5761   @type disks: list of L{objects.Disk} or None
5762   @param disks: selected disks
5763   @rtype: list of L{objects.Disk}
5764   @return: selected instance disks to act on
5765
5766   """
5767   if disks is None:
5768     return instance.disks
5769   else:
5770     if not set(disks).issubset(instance.disks):
5771       raise errors.ProgrammerError("Can only act on disks belonging to the"
5772                                    " target instance")
5773     return disks
5774
5775
5776 def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5777   """Shutdown block devices of an instance.
5778
5779   This does the shutdown on all nodes of the instance.
5780
5781   If the ignore_primary is false, errors on the primary node are
5782   ignored.
5783
5784   """
5785   all_result = True
5786   disks = _ExpandCheckDisks(instance, disks)
5787
5788   for disk in disks:
5789     for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5790       lu.cfg.SetDiskID(top_disk, node)
5791       result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5792       msg = result.fail_msg
5793       if msg:
5794         lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5795                       disk.iv_name, node, msg)
5796         if ((node == instance.primary_node and not ignore_primary) or
5797             (node != instance.primary_node and not result.offline)):
5798           all_result = False
5799   return all_result
5800
5801
5802 def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5803   """Checks if a node has enough free memory.
5804
5805   This function check if a given node has the needed amount of free
5806   memory. In case the node has less memory or we cannot get the
5807   information from the node, this function raise an OpPrereqError
5808   exception.
5809
5810   @type lu: C{LogicalUnit}
5811   @param lu: a logical unit from which we get configuration data
5812   @type node: C{str}
5813   @param node: the node to check
5814   @type reason: C{str}
5815   @param reason: string to use in the error message
5816   @type requested: C{int}
5817   @param requested: the amount of memory in MiB to check for
5818   @type hypervisor_name: C{str}
5819   @param hypervisor_name: the hypervisor to ask for memory stats
5820   @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5821       we cannot check the node
5822
5823   """
5824   nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5825   nodeinfo[node].Raise("Can't get data from node %s" % node,
5826                        prereq=True, ecode=errors.ECODE_ENVIRON)
5827   free_mem = nodeinfo[node].payload.get("memory_free", None)
5828   if not isinstance(free_mem, int):
5829     raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5830                                " was '%s'" % (node, free_mem),
5831                                errors.ECODE_ENVIRON)
5832   if requested > free_mem:
5833     raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5834                                " needed %s MiB, available %s MiB" %
5835                                (node, reason, requested, free_mem),
5836                                errors.ECODE_NORES)
5837
5838
5839 def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5840   """Checks if nodes have enough free disk space in the all VGs.
5841
5842   This function check if all given nodes have the needed amount of
5843   free disk. In case any node has less disk or we cannot get the
5844   information from the node, this function raise an OpPrereqError
5845   exception.
5846
5847   @type lu: C{LogicalUnit}
5848   @param lu: a logical unit from which we get configuration data
5849   @type nodenames: C{list}
5850   @param nodenames: the list of node names to check
5851   @type req_sizes: C{dict}
5852   @param req_sizes: the hash of vg and corresponding amount of disk in
5853       MiB to check for
5854   @raise errors.OpPrereqError: if the node doesn't have enough disk,
5855       or we cannot check the node
5856
5857   """
5858   for vg, req_size in req_sizes.items():
5859     _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5860
5861
5862 def _CheckNodesFreeDiskOnVG(lu, nodenames, vg, requested):
5863   """Checks if nodes have enough free disk space in the specified VG.
5864
5865   This function check if all given nodes have the needed amount of
5866   free disk. In case any node has less disk or we cannot get the
5867   information from the node, this function raise an OpPrereqError
5868   exception.
5869
5870   @type lu: C{LogicalUnit}
5871   @param lu: a logical unit from which we get configuration data
5872   @type nodenames: C{list}
5873   @param nodenames: the list of node names to check
5874   @type vg: C{str}
5875   @param vg: the volume group to check
5876   @type requested: C{int}
5877   @param requested: the amount of disk in MiB to check for
5878   @raise errors.OpPrereqError: if the node doesn't have enough disk,
5879       or we cannot check the node
5880
5881   """
5882   nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5883   for node in nodenames:
5884     info = nodeinfo[node]
5885     info.Raise("Cannot get current information from node %s" % node,
5886                prereq=True, ecode=errors.ECODE_ENVIRON)
5887     vg_free = info.payload.get("vg_free", None)
5888     if not isinstance(vg_free, int):
5889       raise errors.OpPrereqError("Can't compute free disk space on node"
5890                                  " %s for vg %s, result was '%s'" %
5891                                  (node, vg, vg_free), errors.ECODE_ENVIRON)
5892     if requested > vg_free:
5893       raise errors.OpPrereqError("Not enough disk space on target node %s"
5894                                  " vg %s: required %d MiB, available %d MiB" %
5895                                  (node, vg, requested, vg_free),
5896                                  errors.ECODE_NORES)
5897
5898
5899 class LUInstanceStartup(LogicalUnit):
5900   """Starts an instance.
5901
5902   """
5903   HPATH = "instance-start"
5904   HTYPE = constants.HTYPE_INSTANCE
5905   REQ_BGL = False
5906
5907   def CheckArguments(self):
5908     # extra beparams
5909     if self.op.beparams:
5910       # fill the beparams dict
5911       utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5912
5913   def ExpandNames(self):
5914     self._ExpandAndLockInstance()
5915
5916   def BuildHooksEnv(self):
5917     """Build hooks env.
5918
5919     This runs on master, primary and secondary nodes of the instance.
5920
5921     """
5922     env = {
5923       "FORCE": self.op.force,
5924       }
5925
5926     env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5927
5928     return env
5929
5930   def BuildHooksNodes(self):
5931     """Build hooks nodes.
5932
5933     """
5934     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5935     return (nl, nl)
5936
5937   def CheckPrereq(self):
5938     """Check prerequisites.
5939
5940     This checks that the instance is in the cluster.
5941
5942     """
5943     self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5944     assert self.instance is not None, \
5945       "Cannot retrieve locked instance %s" % self.op.instance_name
5946
5947     # extra hvparams
5948     if self.op.hvparams:
5949       # check hypervisor parameter syntax (locally)
5950       cluster = self.cfg.GetClusterInfo()
5951       utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5952       filled_hvp = cluster.FillHV(instance)
5953       filled_hvp.update(self.op.hvparams)
5954       hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5955       hv_type.CheckParameterSyntax(filled_hvp)
5956       _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5957
5958     self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5959
5960     if self.primary_offline and self.op.ignore_offline_nodes:
5961       self.proc.LogWarning("Ignoring offline primary node")
5962
5963       if self.op.hvparams or self.op.beparams:
5964         self.proc.LogWarning("Overridden parameters are ignored")
5965     else:
5966       _CheckNodeOnline(self, instance.primary_node)
5967
5968       bep = self.cfg.GetClusterInfo().FillBE(instance)
5969
5970       # check bridges existence
5971       _CheckInstanceBridgesExist(self, instance)
5972
5973       remote_info = self.rpc.call_instance_info(instance.primary_node,
5974                                                 instance.name,
5975                                                 instance.hypervisor)
5976       remote_info.Raise("Error checking node %s" % instance.primary_node,
5977                         prereq=True, ecode=errors.ECODE_ENVIRON)
5978       if not remote_info.payload: # not running already
5979         _CheckNodeFreeMemory(self, instance.primary_node,
5980                              "starting instance %s" % instance.name,
5981                              bep[constants.BE_MEMORY], instance.hypervisor)
5982
5983   def Exec(self, feedback_fn):
5984     """Start the instance.
5985
5986     """
5987     instance = self.instance
5988     force = self.op.force
5989
5990     if not self.op.no_remember:
5991       self.cfg.MarkInstanceUp(instance.name)
5992
5993     if self.primary_offline:
5994       assert self.op.ignore_offline_nodes
5995       self.proc.LogInfo("Primary node offline, marked instance as started")
5996     else:
5997       node_current = instance.primary_node
5998
5999       _StartInstanceDisks(self, instance, force)
6000
6001       result = self.rpc.call_instance_start(node_current, instance,
6002                                             self.op.hvparams, self.op.beparams,
6003                                             self.op.startup_paused)
6004       msg = result.fail_msg
6005       if msg:
6006         _ShutdownInstanceDisks(self, instance)
6007         raise errors.OpExecError("Could not start instance: %s" % msg)
6008
6009
6010 class LUInstanceReboot(LogicalUnit):
6011   """Reboot an instance.
6012
6013   """
6014   HPATH = "instance-reboot"
6015   HTYPE = constants.HTYPE_INSTANCE
6016   REQ_BGL = False
6017
6018   def ExpandNames(self):
6019     self._ExpandAndLockInstance()
6020
6021   def BuildHooksEnv(self):
6022     """Build hooks env.
6023
6024     This runs on master, primary and secondary nodes of the instance.
6025
6026     """
6027     env = {
6028       "IGNORE_SECONDARIES": self.op.ignore_secondaries,
6029       "REBOOT_TYPE": self.op.reboot_type,
6030       "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6031       }
6032
6033     env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6034
6035     return env
6036
6037   def BuildHooksNodes(self):
6038     """Build hooks nodes.
6039
6040     """
6041     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6042     return (nl, nl)
6043
6044   def CheckPrereq(self):
6045     """Check prerequisites.
6046
6047     This checks that the instance is in the cluster.
6048
6049     """
6050     self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6051     assert self.instance is not None, \
6052       "Cannot retrieve locked instance %s" % self.op.instance_name
6053
6054     _CheckNodeOnline(self, instance.primary_node)
6055
6056     # check bridges existence
6057     _CheckInstanceBridgesExist(self, instance)
6058
6059   def Exec(self, feedback_fn):
6060     """Reboot the instance.
6061
6062     """
6063     instance = self.instance
6064     ignore_secondaries = self.op.ignore_secondaries
6065     reboot_type = self.op.reboot_type
6066
6067     remote_info = self.rpc.call_instance_info(instance.primary_node,
6068                                               instance.name,
6069                                               instance.hypervisor)
6070     remote_info.Raise("Error checking node %s" % instance.primary_node)
6071     instance_running = bool(remote_info.payload)
6072
6073     node_current = instance.primary_node
6074
6075     if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
6076                                             constants.INSTANCE_REBOOT_HARD]:
6077       for disk in instance.disks:
6078         self.cfg.SetDiskID(disk, node_current)
6079       result = self.rpc.call_instance_reboot(node_current, instance,
6080                                              reboot_type,
6081                                              self.op.shutdown_timeout)
6082       result.Raise("Could not reboot instance")
6083     else:
6084       if instance_running:
6085         result = self.rpc.call_instance_shutdown(node_current, instance,
6086                                                  self.op.shutdown_timeout)
6087         result.Raise("Could not shutdown instance for full reboot")
6088         _ShutdownInstanceDisks(self, instance)
6089       else:
6090         self.LogInfo("Instance %s was already stopped, starting now",
6091                      instance.name)
6092       _StartInstanceDisks(self, instance, ignore_secondaries)
6093       result = self.rpc.call_instance_start(node_current, instance,
6094                                             None, None, False)
6095       msg = result.fail_msg
6096       if msg:
6097         _ShutdownInstanceDisks(self, instance)
6098         raise errors.OpExecError("Could not start instance for"
6099                                  " full reboot: %s" % msg)
6100
6101     self.cfg.MarkInstanceUp(instance.name)
6102
6103
6104 class LUInstanceShutdown(LogicalUnit):
6105   """Shutdown an instance.
6106
6107   """
6108   HPATH = "instance-stop"
6109   HTYPE = constants.HTYPE_INSTANCE
6110   REQ_BGL = False
6111
6112   def ExpandNames(self):
6113     self._ExpandAndLockInstance()
6114
6115   def BuildHooksEnv(self):
6116     """Build hooks env.
6117
6118     This runs on master, primary and secondary nodes of the instance.
6119
6120     """
6121     env = _BuildInstanceHookEnvByObject(self, self.instance)
6122     env["TIMEOUT"] = self.op.timeout
6123     return env
6124
6125   def BuildHooksNodes(self):
6126     """Build hooks nodes.
6127
6128     """
6129     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6130     return (nl, nl)
6131
6132   def CheckPrereq(self):
6133     """Check prerequisites.
6134
6135     This checks that the instance is in the cluster.
6136
6137     """
6138     self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6139     assert self.instance is not None, \
6140       "Cannot retrieve locked instance %s" % self.op.instance_name
6141
6142     self.primary_offline = \
6143       self.cfg.GetNodeInfo(self.instance.primary_node).offline
6144
6145     if self.primary_offline and self.op.ignore_offline_nodes:
6146       self.proc.LogWarning("Ignoring offline primary node")
6147     else:
6148       _CheckNodeOnline(self, self.instance.primary_node)
6149
6150   def Exec(self, feedback_fn):
6151     """Shutdown the instance.
6152
6153     """
6154     instance = self.instance
6155     node_current = instance.primary_node
6156     timeout = self.op.timeout
6157
6158     if not self.op.no_remember:
6159       self.cfg.MarkInstanceDown(instance.name)
6160
6161     if self.primary_offline:
6162       assert self.op.ignore_offline_nodes
6163       self.proc.LogInfo("Primary node offline, marked instance as stopped")
6164     else:
6165       result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
6166       msg = result.fail_msg
6167       if msg:
6168         self.proc.LogWarning("Could not shutdown instance: %s" % msg)
6169
6170       _ShutdownInstanceDisks(self, instance)
6171
6172
6173 class LUInstanceReinstall(LogicalUnit):
6174   """Reinstall an instance.
6175
6176   """
6177   HPATH = "instance-reinstall"
6178   HTYPE = constants.HTYPE_INSTANCE
6179   REQ_BGL = False
6180
6181   def ExpandNames(self):
6182     self._ExpandAndLockInstance()
6183
6184   def BuildHooksEnv(self):
6185     """Build hooks env.
6186
6187     This runs on master, primary and secondary nodes of the instance.
6188
6189     """
6190     return _BuildInstanceHookEnvByObject(self, self.instance)
6191
6192   def BuildHooksNodes(self):
6193     """Build hooks nodes.
6194
6195     """
6196     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6197     return (nl, nl)
6198
6199   def CheckPrereq(self):
6200     """Check prerequisites.
6201
6202     This checks that the instance is in the cluster and is not running.
6203
6204     """
6205     instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6206     assert instance is not None, \
6207       "Cannot retrieve locked instance %s" % self.op.instance_name
6208     _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
6209                      " offline, cannot reinstall")
6210     for node in instance.secondary_nodes:
6211       _CheckNodeOnline(self, node, "Instance secondary node offline,"
6212                        " cannot reinstall")
6213
6214     if instance.disk_template == constants.DT_DISKLESS:
6215       raise errors.OpPrereqError("Instance '%s' has no disks" %
6216                                  self.op.instance_name,
6217                                  errors.ECODE_INVAL)
6218     _CheckInstanceDown(self, instance, "cannot reinstall")
6219
6220     if self.op.os_type is not None:
6221       # OS verification
6222       pnode = _ExpandNodeName(self.cfg, instance.primary_node)
6223       _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
6224       instance_os = self.op.os_type
6225     else:
6226       instance_os = instance.os
6227
6228     nodelist = list(instance.all_nodes)
6229
6230     if self.op.osparams:
6231       i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
6232       _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
6233       self.os_inst = i_osdict # the new dict (without defaults)
6234     else:
6235       self.os_inst = None
6236
6237     self.instance = instance
6238
6239   def Exec(self, feedback_fn):
6240     """Reinstall the instance.
6241
6242     """
6243     inst = self.instance
6244
6245     if self.op.os_type is not None:
6246       feedback_fn("Changing OS to '%s'..." % self.op.os_type)
6247       inst.os = self.op.os_type
6248       # Write to configuration
6249       self.cfg.Update(inst, feedback_fn)
6250
6251     _StartInstanceDisks(self, inst, None)
6252     try:
6253       feedback_fn("Running the instance OS create scripts...")
6254       # FIXME: pass debug option from opcode to backend
6255       result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
6256                                              self.op.debug_level,
6257                                              osparams=self.os_inst)
6258       result.Raise("Could not install OS for instance %s on node %s" %
6259                    (inst.name, inst.primary_node))
6260     finally:
6261       _ShutdownInstanceDisks(self, inst)
6262
6263
6264 class LUInstanceRecreateDisks(LogicalUnit):
6265   """Recreate an instance's missing disks.
6266
6267   """
6268   HPATH = "instance-recreate-disks"
6269   HTYPE = constants.HTYPE_INSTANCE
6270   REQ_BGL = False
6271
6272   def CheckArguments(self):
6273     # normalise the disk list
6274     self.op.disks = sorted(frozenset(self.op.disks))
6275
6276   def ExpandNames(self):
6277     self._ExpandAndLockInstance()
6278     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6279     if self.op.nodes:
6280       self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
6281       self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
6282     else:
6283       self.needed_locks[locking.LEVEL_NODE] = []
6284
6285   def DeclareLocks(self, level):
6286     if level == locking.LEVEL_NODE:
6287       # if we replace the nodes, we only need to lock the old primary,
6288       # otherwise we need to lock all nodes for disk re-creation
6289       primary_only = bool(self.op.nodes)
6290       self._LockInstancesNodes(primary_only=primary_only)
6291
6292   def BuildHooksEnv(self):
6293     """Build hooks env.
6294
6295     This runs on master, primary and secondary nodes of the instance.
6296
6297     """
6298     return _BuildInstanceHookEnvByObject(self, self.instance)
6299
6300   def BuildHooksNodes(self):
6301     """Build hooks nodes.
6302
6303     """
6304     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6305     return (nl, nl)
6306
6307   def CheckPrereq(self):
6308     """Check prerequisites.
6309
6310     This checks that the instance is in the cluster and is not running.
6311
6312     """
6313     instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6314     assert instance is not None, \
6315       "Cannot retrieve locked instance %s" % self.op.instance_name
6316     if self.op.nodes:
6317       if len(self.op.nodes) != len(instance.all_nodes):
6318         raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6319                                    " %d replacement nodes were specified" %
6320                                    (instance.name, len(instance.all_nodes),
6321                                     len(self.op.nodes)),
6322                                    errors.ECODE_INVAL)
6323       assert instance.disk_template != constants.DT_DRBD8 or \
6324           len(self.op.nodes) == 2
6325       assert instance.disk_template != constants.DT_PLAIN or \
6326           len(self.op.nodes) == 1
6327       primary_node = self.op.nodes[0]
6328     else:
6329       primary_node = instance.primary_node
6330     _CheckNodeOnline(self, primary_node)
6331
6332     if instance.disk_template == constants.DT_DISKLESS:
6333       raise errors.OpPrereqError("Instance '%s' has no disks" %
6334                                  self.op.instance_name, errors.ECODE_INVAL)
6335     # if we replace nodes *and* the old primary is offline, we don't
6336     # check
6337     assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
6338     old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6339     if not (self.op.nodes and old_pnode.offline):
6340       _CheckInstanceDown(self, instance, "cannot recreate disks")
6341
6342     if not self.op.disks:
6343       self.op.disks = range(len(instance.disks))
6344     else:
6345       for idx in self.op.disks:
6346         if idx >= len(instance.disks):
6347           raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6348                                      errors.ECODE_INVAL)
6349     if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6350       raise errors.OpPrereqError("Can't recreate disks partially and"
6351                                  " change the nodes at the same time",
6352                                  errors.ECODE_INVAL)
6353     self.instance = instance
6354
6355   def Exec(self, feedback_fn):
6356     """Recreate the disks.
6357
6358     """
6359     instance = self.instance
6360
6361     to_skip = []
6362     mods = [] # keeps track of needed logical_id changes
6363
6364     for idx, disk in enumerate(instance.disks):
6365       if idx not in self.op.disks: # disk idx has not been passed in
6366         to_skip.append(idx)
6367         continue
6368       # update secondaries for disks, if needed
6369       if self.op.nodes:
6370         if disk.dev_type == constants.LD_DRBD8:
6371           # need to update the nodes and minors
6372           assert len(self.op.nodes) == 2
6373           assert len(disk.logical_id) == 6 # otherwise disk internals
6374                                            # have changed
6375           (_, _, old_port, _, _, old_secret) = disk.logical_id
6376           new_minors = self.cfg.AllocateDRBDMinor(self.op.nodes, instance.name)
6377           new_id = (self.op.nodes[0], self.op.nodes[1], old_port,
6378                     new_minors[0], new_minors[1], old_secret)
6379           assert len(disk.logical_id) == len(new_id)
6380           mods.append((idx, new_id))
6381
6382     # now that we have passed all asserts above, we can apply the mods
6383     # in a single run (to avoid partial changes)
6384     for idx, new_id in mods:
6385       instance.disks[idx].logical_id = new_id
6386
6387     # change primary node, if needed
6388     if self.op.nodes:
6389       instance.primary_node = self.op.nodes[0]
6390       self.LogWarning("Changing the instance's nodes, you will have to"
6391                       " remove any disks left on the older nodes manually")
6392
6393     if self.op.nodes:
6394       self.cfg.Update(instance, feedback_fn)
6395
6396     _CreateDisks(self, instance, to_skip=to_skip)
6397
6398
6399 class LUInstanceRename(LogicalUnit):
6400   """Rename an instance.
6401
6402   """
6403   HPATH = "instance-rename"
6404   HTYPE = constants.HTYPE_INSTANCE
6405
6406   def CheckArguments(self):
6407     """Check arguments.
6408
6409     """
6410     if self.op.ip_check and not self.op.name_check:
6411       # TODO: make the ip check more flexible and not depend on the name check
6412       raise errors.OpPrereqError("IP address check requires a name check",
6413                                  errors.ECODE_INVAL)
6414
6415   def BuildHooksEnv(self):
6416     """Build hooks env.
6417
6418     This runs on master, primary and secondary nodes of the instance.
6419
6420     """
6421     env = _BuildInstanceHookEnvByObject(self, self.instance)
6422     env["INSTANCE_NEW_NAME"] = self.op.new_name
6423     return env
6424
6425   def BuildHooksNodes(self):
6426     """Build hooks nodes.
6427
6428     """
6429     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6430     return (nl, nl)
6431
6432   def CheckPrereq(self):
6433     """Check prerequisites.
6434
6435     This checks that the instance is in the cluster and is not running.
6436
6437     """
6438     self.op.instance_name = _ExpandInstanceName(self.cfg,
6439                                                 self.op.instance_name)
6440     instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6441     assert instance is not None
6442     _CheckNodeOnline(self, instance.primary_node)
6443     _CheckInstanceDown(self, instance, "cannot rename")
6444     self.instance = instance
6445
6446     new_name = self.op.new_name
6447     if self.op.name_check:
6448       hostname = netutils.GetHostname(name=new_name)
6449       if hostname.name != new_name:
6450         self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6451                      hostname.name)
6452       if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6453         raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6454                                     " same as given hostname '%s'") %
6455                                     (hostname.name, self.op.new_name),
6456                                     errors.ECODE_INVAL)
6457       new_name = self.op.new_name = hostname.name
6458       if (self.op.ip_check and
6459           netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6460         raise errors.OpPrereqError("IP %s of instance %s already in use" %
6461                                    (hostname.ip, new_name),
6462                                    errors.ECODE_NOTUNIQUE)
6463
6464     instance_list = self.cfg.GetInstanceList()
6465     if new_name in instance_list and new_name != instance.name:
6466       raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6467                                  new_name, errors.ECODE_EXISTS)
6468
6469   def Exec(self, feedback_fn):
6470     """Rename the instance.
6471
6472     """
6473     inst = self.instance
6474     old_name = inst.name
6475
6476     rename_file_storage = False
6477     if (inst.disk_template in constants.DTS_FILEBASED and
6478         self.op.new_name != inst.name):
6479       old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6480       rename_file_storage = True
6481
6482     self.cfg.RenameInstance(inst.name, self.op.new_name)
6483     # Change the instance lock. This is definitely safe while we hold the BGL.
6484     # Otherwise the new lock would have to be added in acquired mode.
6485     assert self.REQ_BGL
6486     self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6487     self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6488
6489     # re-read the instance from the configuration after rename
6490     inst = self.cfg.GetInstanceInfo(self.op.new_name)
6491
6492     if rename_file_storage:
6493       new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6494       result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6495                                                      old_file_storage_dir,
6496                                                      new_file_storage_dir)
6497       result.Raise("Could not rename on node %s directory '%s' to '%s'"
6498                    " (but the instance has been renamed in Ganeti)" %
6499                    (inst.primary_node, old_file_storage_dir,
6500                     new_file_storage_dir))
6501
6502     _StartInstanceDisks(self, inst, None)
6503     try:
6504       result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6505                                                  old_name, self.op.debug_level)
6506       msg = result.fail_msg
6507       if msg:
6508         msg = ("Could not run OS rename script for instance %s on node %s"
6509                " (but the instance has been renamed in Ganeti): %s" %
6510                (inst.name, inst.primary_node, msg))
6511         self.proc.LogWarning(msg)
6512     finally:
6513       _ShutdownInstanceDisks(self, inst)
6514
6515     return inst.name
6516
6517
6518 class LUInstanceRemove(LogicalUnit):
6519   """Remove an instance.
6520
6521   """
6522   HPATH = "instance-remove"
6523   HTYPE = constants.HTYPE_INSTANCE
6524   REQ_BGL = False
6525
6526   def ExpandNames(self):
6527     self._ExpandAndLockInstance()
6528     self.needed_locks[locking.LEVEL_NODE] = []
6529     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6530
6531   def DeclareLocks(self, level):
6532     if level == locking.LEVEL_NODE:
6533       self._LockInstancesNodes()
6534
6535   def BuildHooksEnv(self):
6536     """Build hooks env.
6537
6538     This runs on master, primary and secondary nodes of the instance.
6539
6540     """
6541     env = _BuildInstanceHookEnvByObject(self, self.instance)
6542     env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6543     return env
6544
6545   def BuildHooksNodes(self):
6546     """Build hooks nodes.
6547
6548     """
6549     nl = [self.cfg.GetMasterNode()]
6550     nl_post = list(self.instance.all_nodes) + nl
6551     return (nl, nl_post)
6552
6553   def CheckPrereq(self):
6554     """Check prerequisites.
6555
6556     This checks that the instance is in the cluster.
6557
6558     """
6559     self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6560     assert self.instance is not None, \
6561       "Cannot retrieve locked instance %s" % self.op.instance_name
6562
6563   def Exec(self, feedback_fn):
6564     """Remove the instance.
6565
6566     """
6567     instance = self.instance
6568     logging.info("Shutting down instance %s on node %s",
6569                  instance.name, instance.primary_node)
6570
6571     result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6572                                              self.op.shutdown_timeout)
6573     msg = result.fail_msg
6574     if msg:
6575       if self.op.ignore_failures:
6576         feedback_fn("Warning: can't shutdown instance: %s" % msg)
6577       else:
6578         raise errors.OpExecError("Could not shutdown instance %s on"
6579                                  " node %s: %s" %
6580                                  (instance.name, instance.primary_node, msg))
6581
6582     _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6583
6584
6585 def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6586   """Utility function to remove an instance.
6587
6588   """
6589   logging.info("Removing block devices for instance %s", instance.name)
6590
6591   if not _RemoveDisks(lu, instance):
6592     if not ignore_failures:
6593       raise errors.OpExecError("Can't remove instance's disks")
6594     feedback_fn("Warning: can't remove instance's disks")
6595
6596   logging.info("Removing instance %s out of cluster config", instance.name)
6597
6598   lu.cfg.RemoveInstance(instance.name)
6599
6600   assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6601     "Instance lock removal conflict"
6602
6603   # Remove lock for the instance
6604   lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6605
6606
6607 class LUInstanceQuery(NoHooksLU):
6608   """Logical unit for querying instances.
6609
6610   """
6611   # pylint: disable=W0142
6612   REQ_BGL = False
6613
6614   def CheckArguments(self):
6615     self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6616                              self.op.output_fields, self.op.use_locking)
6617
6618   def ExpandNames(self):
6619     self.iq.ExpandNames(self)
6620
6621   def DeclareLocks(self, level):
6622     self.iq.DeclareLocks(self, level)
6623
6624   def Exec(self, feedback_fn):
6625     return self.iq.OldStyleQuery(self)
6626
6627
6628 class LUInstanceFailover(LogicalUnit):
6629   """Failover an instance.
6630
6631   """
6632   HPATH = "instance-failover"
6633   HTYPE = constants.HTYPE_INSTANCE
6634   REQ_BGL = False
6635
6636   def CheckArguments(self):
6637     """Check the arguments.
6638
6639     """
6640     self.iallocator = getattr(self.op, "iallocator", None)
6641     self.target_node = getattr(self.op, "target_node", None)
6642
6643   def ExpandNames(self):
6644     self._ExpandAndLockInstance()
6645
6646     if self.op.target_node is not None:
6647       self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6648
6649     self.needed_locks[locking.LEVEL_NODE] = []
6650     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6651
6652     ignore_consistency = self.op.ignore_consistency
6653     shutdown_timeout = self.op.shutdown_timeout
6654     self._migrater = TLMigrateInstance(self, self.op.instance_name,
6655                                        cleanup=False,
6656                                        failover=True,
6657                                        ignore_consistency=ignore_consistency,
6658                                        shutdown_timeout=shutdown_timeout)
6659     self.tasklets = [self._migrater]
6660
6661   def DeclareLocks(self, level):
6662     if level == locking.LEVEL_NODE:
6663       instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6664       if instance.disk_template in constants.DTS_EXT_MIRROR:
6665         if self.op.target_node is None:
6666           self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6667         else:
6668           self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6669                                                    self.op.target_node]
6670         del self.recalculate_locks[locking.LEVEL_NODE]
6671       else:
6672         self._LockInstancesNodes()
6673
6674   def BuildHooksEnv(self):
6675     """Build hooks env.
6676
6677     This runs on master, primary and secondary nodes of the instance.
6678
6679     """
6680     instance = self._migrater.instance
6681     source_node = instance.primary_node
6682     target_node = self.op.target_node
6683     env = {
6684       "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6685       "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6686       "OLD_PRIMARY": source_node,
6687       "NEW_PRIMARY": target_node,
6688       }
6689
6690     if instance.disk_template in constants.DTS_INT_MIRROR:
6691       env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6692       env["NEW_SECONDARY"] = source_node
6693     else:
6694       env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6695
6696     env.update(_BuildInstanceHookEnvByObject(self, instance))
6697
6698     return env
6699
6700   def BuildHooksNodes(self):
6701     """Build hooks nodes.
6702
6703     """
6704     instance = self._migrater.instance
6705     nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6706     return (nl, nl + [instance.primary_node])
6707
6708
6709 class LUInstanceMigrate(LogicalUnit):
6710   """Migrate an instance.
6711
6712   This is migration without shutting down, compared to the failover,
6713   which is done with shutdown.
6714
6715   """
6716   HPATH = "instance-migrate"
6717   HTYPE = constants.HTYPE_INSTANCE
6718   REQ_BGL = False
6719
6720   def ExpandNames(self):
6721     self._ExpandAndLockInstance()
6722
6723     if self.op.target_node is not None:
6724       self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6725
6726     self.needed_locks[locking.LEVEL_NODE] = []
6727     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6728
6729     self._migrater = TLMigrateInstance(self, self.op.instance_name,
6730                                        cleanup=self.op.cleanup,
6731                                        failover=False,
6732                                        fallback=self.op.allow_failover)
6733     self.tasklets = [self._migrater]
6734
6735   def DeclareLocks(self, level):
6736     if level == locking.LEVEL_NODE:
6737       instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6738       if instance.disk_template in constants.DTS_EXT_MIRROR:
6739         if self.op.target_node is None:
6740           self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6741         else:
6742           self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6743                                                    self.op.target_node]
6744         del self.recalculate_locks[locking.LEVEL_NODE]
6745       else:
6746         self._LockInstancesNodes()
6747
6748   def BuildHooksEnv(self):
6749     """Build hooks env.
6750
6751     This runs on master, primary and secondary nodes of the instance.
6752
6753     """
6754     instance = self._migrater.instance
6755     source_node = instance.primary_node
6756     target_node = self.op.target_node
6757     env = _BuildInstanceHookEnvByObject(self, instance)
6758     env.update({
6759       "MIGRATE_LIVE": self._migrater.live,
6760       "MIGRATE_CLEANUP": self.op.cleanup,
6761       "OLD_PRIMARY": source_node,
6762       "NEW_PRIMARY": target_node,
6763       })
6764
6765     if instance.disk_template in constants.DTS_INT_MIRROR:
6766       env["OLD_SECONDARY"] = target_node
6767       env["NEW_SECONDARY"] = source_node
6768     else:
6769       env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6770
6771     return env
6772
6773   def BuildHooksNodes(self):
6774     """Build hooks nodes.
6775
6776     """
6777     instance = self._migrater.instance
6778     nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6779     return (nl, nl + [instance.primary_node])
6780
6781
6782 class LUInstanceMove(LogicalUnit):
6783   """Move an instance by data-copying.
6784
6785   """
6786   HPATH = "instance-move"
6787   HTYPE = constants.HTYPE_INSTANCE
6788   REQ_BGL = False
6789
6790   def ExpandNames(self):
6791     self._ExpandAndLockInstance()
6792     target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6793     self.op.target_node = target_node
6794     self.needed_locks[locking.LEVEL_NODE] = [target_node]
6795     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6796
6797   def DeclareLocks(self, level):
6798     if level == locking.LEVEL_NODE:
6799       self._LockInstancesNodes(primary_only=True)
6800
6801   def BuildHooksEnv(self):
6802     """Build hooks env.
6803
6804     This runs on master, primary and secondary nodes of the instance.
6805
6806     """
6807     env = {
6808       "TARGET_NODE": self.op.target_node,
6809       "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6810       }
6811     env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6812     return env
6813
6814   def BuildHooksNodes(self):
6815     """Build hooks nodes.
6816
6817     """
6818     nl = [
6819       self.cfg.GetMasterNode(),
6820       self.instance.primary_node,
6821       self.op.target_node,
6822       ]
6823     return (nl, nl)
6824
6825   def CheckPrereq(self):
6826     """Check prerequisites.
6827
6828     This checks that the instance is in the cluster.
6829
6830     """
6831     self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6832     assert self.instance is not None, \
6833       "Cannot retrieve locked instance %s" % self.op.instance_name
6834
6835     node = self.cfg.GetNodeInfo(self.op.target_node)
6836     assert node is not None, \
6837       "Cannot retrieve locked node %s" % self.op.target_node
6838
6839     self.target_node = target_node = node.name
6840
6841     if target_node == instance.primary_node:
6842       raise errors.OpPrereqError("Instance %s is already on the node %s" %
6843                                  (instance.name, target_node),
6844                                  errors.ECODE_STATE)
6845
6846     bep = self.cfg.GetClusterInfo().FillBE(instance)
6847
6848     for idx, dsk in enumerate(instance.disks):
6849       if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6850         raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6851                                    " cannot copy" % idx, errors.ECODE_STATE)
6852
6853     _CheckNodeOnline(self, target_node)
6854     _CheckNodeNotDrained(self, target_node)
6855     _CheckNodeVmCapable(self, target_node)
6856
6857     if instance.admin_up:
6858       # check memory requirements on the secondary node
6859       _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6860                            instance.name, bep[constants.BE_MEMORY],
6861                            instance.hypervisor)
6862     else:
6863       self.LogInfo("Not checking memory on the secondary node as"
6864                    " instance will not be started")
6865
6866     # check bridge existance
6867     _CheckInstanceBridgesExist(self, instance, node=target_node)
6868
6869   def Exec(self, feedback_fn):
6870     """Move an instance.
6871
6872     The move is done by shutting it down on its present node, copying
6873     the data over (slow) and starting it on the new node.
6874
6875     """
6876     instance = self.instance
6877
6878     source_node = instance.primary_node
6879     target_node = self.target_node
6880
6881     self.LogInfo("Shutting down instance %s on source node %s",
6882                  instance.name, source_node)
6883
6884     result = self.rpc.call_instance_shutdown(source_node, instance,
6885                                              self.op.shutdown_timeout)
6886     msg = result.fail_msg
6887     if msg:
6888       if self.op.ignore_consistency:
6889         self.proc.LogWarning("Could not shutdown instance %s on node %s."
6890                              " Proceeding anyway. Please make sure node"
6891                              " %s is down. Error details: %s",
6892                              instance.name, source_node, source_node, msg)
6893       else:
6894         raise errors.OpExecError("Could not shutdown instance %s on"
6895                                  " node %s: %s" %
6896                                  (instance.name, source_node, msg))
6897
6898     # create the target disks
6899     try:
6900       _CreateDisks(self, instance, target_node=target_node)
6901     except errors.OpExecError:
6902       self.LogWarning("Device creation failed, reverting...")
6903       try:
6904         _RemoveDisks(self, instance, target_node=target_node)
6905       finally:
6906         self.cfg.ReleaseDRBDMinors(instance.name)
6907         raise
6908
6909     cluster_name = self.cfg.GetClusterInfo().cluster_name
6910
6911     errs = []
6912     # activate, get path, copy the data over
6913     for idx, disk in enumerate(instance.disks):
6914       self.LogInfo("Copying data for disk %d", idx)
6915       result = self.rpc.call_blockdev_assemble(target_node, disk,
6916                                                instance.name, True, idx)
6917       if result.fail_msg:
6918         self.LogWarning("Can't assemble newly created disk %d: %s",
6919                         idx, result.fail_msg)
6920         errs.append(result.fail_msg)
6921         break
6922       dev_path = result.payload
6923       result = self.rpc.call_blockdev_export(source_node, disk,
6924                                              target_node, dev_path,
6925                                              cluster_name)
6926       if result.fail_msg:
6927         self.LogWarning("Can't copy data over for disk %d: %s",
6928                         idx, result.fail_msg)
6929         errs.append(result.fail_msg)
6930         break
6931
6932     if errs:
6933       self.LogWarning("Some disks failed to copy, aborting")
6934       try:
6935         _RemoveDisks(self, instance, target_node=target_node)
6936       finally:
6937         self.cfg.ReleaseDRBDMinors(instance.name)
6938         raise errors.OpExecError("Errors during disk copy: %s" %
6939                                  (",".join(errs),))
6940
6941     instance.primary_node = target_node
6942     self.cfg.Update(instance, feedback_fn)
6943
6944     self.LogInfo("Removing the disks on the original node")
6945     _RemoveDisks(self, instance, target_node=source_node)
6946
6947     # Only start the instance if it's marked as up
6948     if instance.admin_up:
6949       self.LogInfo("Starting instance %s on node %s",
6950                    instance.name, target_node)
6951
6952       disks_ok, _ = _AssembleInstanceDisks(self, instance,
6953                                            ignore_secondaries=True)
6954       if not disks_ok:
6955         _ShutdownInstanceDisks(self, instance)
6956         raise errors.OpExecError("Can't activate the instance's disks")
6957
6958       result = self.rpc.call_instance_start(target_node, instance,
6959                                             None, None, False)
6960       msg = result.fail_msg
6961       if msg:
6962         _ShutdownInstanceDisks(self, instance)
6963         raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6964                                  (instance.name, target_node, msg))
6965
6966
6967 class LUNodeMigrate(LogicalUnit):
6968   """Migrate all instances from a node.
6969
6970   """
6971   HPATH = "node-migrate"
6972   HTYPE = constants.HTYPE_NODE
6973   REQ_BGL = False
6974
6975   def CheckArguments(self):
6976     pass
6977
6978   def ExpandNames(self):
6979     self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6980
6981     self.share_locks = _ShareAll()
6982     self.needed_locks = {
6983       locking.LEVEL_NODE: [self.op.node_name],
6984       }
6985
6986   def BuildHooksEnv(self):
6987     """Build hooks env.
6988
6989     This runs on the master, the primary and all the secondaries.
6990
6991     """
6992     return {
6993       "NODE_NAME": self.op.node_name,
6994       }
6995
6996   def BuildHooksNodes(self):
6997     """Build hooks nodes.
6998
6999     """
7000     nl = [self.cfg.GetMasterNode()]
7001     return (nl, nl)
7002
7003   def CheckPrereq(self):
7004     pass
7005
7006   def Exec(self, feedback_fn):
7007     # Prepare jobs for migration instances
7008     jobs = [
7009       [opcodes.OpInstanceMigrate(instance_name=inst.name,
7010                                  mode=self.op.mode,
7011                                  live=self.op.live,
7012                                  iallocator=self.op.iallocator,
7013                                  target_node=self.op.target_node)]
7014       for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name)
7015       ]
7016
7017     # TODO: Run iallocator in this opcode and pass correct placement options to
7018     # OpInstanceMigrate. Since other jobs can modify the cluster between
7019     # running the iallocator and the actual migration, a good consistency model
7020     # will have to be found.
7021
7022     assert (frozenset(self.owned_locks(locking.LEVEL_NODE)) ==
7023             frozenset([self.op.node_name]))
7024
7025     return ResultWithJobs(jobs)
7026
7027
7028 class TLMigrateInstance(Tasklet):
7029   """Tasklet class for instance migration.
7030
7031   @type live: boolean
7032   @ivar live: whether the migration will be done live or non-live;
7033       this variable is initalized only after CheckPrereq has run
7034   @type cleanup: boolean
7035   @ivar cleanup: Wheater we cleanup from a failed migration
7036   @type iallocator: string
7037   @ivar iallocator: The iallocator used to determine target_node
7038   @type target_node: string
7039   @ivar target_node: If given, the target_node to reallocate the instance to
7040   @type failover: boolean
7041   @ivar failover: Whether operation results in failover or migration
7042   @type fallback: boolean
7043   @ivar fallback: Whether fallback to failover is allowed if migration not
7044                   possible
7045   @type ignore_consistency: boolean
7046   @ivar ignore_consistency: Wheter we should ignore consistency between source
7047                             and target node
7048   @type shutdown_timeout: int
7049   @ivar shutdown_timeout: In case of failover timeout of the shutdown
7050
7051   """
7052   def __init__(self, lu, instance_name, cleanup=False,
7053                failover=False, fallback=False,
7054                ignore_consistency=False,
7055                shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
7056     """Initializes this class.
7057
7058     """
7059     Tasklet.__init__(self, lu)
7060
7061     # Parameters
7062     self.instance_name = instance_name
7063     self.cleanup = cleanup
7064     self.live = False # will be overridden later
7065     self.failover = failover
7066     self.fallback = fallback
7067     self.ignore_consistency = ignore_consistency
7068     self.shutdown_timeout = shutdown_timeout
7069
7070   def CheckPrereq(self):
7071     """Check prerequisites.
7072
7073     This checks that the instance is in the cluster.
7074
7075     """
7076     instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
7077     instance = self.cfg.GetInstanceInfo(instance_name)
7078     assert instance is not None
7079     self.instance = instance
7080
7081     if (not self.cleanup and not instance.admin_up and not self.failover and
7082         self.fallback):
7083       self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
7084                       " to failover")
7085       self.failover = True
7086
7087     if instance.disk_template not in constants.DTS_MIRRORED:
7088       if self.failover:
7089         text = "failovers"
7090       else:
7091         text = "migrations"
7092       raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
7093                                  " %s" % (instance.disk_template, text),
7094                                  errors.ECODE_STATE)
7095
7096     if instance.disk_template in constants.DTS_EXT_MIRROR:
7097       _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
7098
7099       if self.lu.op.iallocator:
7100         self._RunAllocator()
7101       else:
7102         # We set set self.target_node as it is required by
7103         # BuildHooksEnv
7104         self.target_node = self.lu.op.target_node
7105
7106       # self.target_node is already populated, either directly or by the
7107       # iallocator run
7108       target_node = self.target_node
7109       if self.target_node == instance.primary_node:
7110         raise errors.OpPrereqError("Cannot migrate instance %s"
7111                                    " to its primary (%s)" %
7112                                    (instance.name, instance.primary_node))
7113
7114       if len(self.lu.tasklets) == 1:
7115         # It is safe to release locks only when we're the only tasklet
7116         # in the LU
7117         _ReleaseLocks(self.lu, locking.LEVEL_NODE,
7118                       keep=[instance.primary_node, self.target_node])
7119
7120     else:
7121       secondary_nodes = instance.secondary_nodes
7122       if not secondary_nodes:
7123         raise errors.ConfigurationError("No secondary node but using"
7124                                         " %s disk template" %
7125                                         instance.disk_template)
7126       target_node = secondary_nodes[0]
7127       if self.lu.op.iallocator or (self.lu.op.target_node and
7128                                    self.lu.op.target_node != target_node):
7129         if self.failover:
7130           text = "failed over"
7131         else:
7132           text = "migrated"
7133         raise errors.OpPrereqError("Instances with disk template %s cannot"
7134                                    " be %s to arbitrary nodes"
7135                                    " (neither an iallocator nor a target"
7136                                    " node can be passed)" %
7137                                    (instance.disk_template, text),
7138                                    errors.ECODE_INVAL)
7139
7140     i_be = self.cfg.GetClusterInfo().FillBE(instance)
7141
7142     # check memory requirements on the secondary node
7143     if not self.cleanup and (not self.failover or instance.admin_up):
7144       _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
7145                            instance.name, i_be[constants.BE_MEMORY],
7146                            instance.hypervisor)
7147     else:
7148       self.lu.LogInfo("Not checking memory on the secondary node as"
7149                       " instance will not be started")
7150
7151     # check bridge existance
7152     _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
7153
7154     if not self.cleanup:
7155       _CheckNodeNotDrained(self.lu, target_node)
7156       if not self.failover:
7157         result = self.rpc.call_instance_migratable(instance.primary_node,
7158                                                    instance)
7159         if result.fail_msg and self.fallback:
7160           self.lu.LogInfo("Can't migrate, instance offline, fallback to"
7161                           " failover")
7162           self.failover = True
7163         else:
7164           result.Raise("Can't migrate, please use failover",
7165                        prereq=True, ecode=errors.ECODE_STATE)
7166
7167     assert not (self.failover and self.cleanup)
7168
7169     if not self.failover:
7170       if self.lu.op.live is not None and self.lu.op.mode is not None:
7171         raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
7172                                    " parameters are accepted",
7173                                    errors.ECODE_INVAL)
7174       if self.lu.op.live is not None:
7175         if self.lu.op.live:
7176           self.lu.op.mode = constants.HT_MIGRATION_LIVE
7177         else:
7178           self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
7179         # reset the 'live' parameter to None so that repeated
7180         # invocations of CheckPrereq do not raise an exception
7181         self.lu.op.live = None
7182       elif self.lu.op.mode is None:
7183         # read the default value from the hypervisor
7184         i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
7185                                                 skip_globals=False)
7186         self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
7187
7188       self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
7189     else:
7190       # Failover is never live
7191       self.live = False
7192
7193   def _RunAllocator(self):
7194     """Run the allocator based on input opcode.
7195
7196     """
7197     ial = IAllocator(self.cfg, self.rpc,
7198                      mode=constants.IALLOCATOR_MODE_RELOC,
7199                      name=self.instance_name,
7200                      # TODO See why hail breaks with a single node below
7201                      relocate_from=[self.instance.primary_node,
7202                                     self.instance.primary_node],
7203                      )
7204
7205     ial.Run(self.lu.op.iallocator)
7206
7207     if not ial.success:
7208       raise errors.OpPrereqError("Can't compute nodes using"
7209                                  " iallocator '%s': %s" %
7210                                  (self.lu.op.iallocator, ial.info),
7211                                  errors.ECODE_NORES)
7212     if len(ial.result) != ial.required_nodes:
7213       raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7214                                  " of nodes (%s), required %s" %
7215                                  (self.lu.op.iallocator, len(ial.result),
7216                                   ial.required_nodes), errors.ECODE_FAULT)
7217     self.target_node = ial.result[0]
7218     self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7219                  self.instance_name, self.lu.op.iallocator,
7220                  utils.CommaJoin(ial.result))
7221
7222   def _WaitUntilSync(self):
7223     """Poll with custom rpc for disk sync.
7224
7225     This uses our own step-based rpc call.
7226
7227     """
7228     self.feedback_fn("* wait until resync is done")
7229     all_done = False
7230     while not all_done:
7231       all_done = True
7232       result = self.rpc.call_drbd_wait_sync(self.all_nodes,
7233                                             self.nodes_ip,
7234                                             self.instance.disks)
7235       min_percent = 100
7236       for node, nres in result.items():
7237         nres.Raise("Cannot resync disks on node %s" % node)
7238         node_done, node_percent = nres.payload
7239         all_done = all_done and node_done
7240         if node_percent is not None:
7241           min_percent = min(min_percent, node_percent)
7242       if not all_done:
7243         if min_percent < 100:
7244           self.feedback_fn("   - progress: %.1f%%" % min_percent)
7245         time.sleep(2)
7246
7247   def _EnsureSecondary(self, node):
7248     """Demote a node to secondary.
7249
7250     """
7251     self.feedback_fn("* switching node %s to secondary mode" % node)
7252
7253     for dev in self.instance.disks:
7254       self.cfg.SetDiskID(dev, node)
7255
7256     result = self.rpc.call_blockdev_close(node, self.instance.name,
7257                                           self.instance.disks)
7258     result.Raise("Cannot change disk to secondary on node %s" % node)
7259
7260   def _GoStandalone(self):
7261     """Disconnect from the network.
7262
7263     """
7264     self.feedback_fn("* changing into standalone mode")
7265     result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
7266                                                self.instance.disks)
7267     for node, nres in result.items():
7268       nres.Raise("Cannot disconnect disks node %s" % node)
7269
7270   def _GoReconnect(self, multimaster):
7271     """Reconnect to the network.
7272
7273     """
7274     if multimaster:
7275       msg = "dual-master"
7276     else:
7277       msg = "single-master"
7278     self.feedback_fn("* changing disks into %s mode" % msg)
7279     result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
7280                                            self.instance.disks,
7281                                            self.instance.name, multimaster)
7282     for node, nres in result.items():
7283       nres.Raise("Cannot change disks config on node %s" % node)
7284
7285   def _ExecCleanup(self):
7286     """Try to cleanup after a failed migration.
7287
7288     The cleanup is done by:
7289       - check that the instance is running only on one node
7290         (and update the config if needed)
7291       - change disks on its secondary node to secondary
7292       - wait until disks are fully synchronized
7293       - disconnect from the network
7294       - change disks into single-master mode
7295       - wait again until disks are fully synchronized
7296
7297     """
7298     instance = self.instance
7299     target_node = self.target_node
7300     source_node = self.source_node
7301
7302     # check running on only one node
7303     self.feedback_fn("* checking where the instance actually runs"
7304                      " (if this hangs, the hypervisor might be in"
7305                      " a bad state)")
7306     ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
7307     for node, result in ins_l.items():
7308       result.Raise("Can't contact node %s" % node)
7309
7310     runningon_source = instance.name in ins_l[source_node].payload
7311     runningon_target = instance.name in ins_l[target_node].payload
7312
7313     if runningon_source and runningon_target:
7314       raise errors.OpExecError("Instance seems to be running on two nodes,"
7315                                " or the hypervisor is confused; you will have"
7316                                " to ensure manually that it runs only on one"
7317                                " and restart this operation")
7318
7319     if not (runningon_source or runningon_target):
7320       raise errors.OpExecError("Instance does not seem to be running at all;"
7321                                " in this case it's safer to repair by"
7322                                " running 'gnt-instance stop' to ensure disk"
7323                                " shutdown, and then restarting it")
7324
7325     if runningon_target:
7326       # the migration has actually succeeded, we need to update the config
7327       self.feedback_fn("* instance running on secondary node (%s),"
7328                        " updating config" % target_node)
7329       instance.primary_node = target_node
7330       self.cfg.Update(instance, self.feedback_fn)
7331       demoted_node = source_node
7332     else:
7333       self.feedback_fn("* instance confirmed to be running on its"
7334                        " primary node (%s)" % source_node)
7335       demoted_node = target_node
7336
7337     if instance.disk_template in constants.DTS_INT_MIRROR:
7338       self._EnsureSecondary(demoted_node)
7339       try:
7340         self._WaitUntilSync()
7341       except errors.OpExecError:
7342         # we ignore here errors, since if the device is standalone, it
7343         # won't be able to sync
7344         pass
7345       self._GoStandalone()
7346       self._GoReconnect(False)
7347       self._WaitUntilSync()
7348
7349     self.feedback_fn("* done")
7350
7351   def _RevertDiskStatus(self):
7352     """Try to revert the disk status after a failed migration.
7353
7354     """
7355     target_node = self.target_node
7356     if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7357       return
7358
7359     try:
7360       self._EnsureSecondary(target_node)
7361       self._GoStandalone()
7362       self._GoReconnect(False)
7363       self._WaitUntilSync()
7364     except errors.OpExecError, err:
7365       self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7366                          " please try to recover the instance manually;"
7367                          " error '%s'" % str(err))
7368
7369   def _AbortMigration(self):
7370     """Call the hypervisor code to abort a started migration.
7371
7372     """
7373     instance = self.instance
7374     target_node = self.target_node
7375     migration_info = self.migration_info
7376
7377     abort_result = self.rpc.call_finalize_migration(target_node,
7378                                                     instance,
7379                                                     migration_info,
7380                                                     False)
7381     abort_msg = abort_result.fail_msg
7382     if abort_msg:
7383       logging.error("Aborting migration failed on target node %s: %s",
7384                     target_node, abort_msg)
7385       # Don't raise an exception here, as we stil have to try to revert the
7386       # disk status, even if this step failed.
7387
7388   def _ExecMigration(self):
7389     """Migrate an instance.
7390
7391     The migrate is done by:
7392       - change the disks into dual-master mode
7393       - wait until disks are fully synchronized again
7394       - migrate the instance
7395       - change disks on the new secondary node (the old primary) to secondary
7396       - wait until disks are fully synchronized
7397       - change disks into single-master mode
7398
7399     """
7400     instance = self.instance
7401     target_node = self.target_node
7402     source_node = self.source_node
7403
7404     self.feedback_fn("* checking disk consistency between source and target")
7405     for dev in instance.disks:
7406       if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7407         raise errors.OpExecError("Disk %s is degraded or not fully"
7408                                  " synchronized on target node,"
7409                                  " aborting migration" % dev.iv_name)
7410
7411     # First get the migration information from the remote node
7412     result = self.rpc.call_migration_info(source_node, instance)
7413     msg = result.fail_msg
7414     if msg:
7415       log_err = ("Failed fetching source migration information from %s: %s" %
7416                  (source_node, msg))
7417       logging.error(log_err)
7418       raise errors.OpExecError(log_err)
7419
7420     self.migration_info = migration_info = result.payload
7421
7422     if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7423       # Then switch the disks to master/master mode
7424       self._EnsureSecondary(target_node)
7425       self._GoStandalone()
7426       self._GoReconnect(True)
7427       self._WaitUntilSync()
7428
7429     self.feedback_fn("* preparing %s to accept the instance" % target_node)
7430     result = self.rpc.call_accept_instance(target_node,
7431                                            instance,
7432                                            migration_info,
7433                                            self.nodes_ip[target_node])
7434
7435     msg = result.fail_msg
7436     if msg:
7437       logging.error("Instance pre-migration failed, trying to revert"
7438                     " disk status: %s", msg)
7439       self.feedback_fn("Pre-migration failed, aborting")
7440       self._AbortMigration()
7441       self._RevertDiskStatus()
7442       raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7443                                (instance.name, msg))
7444
7445     self.feedback_fn("* migrating instance to %s" % target_node)
7446     result = self.rpc.call_instance_migrate(source_node, instance,
7447                                             self.nodes_ip[target_node],
7448                                             self.live)
7449     msg = result.fail_msg
7450     if msg:
7451       logging.error("Instance migration failed, trying to revert"
7452                     " disk status: %s", msg)
7453       self.feedback_fn("Migration failed, aborting")
7454       self._AbortMigration()
7455       self._RevertDiskStatus()
7456       raise errors.OpExecError("Could not migrate instance %s: %s" %
7457                                (instance.name, msg))
7458
7459     instance.primary_node = target_node
7460     # distribute new instance config to the other nodes
7461     self.cfg.Update(instance, self.feedback_fn)
7462
7463     result = self.rpc.call_finalize_migration(target_node,
7464                                               instance,
7465                                               migration_info,
7466                                               True)
7467     msg = result.fail_msg
7468     if msg:
7469       logging.error("Instance migration succeeded, but finalization failed:"
7470                     " %s", msg)
7471       raise errors.OpExecError("Could not finalize instance migration: %s" %
7472                                msg)
7473
7474     if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7475       self._EnsureSecondary(source_node)
7476       self._WaitUntilSync()
7477       self._GoStandalone()
7478       self._GoReconnect(False)
7479       self._WaitUntilSync()
7480
7481     self.feedback_fn("* done")
7482
7483   def _ExecFailover(self):
7484     """Failover an instance.
7485
7486     The failover is done by shutting it down on its present node and
7487     starting it on the secondary.
7488
7489     """
7490     instance = self.instance
7491     primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7492
7493     source_node = instance.primary_node
7494     target_node = self.target_node
7495
7496     if instance.admin_up:
7497       self.feedback_fn("* checking disk consistency between source and target")
7498       for dev in instance.disks:
7499         # for drbd, these are drbd over lvm
7500         if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7501           if primary_node.offline:
7502             self.feedback_fn("Node %s is offline, ignoring degraded disk %s on"
7503                              " target node %s" %
7504                              (primary_node.name, dev.iv_name, target_node))
7505           elif not self.ignore_consistency:
7506             raise errors.OpExecError("Disk %s is degraded on target node,"
7507                                      " aborting failover" % dev.iv_name)
7508     else:
7509       self.feedback_fn("* not checking disk consistency as instance is not"
7510                        " running")
7511
7512     self.feedback_fn("* shutting down instance on source node")
7513     logging.info("Shutting down instance %s on node %s",
7514                  instance.name, source_node)
7515
7516     result = self.rpc.call_instance_shutdown(source_node, instance,
7517                                              self.shutdown_timeout)
7518     msg = result.fail_msg
7519     if msg:
7520       if self.ignore_consistency or primary_node.offline:
7521         self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7522                            " proceeding anyway; please make sure node"
7523                            " %s is down; error details: %s",
7524                            instance.name, source_node, source_node, msg)
7525       else:
7526         raise errors.OpExecError("Could not shutdown instance %s on"
7527                                  " node %s: %s" %
7528                                  (instance.name, source_node, msg))
7529
7530     self.feedback_fn("* deactivating the instance's disks on source node")
7531     if not _ShutdownInstanceDisks(self.lu, instance, ignore_primary=True):
7532       raise errors.OpExecError("Can't shut down the instance's disks")
7533
7534     instance.primary_node = target_node
7535     # distribute new instance config to the other nodes
7536     self.cfg.Update(instance, self.feedback_fn)
7537
7538     # Only start the instance if it's marked as up
7539     if instance.admin_up:
7540       self.feedback_fn("* activating the instance's disks on target node %s" %
7541                        target_node)
7542       logging.info("Starting instance %s on node %s",
7543                    instance.name, target_node)
7544
7545       disks_ok, _ = _AssembleInstanceDisks(self.lu, instance,
7546                                            ignore_secondaries=True)
7547       if not disks_ok:
7548         _ShutdownInstanceDisks(self.lu, instance)
7549         raise errors.OpExecError("Can't activate the instance's disks")
7550
7551       self.feedback_fn("* starting the instance on the target node %s" %
7552                        target_node)
7553       result = self.rpc.call_instance_start(target_node, instance, None, None,
7554                                             False)
7555       msg = result.fail_msg
7556       if msg:
7557         _ShutdownInstanceDisks(self.lu, instance)
7558         raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7559                                  (instance.name, target_node, msg))
7560
7561   def Exec(self, feedback_fn):
7562     """Perform the migration.
7563
7564     """
7565     self.feedback_fn = feedback_fn
7566     self.source_node = self.instance.primary_node
7567
7568     # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7569     if self.instance.disk_template in constants.DTS_INT_MIRROR:
7570       self.target_node = self.instance.secondary_nodes[0]
7571       # Otherwise self.target_node has been populated either
7572       # directly, or through an iallocator.
7573
7574     self.all_nodes = [self.source_node, self.target_node]
7575     self.nodes_ip = dict((name, node.secondary_ip) for (name, node)
7576                          in self.cfg.GetMultiNodeInfo(self.all_nodes))
7577
7578     if self.failover:
7579       feedback_fn("Failover instance %s" % self.instance.name)
7580       self._ExecFailover()
7581     else:
7582       feedback_fn("Migrating instance %s" % self.instance.name)
7583
7584       if self.cleanup:
7585         return self._ExecCleanup()
7586       else:
7587         return self._ExecMigration()
7588
7589
7590 def _CreateBlockDev(lu, node, instance, device, force_create,
7591                     info, force_open):
7592   """Create a tree of block devices on a given node.
7593
7594   If this device type has to be created on secondaries, create it and
7595   all its children.
7596
7597   If not, just recurse to children keeping the same 'force' value.
7598
7599   @param lu: the lu on whose behalf we execute
7600   @param node: the node on which to create the device
7601   @type instance: L{objects.Instance}
7602   @param instance: the instance which owns the device
7603   @type device: L{objects.Disk}
7604   @param device: the device to create
7605   @type force_create: boolean
7606   @param force_create: whether to force creation of this device; this
7607       will be change to True whenever we find a device which has
7608       CreateOnSecondary() attribute
7609   @param info: the extra 'metadata' we should attach to the device
7610       (this will be represented as a LVM tag)
7611   @type force_open: boolean
7612   @param force_open: this parameter will be passes to the
7613       L{backend.BlockdevCreate} function where it specifies
7614       whether we run on primary or not, and it affects both
7615       the child assembly and the device own Open() execution
7616
7617   """
7618   if device.CreateOnSecondary():
7619     force_create = True
7620
7621   if device.children:
7622     for child in device.children:
7623       _CreateBlockDev(lu, node, instance, child, force_create,
7624                       info, force_open)
7625
7626   if not force_create:
7627     return
7628
7629   _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7630
7631
7632 def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7633   """Create a single block device on a given node.
7634
7635   This will not recurse over children of the device, so they must be
7636   created in advance.
7637
7638   @param lu: the lu on whose behalf we execute
7639   @param node: the node on which to create the device
7640   @type instance: L{objects.Instance}
7641   @param instance: the instance which owns the device
7642   @type device: L{objects.Disk}
7643   @param device: the device to create
7644   @param info: the extra 'metadata' we should attach to the device
7645       (this will be represented as a LVM tag)
7646   @type force_open: boolean
7647   @param force_open: this parameter will be passes to the
7648       L{backend.BlockdevCreate} function where it specifies
7649       whether we run on primary or not, and it affects both
7650       the child assembly and the device own Open() execution
7651
7652   """
7653   lu.cfg.SetDiskID(device, node)
7654   result = lu.rpc.call_blockdev_create(node, device, device.size,
7655                                        instance.name, force_open, info)
7656   result.Raise("Can't create block device %s on"
7657                " node %s for instance %s" % (device, node, instance.name))
7658   if device.physical_id is None:
7659     device.physical_id = result.payload
7660
7661
7662 def _GenerateUniqueNames(lu, exts):
7663   """Generate a suitable LV name.
7664
7665   This will generate a logical volume name for the given instance.
7666
7667   """
7668   results = []
7669   for val in exts:
7670     new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7671     results.append("%s%s" % (new_id, val))
7672   return results
7673
7674
7675 def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7676                          iv_name, p_minor, s_minor):
7677   """Generate a drbd8 device complete with its children.
7678
7679   """
7680   assert len(vgnames) == len(names) == 2
7681   port = lu.cfg.AllocatePort()
7682   shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7683   dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7684                           logical_id=(vgnames[0], names[0]))
7685   dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7686                           logical_id=(vgnames[1], names[1]))
7687   drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7688                           logical_id=(primary, secondary, port,
7689                                       p_minor, s_minor,
7690                                       shared_secret),
7691                           children=[dev_data, dev_meta],
7692                           iv_name=iv_name)
7693   return drbd_dev
7694
7695
7696 def _GenerateDiskTemplate(lu, template_name,
7697                           instance_name, primary_node,
7698                           secondary_nodes, disk_info,
7699                           file_storage_dir, file_driver,
7700                           base_index, feedback_fn):
7701   """Generate the entire disk layout for a given template type.
7702
7703   """
7704   #TODO: compute space requirements
7705
7706   vgname = lu.cfg.GetVGName()
7707   disk_count = len(disk_info)
7708   disks = []
7709   if template_name == constants.DT_DISKLESS:
7710     pass
7711   elif template_name == constants.DT_PLAIN:
7712     if len(secondary_nodes) != 0:
7713       raise errors.ProgrammerError("Wrong template configuration")
7714
7715     names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7716                                       for i in range(disk_count)])
7717     for idx, disk in enumerate(disk_info):
7718       disk_index = idx + base_index
7719       vg = disk.get(constants.IDISK_VG, vgname)
7720       feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7721       disk_dev = objects.Disk(dev_type=constants.LD_LV,
7722                               size=disk[constants.IDISK_SIZE],
7723                               logical_id=(vg, names[idx]),
7724                               iv_name="disk/%d" % disk_index,
7725                               mode=disk[constants.IDISK_MODE])
7726       disks.append(disk_dev)
7727   elif template_name == constants.DT_DRBD8:
7728     if len(secondary_nodes) != 1:
7729       raise errors.ProgrammerError("Wrong template configuration")
7730     remote_node = secondary_nodes[0]
7731     minors = lu.cfg.AllocateDRBDMinor(
7732       [primary_node, remote_node] * len(disk_info), instance_name)
7733
7734     names = []
7735     for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7736                                                for i in range(disk_count)]):
7737       names.append(lv_prefix + "_data")
7738       names.append(lv_prefix + "_meta")
7739     for idx, disk in enumerate(disk_info):
7740       disk_index = idx + base_index
7741       data_vg = disk.get(constants.IDISK_VG, vgname)
7742       meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7743       disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7744                                       disk[constants.IDISK_SIZE],
7745                                       [data_vg, meta_vg],
7746                                       names[idx * 2:idx * 2 + 2],
7747                                       "disk/%d" % disk_index,
7748                                       minors[idx * 2], minors[idx * 2 + 1])
7749       disk_dev.mode = disk[constants.IDISK_MODE]
7750       disks.append(disk_dev)
7751   elif template_name == constants.DT_FILE:
7752     if len(secondary_nodes) != 0:
7753       raise errors.ProgrammerError("Wrong template configuration")
7754
7755     opcodes.RequireFileStorage()
7756
7757     for idx, disk in enumerate(disk_info):
7758       disk_index = idx + base_index
7759       disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7760                               size=disk[constants.IDISK_SIZE],
7761                               iv_name="disk/%d" % disk_index,
7762                               logical_id=(file_driver,
7763                                           "%s/disk%d" % (file_storage_dir,
7764                                                          disk_index)),
7765                               mode=disk[constants.IDISK_MODE])
7766       disks.append(disk_dev)
7767   elif template_name == constants.DT_SHARED_FILE:
7768     if len(secondary_nodes) != 0:
7769       raise errors.ProgrammerError("Wrong template configuration")
7770
7771     opcodes.RequireSharedFileStorage()
7772
7773     for idx, disk in enumerate(disk_info):
7774       disk_index = idx + base_index
7775       disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7776                               size=disk[constants.IDISK_SIZE],
7777                               iv_name="disk/%d" % disk_index,
7778                               logical_id=(file_driver,
7779                                           "%s/disk%d" % (file_storage_dir,
7780                                                          disk_index)),
7781                               mode=disk[constants.IDISK_MODE])
7782       disks.append(disk_dev)
7783   elif template_name == constants.DT_BLOCK:
7784     if len(secondary_nodes) != 0:
7785       raise errors.ProgrammerError("Wrong template configuration")
7786
7787     for idx, disk in enumerate(disk_info):
7788       disk_index = idx + base_index
7789       disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7790                               size=disk[constants.IDISK_SIZE],
7791                               logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7792                                           disk[constants.IDISK_ADOPT]),
7793                               iv_name="disk/%d" % disk_index,
7794                               mode=disk[constants.IDISK_MODE])
7795       disks.append(disk_dev)
7796
7797   else:
7798     raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7799   return disks
7800
7801
7802 def _GetInstanceInfoText(instance):
7803   """Compute that text that should be added to the disk's metadata.
7804
7805   """
7806   return "originstname+%s" % instance.name
7807
7808
7809 def _CalcEta(time_taken, written, total_size):
7810   """Calculates the ETA based on size written and total size.
7811
7812   @param time_taken: The time taken so far
7813   @param written: amount written so far
7814   @param total_size: The total size of data to be written
7815   @return: The remaining time in seconds
7816
7817   """
7818   avg_time = time_taken / float(written)
7819   return (total_size - written) * avg_time
7820
7821
7822 def _WipeDisks(lu, instance):
7823   """Wipes instance disks.
7824
7825   @type lu: L{LogicalUnit}
7826   @param lu: the logical unit on whose behalf we execute
7827   @type instance: L{objects.Instance}
7828   @param instance: the instance whose disks we should create
7829   @return: the success of the wipe
7830
7831   """
7832   node = instance.primary_node
7833
7834   for device in instance.disks:
7835     lu.cfg.SetDiskID(device, node)
7836
7837   logging.info("Pause sync of instance %s disks", instance.name)
7838   result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7839
7840   for idx, success in enumerate(result.payload):
7841     if not success:
7842       logging.warn("pause-sync of instance %s for disks %d failed",
7843                    instance.name, idx)
7844
7845   try:
7846     for idx, device in enumerate(instance.disks):
7847       # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7848       # MAX_WIPE_CHUNK at max
7849       wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7850                             constants.MIN_WIPE_CHUNK_PERCENT)
7851       # we _must_ make this an int, otherwise rounding errors will
7852       # occur
7853       wipe_chunk_size = int(wipe_chunk_size)
7854
7855       lu.LogInfo("* Wiping disk %d", idx)
7856       logging.info("Wiping disk %d for instance %s, node %s using"
7857                    " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7858
7859       offset = 0
7860       size = device.size
7861       last_output = 0
7862       start_time = time.time()
7863
7864       while offset < size:
7865         wipe_size = min(wipe_chunk_size, size - offset)
7866         logging.debug("Wiping disk %d, offset %s, chunk %s",
7867                       idx, offset, wipe_size)
7868         result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7869         result.Raise("Could not wipe disk %d at offset %d for size %d" %
7870                      (idx, offset, wipe_size))
7871         now = time.time()
7872         offset += wipe_size
7873         if now - last_output >= 60:
7874           eta = _CalcEta(now - start_time, offset, size)
7875           lu.LogInfo(" - done: %.1f%% ETA: %s" %
7876                      (offset / float(size) * 100, utils.FormatSeconds(eta)))
7877           last_output = now
7878   finally:
7879     logging.info("Resume sync of instance %s disks", instance.name)
7880
7881     result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7882
7883     for idx, success in enumerate(result.payload):
7884       if not success:
7885         lu.LogWarning("Resume sync of disk %d failed, please have a"
7886                       " look at the status and troubleshoot the issue", idx)
7887         logging.warn("resume-sync of instance %s for disks %d failed",
7888                      instance.name, idx)
7889
7890
7891 def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7892   """Create all disks for an instance.
7893
7894   This abstracts away some work from AddInstance.
7895
7896   @type lu: L{LogicalUnit}
7897   @param lu: the logical unit on whose behalf we execute
7898   @type instance: L{objects.Instance}
7899   @param instance: the instance whose disks we should create
7900   @type to_skip: list
7901   @param to_skip: list of indices to skip
7902   @type target_node: string
7903   @param target_node: if passed, overrides the target node for creation
7904   @rtype: boolean
7905   @return: the success of the creation
7906
7907   """
7908   info = _GetInstanceInfoText(instance)
7909   if target_node is None:
7910     pnode = instance.primary_node
7911     all_nodes = instance.all_nodes
7912   else:
7913     pnode = target_node
7914     all_nodes = [pnode]
7915
7916   if instance.disk_template in constants.DTS_FILEBASED:
7917     file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7918     result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7919
7920     result.Raise("Failed to create directory '%s' on"
7921                  " node %s" % (file_storage_dir, pnode))
7922
7923   # Note: this needs to be kept in sync with adding of disks in
7924   # LUInstanceSetParams
7925   for idx, device in enumerate(instance.disks):
7926     if to_skip and idx in to_skip:
7927       continue
7928     logging.info("Creating volume %s for instance %s",
7929                  device.iv_name, instance.name)
7930     #HARDCODE
7931     for node in all_nodes:
7932       f_create = node == pnode
7933       _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7934
7935
7936 def _RemoveDisks(lu, instance, target_node=None):
7937   """Remove all disks for an instance.
7938
7939   This abstracts away some work from `AddInstance()` and
7940   `RemoveInstance()`. Note that in case some of the devices couldn't
7941   be removed, the removal will continue with the other ones (compare
7942   with `_CreateDisks()`).
7943
7944   @type lu: L{LogicalUnit}
7945   @param lu: the logical unit on whose behalf we execute
7946   @type instance: L{objects.Instance}
7947   @param instance: the instance whose disks we should remove
7948   @type target_node: string
7949   @param target_node: used to override the node on which to remove the disks
7950   @rtype: boolean
7951   @return: the success of the removal
7952
7953   """
7954   logging.info("Removing block devices for instance %s", instance.name)
7955
7956   all_result = True
7957   for device in instance.disks:
7958     if target_node:
7959       edata = [(target_node, device)]
7960     else:
7961       edata = device.ComputeNodeTree(instance.primary_node)
7962     for node, disk in edata:
7963       lu.cfg.SetDiskID(disk, node)
7964       msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7965       if msg:
7966         lu.LogWarning("Could not remove block device %s on node %s,"
7967                       " continuing anyway: %s", device.iv_name, node, msg)
7968         all_result = False
7969
7970     # if this is a DRBD disk, return its port to the pool
7971     if device.dev_type in constants.LDS_DRBD:
7972       tcp_port = device.logical_id[2]
7973       lu.cfg.AddTcpUdpPort(tcp_port)
7974
7975   if instance.disk_template == constants.DT_FILE:
7976     file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7977     if target_node:
7978       tgt = target_node
7979     else:
7980       tgt = instance.primary_node
7981     result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7982     if result.fail_msg:
7983       lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7984                     file_storage_dir, instance.primary_node, result.fail_msg)
7985       all_result = False
7986
7987   return all_result
7988
7989
7990 def _ComputeDiskSizePerVG(disk_template, disks):
7991   """Compute disk size requirements in the volume group
7992
7993   """
7994   def _compute(disks, payload):
7995     """Universal algorithm.
7996
7997     """
7998     vgs = {}
7999     for disk in disks:
8000       vgs[disk[constants.IDISK_VG]] = \
8001         vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
8002
8003     return vgs
8004
8005   # Required free disk space as a function of disk and swap space
8006   req_size_dict = {
8007     constants.DT_DISKLESS: {},
8008     constants.DT_PLAIN: _compute(disks, 0),
8009     # 128 MB are added for drbd metadata for each disk
8010     constants.DT_DRBD8: _compute(disks, 128),
8011     constants.DT_FILE: {},
8012     constants.DT_SHARED_FILE: {},
8013   }
8014
8015   if disk_template not in req_size_dict:
8016     raise errors.ProgrammerError("Disk template '%s' size requirement"
8017                                  " is unknown" % disk_template)
8018
8019   return req_size_dict[disk_template]
8020
8021
8022 def _ComputeDiskSize(disk_template, disks):
8023   """Compute disk size requirements in the volume group
8024
8025   """
8026   # Required free disk space as a function of disk and swap space
8027   req_size_dict = {
8028     constants.DT_DISKLESS: None,
8029     constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
8030     # 128 MB are added for drbd metadata for each disk
8031     constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
8032     constants.DT_FILE: None,
8033     constants.DT_SHARED_FILE: 0,
8034     constants.DT_BLOCK: 0,
8035   }
8036
8037   if disk_template not in req_size_dict:
8038     raise errors.ProgrammerError("Disk template '%s' size requirement"
8039                                  " is unknown" % disk_template)
8040
8041   return req_size_dict[disk_template]
8042
8043
8044 def _FilterVmNodes(lu, nodenames):
8045   """Filters out non-vm_capable nodes from a list.
8046
8047   @type lu: L{LogicalUnit}
8048   @param lu: the logical unit for which we check
8049   @type nodenames: list
8050   @param nodenames: the list of nodes on which we should check
8051   @rtype: list
8052   @return: the list of vm-capable nodes
8053
8054   """
8055   vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
8056   return [name for name in nodenames if name not in vm_nodes]
8057
8058
8059 def _CheckHVParams(lu, nodenames, hvname, hvparams):
8060   """Hypervisor parameter validation.
8061
8062   This function abstract the hypervisor parameter validation to be
8063   used in both instance create and instance modify.
8064
8065   @type lu: L{LogicalUnit}
8066   @param lu: the logical unit for which we check
8067   @type nodenames: list
8068   @param nodenames: the list of nodes on which we should check
8069   @type hvname: string
8070   @param hvname: the name of the hypervisor we should use
8071   @type hvparams: dict
8072   @param hvparams: the parameters which we need to check
8073   @raise errors.OpPrereqError: if the parameters are not valid
8074
8075   """
8076   nodenames = _FilterVmNodes(lu, nodenames)
8077   hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
8078                                                   hvname,
8079                                                   hvparams)
8080   for node in nodenames:
8081     info = hvinfo[node]
8082     if info.offline:
8083       continue
8084     info.Raise("Hypervisor parameter validation failed on node %s" % node)
8085
8086
8087 def _CheckOSParams(lu, required, nodenames, osname, osparams):
8088   """OS parameters validation.
8089
8090   @type lu: L{LogicalUnit}
8091   @param lu: the logical unit for which we check
8092   @type required: boolean
8093   @param required: whether the validation should fail if the OS is not
8094       found
8095   @type nodenames: list
8096   @param nodenames: the list of nodes on which we should check
8097   @type osname: string
8098   @param osname: the name of the hypervisor we should use
8099   @type osparams: dict
8100   @param osparams: the parameters which we need to check
8101   @raise errors.OpPrereqError: if the parameters are not valid
8102
8103   """
8104   nodenames = _FilterVmNodes(lu, nodenames)
8105   result = lu.rpc.call_os_validate(required, nodenames, osname,
8106                                    [constants.OS_VALIDATE_PARAMETERS],
8107                                    osparams)
8108   for node, nres in result.items():
8109     # we don't check for offline cases since this should be run only
8110     # against the master node and/or an instance's nodes
8111     nres.Raise("OS Parameters validation failed on node %s" % node)
8112     if not nres.payload:
8113       lu.LogInfo("OS %s not found on node %s, validation skipped",
8114                  osname, node)
8115
8116
8117 class LUInstanceCreate(LogicalUnit):
8118   """Create an instance.
8119
8120   """
8121   HPATH = "instance-add"
8122   HTYPE = constants.HTYPE_INSTANCE
8123   REQ_BGL = False
8124
8125   def CheckArguments(self):
8126     """Check arguments.
8127
8128     """
8129     # do not require name_check to ease forward/backward compatibility
8130     # for tools
8131     if self.op.no_install and self.op.start:
8132       self.LogInfo("No-installation mode selected, disabling startup")
8133       self.op.start = False
8134     # validate/normalize the instance name
8135     self.op.instance_name = \
8136       netutils.Hostname.GetNormalizedName(self.op.instance_name)
8137
8138     if self.op.ip_check and not self.op.name_check:
8139       # TODO: make the ip check more flexible and not depend on the name check
8140       raise errors.OpPrereqError("Cannot do IP address check without a name"
8141                                  " check", errors.ECODE_INVAL)
8142
8143     # check nics' parameter names
8144     for nic in self.op.nics:
8145       utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
8146
8147     # check disks. parameter names and consistent adopt/no-adopt strategy
8148     has_adopt = has_no_adopt = False
8149     for disk in self.op.disks:
8150       utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
8151       if constants.IDISK_ADOPT in disk:
8152         has_adopt = True
8153       else:
8154         has_no_adopt = True
8155     if has_adopt and has_no_adopt:
8156       raise errors.OpPrereqError("Either all disks are adopted or none is",
8157                                  errors.ECODE_INVAL)
8158     if has_adopt:
8159       if self.op.disk_template not in constants.DTS_MAY_ADOPT:
8160         raise errors.OpPrereqError("Disk adoption is not supported for the"
8161                                    " '%s' disk template" %
8162                                    self.op.disk_template,
8163                                    errors.ECODE_INVAL)
8164       if self.op.iallocator is not None:
8165         raise errors.OpPrereqError("Disk adoption not allowed with an"
8166                                    " iallocator script", errors.ECODE_INVAL)
8167       if self.op.mode == constants.INSTANCE_IMPORT:
8168         raise errors.OpPrereqError("Disk adoption not allowed for"
8169                                    " instance import", errors.ECODE_INVAL)
8170     else:
8171       if self.op.disk_template in constants.DTS_MUST_ADOPT:
8172         raise errors.OpPrereqError("Disk template %s requires disk adoption,"
8173                                    " but no 'adopt' parameter given" %
8174                                    self.op.disk_template,
8175                                    errors.ECODE_INVAL)
8176
8177     self.adopt_disks = has_adopt
8178
8179     # instance name verification
8180     if self.op.name_check:
8181       self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
8182       self.op.instance_name = self.hostname1.name
8183       # used in CheckPrereq for ip ping check
8184       self.check_ip = self.hostname1.ip
8185     else:
8186       self.check_ip = None
8187
8188     # file storage checks
8189     if (self.op.file_driver and
8190         not self.op.file_driver in constants.FILE_DRIVER):
8191       raise errors.OpPrereqError("Invalid file driver name '%s'" %
8192                                  self.op.file_driver, errors.ECODE_INVAL)
8193
8194     if self.op.disk_template == constants.DT_FILE:
8195       opcodes.RequireFileStorage()
8196     elif self.op.disk_template == constants.DT_SHARED_FILE:
8197       opcodes.RequireSharedFileStorage()
8198
8199     ### Node/iallocator related checks
8200     _CheckIAllocatorOrNode(self, "iallocator", "pnode")
8201
8202     if self.op.pnode is not None:
8203       if self.op.disk_template in constants.DTS_INT_MIRROR:
8204         if self.op.snode is None:
8205           raise errors.OpPrereqError("The networked disk templates need"
8206                                      " a mirror node", errors.ECODE_INVAL)
8207       elif self.op.snode:
8208         self.LogWarning("Secondary node will be ignored on non-mirrored disk"
8209                         " template")
8210         self.op.snode = None
8211
8212     self._cds = _GetClusterDomainSecret()
8213
8214     if self.op.mode == constants.INSTANCE_IMPORT:
8215       # On import force_variant must be True, because if we forced it at
8216       # initial install, our only chance when importing it back is that it
8217       # works again!
8218       self.op.force_variant = True
8219
8220       if self.op.no_install:
8221         self.LogInfo("No-installation mode has no effect during import")
8222
8223     elif self.op.mode == constants.INSTANCE_CREATE:
8224       if self.op.os_type is None:
8225         raise errors.OpPrereqError("No guest OS specified",
8226                                    errors.ECODE_INVAL)
8227       if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
8228         raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
8229                                    " installation" % self.op.os_type,
8230                                    errors.ECODE_STATE)
8231       if self.op.disk_template is None:
8232         raise errors.OpPrereqError("No disk template specified",
8233                                    errors.ECODE_INVAL)
8234
8235     elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8236       # Check handshake to ensure both clusters have the same domain secret
8237       src_handshake = self.op.source_handshake
8238       if not src_handshake:
8239         raise errors.OpPrereqError("Missing source handshake",
8240                                    errors.ECODE_INVAL)
8241
8242       errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
8243                                                            src_handshake)
8244       if errmsg:
8245         raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
8246                                    errors.ECODE_INVAL)
8247
8248       # Load and check source CA
8249       self.source_x509_ca_pem = self.op.source_x509_ca
8250       if not self.source_x509_ca_pem:
8251         raise errors.OpPrereqError("Missing source X509 CA",
8252                                    errors.ECODE_INVAL)
8253
8254       try:
8255         (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
8256                                                     self._cds)
8257       except OpenSSL.crypto.Error, err:
8258         raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
8259                                    (err, ), errors.ECODE_INVAL)
8260
8261       (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
8262       if errcode is not None:
8263         raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
8264                                    errors.ECODE_INVAL)
8265
8266       self.source_x509_ca = cert
8267
8268       src_instance_name = self.op.source_instance_name
8269       if not src_instance_name:
8270         raise errors.OpPrereqError("Missing source instance name",
8271                                    errors.ECODE_INVAL)
8272
8273       self.source_instance_name = \
8274           netutils.GetHostname(name=src_instance_name).name
8275
8276     else:
8277       raise errors.OpPrereqError("Invalid instance creation mode %r" %
8278                                  self.op.mode, errors.ECODE_INVAL)
8279
8280   def ExpandNames(self):
8281     """ExpandNames for CreateInstance.
8282
8283     Figure out the right locks for instance creation.
8284
8285     """
8286     self.needed_locks = {}
8287
8288     instance_name = self.op.instance_name
8289     # this is just a preventive check, but someone might still add this
8290     # instance in the meantime, and creation will fail at lock-add time
8291     if instance_name in self.cfg.GetInstanceList():
8292       raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
8293                                  instance_name, errors.ECODE_EXISTS)
8294
8295     self.add_locks[locking.LEVEL_INSTANCE] = instance_name
8296
8297     if self.op.iallocator:
8298       self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8299     else:
8300       self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
8301       nodelist = [self.op.pnode]
8302       if self.op.snode is not None:
8303         self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
8304         nodelist.append(self.op.snode)
8305       self.needed_locks[locking.LEVEL_NODE] = nodelist
8306
8307     # in case of import lock the source node too
8308     if self.op.mode == constants.INSTANCE_IMPORT:
8309       src_node = self.op.src_node
8310       src_path = self.op.src_path
8311
8312       if src_path is None:
8313         self.op.src_path = src_path = self.op.instance_name
8314
8315       if src_node is None:
8316         self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8317         self.op.src_node = None
8318         if os.path.isabs(src_path):
8319           raise errors.OpPrereqError("Importing an instance from a path"
8320                                      " requires a source node option",
8321                                      errors.ECODE_INVAL)
8322       else:
8323         self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
8324         if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
8325           self.needed_locks[locking.LEVEL_NODE].append(src_node)
8326         if not os.path.isabs(src_path):
8327           self.op.src_path = src_path = \
8328             utils.PathJoin(constants.EXPORT_DIR, src_path)
8329
8330   def _RunAllocator(self):
8331     """Run the allocator based on input opcode.
8332
8333     """
8334     nics = [n.ToDict() for n in self.nics]
8335     ial = IAllocator(self.cfg, self.rpc,
8336                      mode=constants.IALLOCATOR_MODE_ALLOC,
8337                      name=self.op.instance_name,
8338                      disk_template=self.op.disk_template,
8339                      tags=self.op.tags,
8340                      os=self.op.os_type,
8341                      vcpus=self.be_full[constants.BE_VCPUS],
8342                      memory=self.be_full[constants.BE_MEMORY],
8343                      disks=self.disks,
8344                      nics=nics,
8345                      hypervisor=self.op.hypervisor,
8346                      )
8347
8348     ial.Run(self.op.iallocator)
8349
8350     if not ial.success:
8351       raise errors.OpPrereqError("Can't compute nodes using"
8352                                  " iallocator '%s': %s" %
8353                                  (self.op.iallocator, ial.info),
8354                                  errors.ECODE_NORES)
8355     if len(ial.result) != ial.required_nodes:
8356       raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8357                                  " of nodes (%s), required %s" %
8358                                  (self.op.iallocator, len(ial.result),
8359                                   ial.required_nodes), errors.ECODE_FAULT)
8360     self.op.pnode = ial.result[0]
8361     self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8362                  self.op.instance_name, self.op.iallocator,
8363                  utils.CommaJoin(ial.result))
8364     if ial.required_nodes == 2:
8365       self.op.snode = ial.result[1]
8366
8367   def BuildHooksEnv(self):
8368     """Build hooks env.
8369
8370     This runs on master, primary and secondary nodes of the instance.
8371
8372     """
8373     env = {
8374       "ADD_MODE": self.op.mode,
8375       }
8376     if self.op.mode == constants.INSTANCE_IMPORT:
8377       env["SRC_NODE"] = self.op.src_node
8378       env["SRC_PATH"] = self.op.src_path
8379       env["SRC_IMAGES"] = self.src_images
8380
8381     env.update(_BuildInstanceHookEnv(
8382       name=self.op.instance_name,
8383       primary_node=self.op.pnode,
8384       secondary_nodes=self.secondaries,
8385       status=self.op.start,
8386       os_type=self.op.os_type,
8387       memory=self.be_full[constants.BE_MEMORY],
8388       vcpus=self.be_full[constants.BE_VCPUS],
8389       nics=_NICListToTuple(self, self.nics),
8390       disk_template=self.op.disk_template,
8391       disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8392              for d in self.disks],
8393       bep=self.be_full,
8394       hvp=self.hv_full,
8395       hypervisor_name=self.op.hypervisor,
8396       tags=self.op.tags,
8397     ))
8398
8399     return env
8400
8401   def BuildHooksNodes(self):
8402     """Build hooks nodes.
8403
8404     """
8405     nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8406     return nl, nl
8407
8408   def _ReadExportInfo(self):
8409     """Reads the export information from disk.
8410
8411     It will override the opcode source node and path with the actual
8412     information, if these two were not specified before.
8413
8414     @return: the export information
8415
8416     """
8417     assert self.op.mode == constants.INSTANCE_IMPORT
8418
8419     src_node = self.op.src_node
8420     src_path = self.op.src_path
8421
8422     if src_node is None:
8423       locked_nodes = self.owned_locks(locking.LEVEL_NODE)
8424       exp_list = self.rpc.call_export_list(locked_nodes)
8425       found = False
8426       for node in exp_list:
8427         if exp_list[node].fail_msg:
8428           continue
8429         if src_path in exp_list[node].payload:
8430           found = True
8431           self.op.src_node = src_node = node
8432           self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8433                                                        src_path)
8434           break
8435       if not found:
8436         raise errors.OpPrereqError("No export found for relative path %s" %
8437                                     src_path, errors.ECODE_INVAL)
8438
8439     _CheckNodeOnline(self, src_node)
8440     result = self.rpc.call_export_info(src_node, src_path)
8441     result.Raise("No export or invalid export found in dir %s" % src_path)
8442
8443     export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8444     if not export_info.has_section(constants.INISECT_EXP):
8445       raise errors.ProgrammerError("Corrupted export config",
8446                                    errors.ECODE_ENVIRON)
8447
8448     ei_version = export_info.get(constants.INISECT_EXP, "version")
8449     if (int(ei_version) != constants.EXPORT_VERSION):
8450       raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8451                                  (ei_version, constants.EXPORT_VERSION),
8452                                  errors.ECODE_ENVIRON)
8453     return export_info
8454
8455   def _ReadExportParams(self, einfo):
8456     """Use export parameters as defaults.
8457
8458     In case the opcode doesn't specify (as in override) some instance
8459     parameters, then try to use them from the export information, if
8460     that declares them.
8461
8462     """
8463     self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8464
8465     if self.op.disk_template is None:
8466       if einfo.has_option(constants.INISECT_INS, "disk_template"):
8467         self.op.disk_template = einfo.get(constants.INISECT_INS,
8468                                           "disk_template")
8469       else:
8470         raise errors.OpPrereqError("No disk template specified and the export"
8471                                    " is missing the disk_template information",
8472                                    errors.ECODE_INVAL)
8473
8474     if not self.op.disks:
8475       if einfo.has_option(constants.INISECT_INS, "disk_count"):
8476         disks = []
8477         # TODO: import the disk iv_name too
8478         for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8479           disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8480           disks.append({constants.IDISK_SIZE: disk_sz})
8481         self.op.disks = disks
8482       else:
8483         raise errors.OpPrereqError("No disk info specified and the export"
8484                                    " is missing the disk information",
8485                                    errors.ECODE_INVAL)
8486
8487     if (not self.op.nics and
8488         einfo.has_option(constants.INISECT_INS, "nic_count")):
8489       nics = []
8490       for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8491         ndict = {}
8492         for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8493           v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8494           ndict[name] = v
8495         nics.append(ndict)
8496       self.op.nics = nics
8497
8498     if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
8499       self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
8500
8501     if (self.op.hypervisor is None and
8502         einfo.has_option(constants.INISECT_INS, "hypervisor")):
8503       self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8504
8505     if einfo.has_section(constants.INISECT_HYP):
8506       # use the export parameters but do not override the ones
8507       # specified by the user
8508       for name, value in einfo.items(constants.INISECT_HYP):
8509         if name not in self.op.hvparams:
8510           self.op.hvparams[name] = value
8511
8512     if einfo.has_section(constants.INISECT_BEP):
8513       # use the parameters, without overriding
8514       for name, value in einfo.items(constants.INISECT_BEP):
8515         if name not in self.op.beparams:
8516           self.op.beparams[name] = value
8517     else:
8518       # try to read the parameters old style, from the main section
8519       for name in constants.BES_PARAMETERS:
8520         if (name not in self.op.beparams and
8521             einfo.has_option(constants.INISECT_INS, name)):
8522           self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8523
8524     if einfo.has_section(constants.INISECT_OSP):
8525       # use the parameters, without overriding
8526       for name, value in einfo.items(constants.INISECT_OSP):
8527         if name not in self.op.osparams:
8528           self.op.osparams[name] = value
8529
8530   def _RevertToDefaults(self, cluster):
8531     """Revert the instance parameters to the default values.
8532
8533     """
8534     # hvparams
8535     hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8536     for name in self.op.hvparams.keys():
8537       if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8538         del self.op.hvparams[name]
8539     # beparams
8540     be_defs = cluster.SimpleFillBE({})
8541     for name in self.op.beparams.keys():
8542       if name in be_defs and be_defs[name] == self.op.beparams[name]:
8543         del self.op.beparams[name]
8544     # nic params
8545     nic_defs = cluster.SimpleFillNIC({})
8546     for nic in self.op.nics:
8547       for name in constants.NICS_PARAMETERS:
8548         if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8549           del nic[name]
8550     # osparams
8551     os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8552     for name in self.op.osparams.keys():
8553       if name in os_defs and os_defs[name] == self.op.osparams[name]:
8554         del self.op.osparams[name]
8555
8556   def _CalculateFileStorageDir(self):
8557     """Calculate final instance file storage dir.
8558
8559     """
8560     # file storage dir calculation/check
8561     self.instance_file_storage_dir = None
8562     if self.op.disk_template in constants.DTS_FILEBASED:
8563       # build the full file storage dir path
8564       joinargs = []
8565
8566       if self.op.disk_template == constants.DT_SHARED_FILE:
8567         get_fsd_fn = self.cfg.GetSharedFileStorageDir
8568       else:
8569         get_fsd_fn = self.cfg.GetFileStorageDir
8570
8571       cfg_storagedir = get_fsd_fn()
8572       if not cfg_storagedir:
8573         raise errors.OpPrereqError("Cluster file storage dir not defined")
8574       joinargs.append(cfg_storagedir)
8575
8576       if self.op.file_storage_dir is not None:
8577         joinargs.append(self.op.file_storage_dir)
8578
8579       joinargs.append(self.op.instance_name)
8580
8581       # pylint: disable=W0142
8582       self.instance_file_storage_dir = utils.PathJoin(*joinargs)
8583
8584   def CheckPrereq(self):
8585     """Check prerequisites.
8586
8587     """
8588     self._CalculateFileStorageDir()
8589
8590     if self.op.mode == constants.INSTANCE_IMPORT:
8591       export_info = self._ReadExportInfo()
8592       self._ReadExportParams(export_info)
8593
8594     if (not self.cfg.GetVGName() and
8595         self.op.disk_template not in constants.DTS_NOT_LVM):
8596       raise errors.OpPrereqError("Cluster does not support lvm-based"
8597                                  " instances", errors.ECODE_STATE)
8598
8599     if self.op.hypervisor is None:
8600       self.op.hypervisor = self.cfg.GetHypervisorType()
8601
8602     cluster = self.cfg.GetClusterInfo()
8603     enabled_hvs = cluster.enabled_hypervisors
8604     if self.op.hypervisor not in enabled_hvs:
8605       raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8606                                  " cluster (%s)" % (self.op.hypervisor,
8607                                   ",".join(enabled_hvs)),
8608                                  errors.ECODE_STATE)
8609
8610     # Check tag validity
8611     for tag in self.op.tags:
8612       objects.TaggableObject.ValidateTag(tag)
8613
8614     # check hypervisor parameter syntax (locally)
8615     utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8616     filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8617                                       self.op.hvparams)
8618     hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8619     hv_type.CheckParameterSyntax(filled_hvp)
8620     self.hv_full = filled_hvp
8621     # check that we don't specify global parameters on an instance
8622     _CheckGlobalHvParams(self.op.hvparams)
8623
8624     # fill and remember the beparams dict
8625     utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8626     self.be_full = cluster.SimpleFillBE(self.op.beparams)
8627
8628     # build os parameters
8629     self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8630
8631     # now that hvp/bep are in final format, let's reset to defaults,
8632     # if told to do so
8633     if self.op.identify_defaults:
8634       self._RevertToDefaults(cluster)
8635
8636     # NIC buildup
8637     self.nics = []
8638     for idx, nic in enumerate(self.op.nics):
8639       nic_mode_req = nic.get(constants.INIC_MODE, None)
8640       nic_mode = nic_mode_req
8641       if nic_mode is None:
8642         nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8643
8644       # in routed mode, for the first nic, the default ip is 'auto'
8645       if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8646         default_ip_mode = constants.VALUE_AUTO
8647       else:
8648         default_ip_mode = constants.VALUE_NONE
8649
8650       # ip validity checks
8651       ip = nic.get(constants.INIC_IP, default_ip_mode)
8652       if ip is None or ip.lower() == constants.VALUE_NONE:
8653         nic_ip = None
8654       elif ip.lower() == constants.VALUE_AUTO:
8655         if not self.op.name_check:
8656           raise errors.OpPrereqError("IP address set to auto but name checks"
8657                                      " have been skipped",
8658                                      errors.ECODE_INVAL)
8659         nic_ip = self.hostname1.ip
8660       else:
8661         if not netutils.IPAddress.IsValid(ip):
8662           raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8663                                      errors.ECODE_INVAL)
8664         nic_ip = ip
8665
8666       # TODO: check the ip address for uniqueness
8667       if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8668         raise errors.OpPrereqError("Routed nic mode requires an ip address",
8669                                    errors.ECODE_INVAL)
8670
8671       # MAC address verification
8672       mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8673       if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8674         mac = utils.NormalizeAndValidateMac(mac)
8675
8676         try:
8677           self.cfg.ReserveMAC(mac, self.proc.GetECId())
8678         except errors.ReservationError:
8679           raise errors.OpPrereqError("MAC address %s already in use"
8680                                      " in cluster" % mac,
8681                                      errors.ECODE_NOTUNIQUE)
8682
8683       #  Build nic parameters
8684       link = nic.get(constants.INIC_LINK, None)
8685       nicparams = {}
8686       if nic_mode_req:
8687         nicparams[constants.NIC_MODE] = nic_mode_req
8688       if link:
8689         nicparams[constants.NIC_LINK] = link
8690
8691       check_params = cluster.SimpleFillNIC(nicparams)
8692       objects.NIC.CheckParameterSyntax(check_params)
8693       self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8694
8695     # disk checks/pre-build
8696     default_vg = self.cfg.GetVGName()
8697     self.disks = []
8698     for disk in self.op.disks:
8699       mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8700       if mode not in constants.DISK_ACCESS_SET:
8701         raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8702                                    mode, errors.ECODE_INVAL)
8703       size = disk.get(constants.IDISK_SIZE, None)
8704       if size is None:
8705         raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8706       try:
8707         size = int(size)
8708       except (TypeError, ValueError):
8709         raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8710                                    errors.ECODE_INVAL)
8711
8712       data_vg = disk.get(constants.IDISK_VG, default_vg)
8713       new_disk = {
8714         constants.IDISK_SIZE: size,
8715         constants.IDISK_MODE: mode,
8716         constants.IDISK_VG: data_vg,
8717         constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8718         }
8719       if constants.IDISK_ADOPT in disk:
8720         new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8721       self.disks.append(new_disk)
8722
8723     if self.op.mode == constants.INSTANCE_IMPORT:
8724
8725       # Check that the new instance doesn't have less disks than the export
8726       instance_disks = len(self.disks)
8727       export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8728       if instance_disks < export_disks:
8729         raise errors.OpPrereqError("Not enough disks to import."
8730                                    " (instance: %d, export: %d)" %
8731                                    (instance_disks, export_disks),
8732                                    errors.ECODE_INVAL)
8733
8734       disk_images = []
8735       for idx in range(export_disks):
8736         option = "disk%d_dump" % idx
8737         if export_info.has_option(constants.INISECT_INS, option):
8738           # FIXME: are the old os-es, disk sizes, etc. useful?
8739           export_name = export_info.get(constants.INISECT_INS, option)
8740           image = utils.PathJoin(self.op.src_path, export_name)
8741           disk_images.append(image)
8742         else:
8743           disk_images.append(False)
8744
8745       self.src_images = disk_images
8746
8747       old_name = export_info.get(constants.INISECT_INS, "name")
8748       try:
8749         exp_nic_count = export_info.getint(constants.INISECT_INS, "nic_count")
8750       except (TypeError, ValueError), err:
8751         raise errors.OpPrereqError("Invalid export file, nic_count is not"
8752                                    " an integer: %s" % str(err),
8753                                    errors.ECODE_STATE)
8754       if self.op.instance_name == old_name:
8755         for idx, nic in enumerate(self.nics):
8756           if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8757             nic_mac_ini = "nic%d_mac" % idx
8758             nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8759
8760     # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8761
8762     # ip ping checks (we use the same ip that was resolved in ExpandNames)
8763     if self.op.ip_check:
8764       if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8765         raise errors.OpPrereqError("IP %s of instance %s already in use" %
8766                                    (self.check_ip, self.op.instance_name),
8767                                    errors.ECODE_NOTUNIQUE)
8768
8769     #### mac address generation
8770     # By generating here the mac address both the allocator and the hooks get
8771     # the real final mac address rather than the 'auto' or 'generate' value.
8772     # There is a race condition between the generation and the instance object
8773     # creation, which means that we know the mac is valid now, but we're not
8774     # sure it will be when we actually add the instance. If things go bad
8775     # adding the instance will abort because of a duplicate mac, and the
8776     # creation job will fail.
8777     for nic in self.nics:
8778       if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8779         nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8780
8781     #### allocator run
8782
8783     if self.op.iallocator is not None:
8784       self._RunAllocator()
8785
8786     #### node related checks
8787
8788     # check primary node
8789     self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8790     assert self.pnode is not None, \
8791       "Cannot retrieve locked node %s" % self.op.pnode
8792     if pnode.offline:
8793       raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8794                                  pnode.name, errors.ECODE_STATE)
8795     if pnode.drained:
8796       raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8797                                  pnode.name, errors.ECODE_STATE)
8798     if not pnode.vm_capable:
8799       raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8800                                  " '%s'" % pnode.name, errors.ECODE_STATE)
8801
8802     self.secondaries = []
8803
8804     # mirror node verification
8805     if self.op.disk_template in constants.DTS_INT_MIRROR:
8806       if self.op.snode == pnode.name:
8807         raise errors.OpPrereqError("The secondary node cannot be the"
8808                                    " primary node", errors.ECODE_INVAL)
8809       _CheckNodeOnline(self, self.op.snode)
8810       _CheckNodeNotDrained(self, self.op.snode)
8811       _CheckNodeVmCapable(self, self.op.snode)
8812       self.secondaries.append(self.op.snode)
8813
8814     nodenames = [pnode.name] + self.secondaries
8815
8816     if not self.adopt_disks:
8817       # Check lv size requirements, if not adopting
8818       req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8819       _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8820
8821     elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8822       all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8823                                 disk[constants.IDISK_ADOPT])
8824                      for disk in self.disks])
8825       if len(all_lvs) != len(self.disks):
8826         raise errors.OpPrereqError("Duplicate volume names given for adoption",
8827                                    errors.ECODE_INVAL)
8828       for lv_name in all_lvs:
8829         try:
8830           # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8831           # to ReserveLV uses the same syntax
8832           self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8833         except errors.ReservationError:
8834           raise errors.OpPrereqError("LV named %s used by another instance" %
8835                                      lv_name, errors.ECODE_NOTUNIQUE)
8836
8837       vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8838       vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8839
8840       node_lvs = self.rpc.call_lv_list([pnode.name],
8841                                        vg_names.payload.keys())[pnode.name]
8842       node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8843       node_lvs = node_lvs.payload
8844
8845       delta = all_lvs.difference(node_lvs.keys())
8846       if delta:
8847         raise errors.OpPrereqError("Missing logical volume(s): %s" %
8848                                    utils.CommaJoin(delta),
8849                                    errors.ECODE_INVAL)
8850       online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8851       if online_lvs:
8852         raise errors.OpPrereqError("Online logical volumes found, cannot"
8853                                    " adopt: %s" % utils.CommaJoin(online_lvs),
8854                                    errors.ECODE_STATE)
8855       # update the size of disk based on what is found
8856       for dsk in self.disks:
8857         dsk[constants.IDISK_SIZE] = \
8858           int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8859                                         dsk[constants.IDISK_ADOPT])][0]))
8860
8861     elif self.op.disk_template == constants.DT_BLOCK:
8862       # Normalize and de-duplicate device paths
8863       all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8864                        for disk in self.disks])
8865       if len(all_disks) != len(self.disks):
8866         raise errors.OpPrereqError("Duplicate disk names given for adoption",
8867                                    errors.ECODE_INVAL)
8868       baddisks = [d for d in all_disks
8869                   if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8870       if baddisks:
8871         raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8872                                    " cannot be adopted" %
8873                                    (", ".join(baddisks),
8874                                     constants.ADOPTABLE_BLOCKDEV_ROOT),
8875                                    errors.ECODE_INVAL)
8876
8877       node_disks = self.rpc.call_bdev_sizes([pnode.name],
8878                                             list(all_disks))[pnode.name]
8879       node_disks.Raise("Cannot get block device information from node %s" %
8880                        pnode.name)
8881       node_disks = node_disks.payload
8882       delta = all_disks.difference(node_disks.keys())
8883       if delta:
8884         raise errors.OpPrereqError("Missing block device(s): %s" %
8885                                    utils.CommaJoin(delta),
8886                                    errors.ECODE_INVAL)
8887       for dsk in self.disks:
8888         dsk[constants.IDISK_SIZE] = \
8889           int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8890
8891     _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8892
8893     _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8894     # check OS parameters (remotely)
8895     _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8896
8897     _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8898
8899     # memory check on primary node
8900     if self.op.start:
8901       _CheckNodeFreeMemory(self, self.pnode.name,
8902                            "creating instance %s" % self.op.instance_name,
8903                            self.be_full[constants.BE_MEMORY],
8904                            self.op.hypervisor)
8905
8906     self.dry_run_result = list(nodenames)
8907
8908   def Exec(self, feedback_fn):
8909     """Create and add the instance to the cluster.
8910
8911     """
8912     instance = self.op.instance_name
8913     pnode_name = self.pnode.name
8914
8915     ht_kind = self.op.hypervisor
8916     if ht_kind in constants.HTS_REQ_PORT:
8917       network_port = self.cfg.AllocatePort()
8918     else:
8919       network_port = None
8920
8921     disks = _GenerateDiskTemplate(self,
8922                                   self.op.disk_template,
8923                                   instance, pnode_name,
8924                                   self.secondaries,
8925                                   self.disks,
8926                                   self.instance_file_storage_dir,
8927                                   self.op.file_driver,
8928                                   0,
8929                                   feedback_fn)
8930
8931     iobj = objects.Instance(name=instance, os=self.op.os_type,
8932                             primary_node=pnode_name,
8933                             nics=self.nics, disks=disks,
8934                             disk_template=self.op.disk_template,
8935                             admin_up=False,
8936                             network_port=network_port,
8937                             beparams=self.op.beparams,
8938                             hvparams=self.op.hvparams,
8939                             hypervisor=self.op.hypervisor,
8940                             osparams=self.op.osparams,
8941                             )
8942
8943     if self.op.tags:
8944       for tag in self.op.tags:
8945         iobj.AddTag(tag)
8946
8947     if self.adopt_disks:
8948       if self.op.disk_template == constants.DT_PLAIN:
8949         # rename LVs to the newly-generated names; we need to construct
8950         # 'fake' LV disks with the old data, plus the new unique_id
8951         tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8952         rename_to = []
8953         for t_dsk, a_dsk in zip(tmp_disks, self.disks):
8954           rename_to.append(t_dsk.logical_id)
8955           t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8956           self.cfg.SetDiskID(t_dsk, pnode_name)
8957         result = self.rpc.call_blockdev_rename(pnode_name,
8958                                                zip(tmp_disks, rename_to))
8959         result.Raise("Failed to rename adoped LVs")
8960     else:
8961       feedback_fn("* creating instance disks...")
8962       try:
8963         _CreateDisks(self, iobj)
8964       except errors.OpExecError:
8965         self.LogWarning("Device creation failed, reverting...")
8966         try:
8967           _RemoveDisks(self, iobj)
8968         finally:
8969           self.cfg.ReleaseDRBDMinors(instance)
8970           raise
8971
8972     feedback_fn("adding instance %s to cluster config" % instance)
8973
8974     self.cfg.AddInstance(iobj, self.proc.GetECId())
8975
8976     # Declare that we don't want to remove the instance lock anymore, as we've
8977     # added the instance to the config
8978     del self.remove_locks[locking.LEVEL_INSTANCE]
8979
8980     if self.op.mode == constants.INSTANCE_IMPORT:
8981       # Release unused nodes
8982       _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8983     else:
8984       # Release all nodes
8985       _ReleaseLocks(self, locking.LEVEL_NODE)
8986
8987     disk_abort = False
8988     if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8989       feedback_fn("* wiping instance disks...")
8990       try:
8991         _WipeDisks(self, iobj)
8992       except errors.OpExecError, err:
8993         logging.exception("Wiping disks failed")
8994         self.LogWarning("Wiping instance disks failed (%s)", err)
8995         disk_abort = True
8996
8997     if disk_abort:
8998       # Something is already wrong with the disks, don't do anything else
8999       pass
9000     elif self.op.wait_for_sync:
9001       disk_abort = not _WaitForSync(self, iobj)
9002     elif iobj.disk_template in constants.DTS_INT_MIRROR:
9003       # make sure the disks are not degraded (still sync-ing is ok)
9004       feedback_fn("* checking mirrors status")
9005       disk_abort = not _WaitForSync(self, iobj, oneshot=True)
9006     else:
9007       disk_abort = False
9008
9009     if disk_abort:
9010       _RemoveDisks(self, iobj)
9011       self.cfg.RemoveInstance(iobj.name)
9012       # Make sure the instance lock gets removed
9013       self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
9014       raise errors.OpExecError("There are some degraded disks for"
9015                                " this instance")
9016
9017     if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
9018       if self.op.mode == constants.INSTANCE_CREATE:
9019         if not self.op.no_install:
9020           pause_sync = (iobj.disk_template in constants.DTS_INT_MIRROR and
9021                         not self.op.wait_for_sync)
9022           if pause_sync:
9023             feedback_fn("* pausing disk sync to install instance OS")
9024             result = self.rpc.call_blockdev_pause_resume_sync(pnode_name,
9025                                                               iobj.disks, True)
9026             for idx, success in enumerate(result.payload):
9027               if not success:
9028                 logging.warn("pause-sync of instance %s for disk %d failed",
9029                              instance, idx)
9030
9031           feedback_fn("* running the instance OS create scripts...")
9032           # FIXME: pass debug option from opcode to backend
9033           result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
9034                                                  self.op.debug_level)
9035           if pause_sync:
9036             feedback_fn("* resuming disk sync")
9037             result = self.rpc.call_blockdev_pause_resume_sync(pnode_name,
9038                                                               iobj.disks, False)
9039             for idx, success in enumerate(result.payload):
9040               if not success:
9041                 logging.warn("resume-sync of instance %s for disk %d failed",
9042                              instance, idx)
9043
9044           result.Raise("Could not add os for instance %s"
9045                        " on node %s" % (instance, pnode_name))
9046
9047       elif self.op.mode == constants.INSTANCE_IMPORT:
9048         feedback_fn("* running the instance OS import scripts...")
9049
9050         transfers = []
9051
9052         for idx, image in enumerate(self.src_images):
9053           if not image:
9054             continue
9055
9056           # FIXME: pass debug option from opcode to backend
9057           dt = masterd.instance.DiskTransfer("disk/%s" % idx,
9058                                              constants.IEIO_FILE, (image, ),
9059                                              constants.IEIO_SCRIPT,
9060                                              (iobj.disks[idx], idx),
9061                                              None)
9062           transfers.append(dt)
9063
9064         import_result = \
9065           masterd.instance.TransferInstanceData(self, feedback_fn,
9066                                                 self.op.src_node, pnode_name,
9067                                                 self.pnode.secondary_ip,
9068                                                 iobj, transfers)
9069         if not compat.all(import_result):
9070           self.LogWarning("Some disks for instance %s on node %s were not"
9071                           " imported successfully" % (instance, pnode_name))
9072
9073       elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
9074         feedback_fn("* preparing remote import...")
9075         # The source cluster will stop the instance before attempting to make a
9076         # connection. In some cases stopping an instance can take a long time,
9077         # hence the shutdown timeout is added to the connection timeout.
9078         connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
9079                            self.op.source_shutdown_timeout)
9080         timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9081
9082         assert iobj.primary_node == self.pnode.name
9083         disk_results = \
9084           masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
9085                                         self.source_x509_ca,
9086                                         self._cds, timeouts)
9087         if not compat.all(disk_results):
9088           # TODO: Should the instance still be started, even if some disks
9089           # failed to import (valid for local imports, too)?
9090           self.LogWarning("Some disks for instance %s on node %s were not"
9091                           " imported successfully" % (instance, pnode_name))
9092
9093         # Run rename script on newly imported instance
9094         assert iobj.name == instance
9095         feedback_fn("Running rename script for %s" % instance)
9096         result = self.rpc.call_instance_run_rename(pnode_name, iobj,
9097                                                    self.source_instance_name,
9098                                                    self.op.debug_level)
9099         if result.fail_msg:
9100           self.LogWarning("Failed to run rename script for %s on node"
9101                           " %s: %s" % (instance, pnode_name, result.fail_msg))
9102
9103       else:
9104         # also checked in the prereq part
9105         raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
9106                                      % self.op.mode)
9107
9108     if self.op.start:
9109       iobj.admin_up = True
9110       self.cfg.Update(iobj, feedback_fn)
9111       logging.info("Starting instance %s on node %s", instance, pnode_name)
9112       feedback_fn("* starting instance...")
9113       result = self.rpc.call_instance_start(pnode_name, iobj,
9114                                             None, None, False)
9115       result.Raise("Could not start instance")
9116
9117     return list(iobj.all_nodes)
9118
9119
9120 class LUInstanceConsole(NoHooksLU):
9121   """Connect to an instance's console.
9122
9123   This is somewhat special in that it returns the command line that
9124   you need to run on the master node in order to connect to the
9125   console.
9126
9127   """
9128   REQ_BGL = False
9129
9130   def ExpandNames(self):
9131     self._ExpandAndLockInstance()
9132
9133   def CheckPrereq(self):
9134     """Check prerequisites.
9135
9136     This checks that the instance is in the cluster.
9137
9138     """
9139     self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9140     assert self.instance is not None, \
9141       "Cannot retrieve locked instance %s" % self.op.instance_name
9142     _CheckNodeOnline(self, self.instance.primary_node)
9143
9144   def Exec(self, feedback_fn):
9145     """Connect to the console of an instance
9146
9147     """
9148     instance = self.instance
9149     node = instance.primary_node
9150
9151     node_insts = self.rpc.call_instance_list([node],
9152                                              [instance.hypervisor])[node]
9153     node_insts.Raise("Can't get node information from %s" % node)
9154
9155     if instance.name not in node_insts.payload:
9156       if instance.admin_up:
9157         state = constants.INSTST_ERRORDOWN
9158       else:
9159         state = constants.INSTST_ADMINDOWN
9160       raise errors.OpExecError("Instance %s is not running (state %s)" %
9161                                (instance.name, state))
9162
9163     logging.debug("Connecting to console of %s on %s", instance.name, node)
9164
9165     return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
9166
9167
9168 def _GetInstanceConsole(cluster, instance):
9169   """Returns console information for an instance.
9170
9171   @type cluster: L{objects.Cluster}
9172   @type instance: L{objects.Instance}
9173   @rtype: dict
9174
9175   """
9176   hyper = hypervisor.GetHypervisor(instance.hypervisor)
9177   # beparams and hvparams are passed separately, to avoid editing the
9178   # instance and then saving the defaults in the instance itself.
9179   hvparams = cluster.FillHV(instance)
9180   beparams = cluster.FillBE(instance)
9181   console = hyper.GetInstanceConsole(instance, hvparams, beparams)
9182
9183   assert console.instance == instance.name
9184   assert console.Validate()
9185
9186   return console.ToDict()
9187
9188
9189 class LUInstanceReplaceDisks(LogicalUnit):
9190   """Replace the disks of an instance.
9191
9192   """
9193   HPATH = "mirrors-replace"
9194   HTYPE = constants.HTYPE_INSTANCE
9195   REQ_BGL = False
9196
9197   def CheckArguments(self):
9198     TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
9199                                   self.op.iallocator)
9200
9201   def ExpandNames(self):
9202     self._ExpandAndLockInstance()
9203
9204     assert locking.LEVEL_NODE not in self.needed_locks
9205     assert locking.LEVEL_NODEGROUP not in self.needed_locks
9206
9207     assert self.op.iallocator is None or self.op.remote_node is None, \
9208       "Conflicting options"
9209
9210     if self.op.remote_node is not None:
9211       self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9212
9213       # Warning: do not remove the locking of the new secondary here
9214       # unless DRBD8.AddChildren is changed to work in parallel;
9215       # currently it doesn't since parallel invocations of
9216       # FindUnusedMinor will conflict
9217       self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
9218       self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
9219     else:
9220       self.needed_locks[locking.LEVEL_NODE] = []
9221       self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9222
9223       if self.op.iallocator is not None:
9224         # iallocator will select a new node in the same group
9225         self.needed_locks[locking.LEVEL_NODEGROUP] = []
9226
9227     self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
9228                                    self.op.iallocator, self.op.remote_node,
9229                                    self.op.disks, False, self.op.early_release)
9230
9231     self.tasklets = [self.replacer]
9232
9233   def DeclareLocks(self, level):
9234     if level == locking.LEVEL_NODEGROUP:
9235       assert self.op.remote_node is None
9236       assert self.op.iallocator is not None
9237       assert not self.needed_locks[locking.LEVEL_NODEGROUP]
9238
9239       self.share_locks[locking.LEVEL_NODEGROUP] = 1
9240       self.needed_locks[locking.LEVEL_NODEGROUP] = \
9241         self.cfg.GetInstanceNodeGroups(self.op.instance_name)
9242
9243     elif level == locking.LEVEL_NODE:
9244       if self.op.iallocator is not None:
9245         assert self.op.remote_node is None
9246         assert not self.needed_locks[locking.LEVEL_NODE]
9247
9248         # Lock member nodes of all locked groups
9249         self.needed_locks[locking.LEVEL_NODE] = [node_name
9250           for group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
9251           for node_name in self.cfg.GetNodeGroup(group_uuid).members]
9252       else:
9253         self._LockInstancesNodes()
9254
9255   def BuildHooksEnv(self):
9256     """Build hooks env.
9257
9258     This runs on the master, the primary and all the secondaries.
9259
9260     """
9261     instance = self.replacer.instance
9262     env = {
9263       "MODE": self.op.mode,
9264       "NEW_SECONDARY": self.op.remote_node,
9265       "OLD_SECONDARY": instance.secondary_nodes[0],
9266       }
9267     env.update(_BuildInstanceHookEnvByObject(self, instance))
9268     return env
9269
9270   def BuildHooksNodes(self):
9271     """Build hooks nodes.
9272
9273     """
9274     instance = self.replacer.instance
9275     nl = [
9276       self.cfg.GetMasterNode(),
9277       instance.primary_node,
9278       ]
9279     if self.op.remote_node is not None:
9280       nl.append(self.op.remote_node)
9281     return nl, nl
9282
9283   def CheckPrereq(self):
9284     """Check prerequisites.
9285
9286     """
9287     assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
9288             self.op.iallocator is None)
9289
9290     owned_groups = self.owned_locks(locking.LEVEL_NODEGROUP)
9291     if owned_groups:
9292       _CheckInstanceNodeGroups(self.cfg, self.op.instance_name, owned_groups)
9293
9294     return LogicalUnit.CheckPrereq(self)
9295
9296
9297 class TLReplaceDisks(Tasklet):
9298   """Replaces disks for an instance.
9299
9300   Note: Locking is not within the scope of this class.
9301
9302   """
9303   def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
9304                disks, delay_iallocator, early_release):
9305     """Initializes this class.
9306
9307     """
9308     Tasklet.__init__(self, lu)
9309
9310     # Parameters
9311     self.instance_name = instance_name
9312     self.mode = mode
9313     self.iallocator_name = iallocator_name
9314     self.remote_node = remote_node
9315     self.disks = disks
9316     self.delay_iallocator = delay_iallocator
9317     self.early_release = early_release
9318
9319     # Runtime data
9320     self.instance = None
9321     self.new_node = None
9322     self.target_node = None
9323     self.other_node = None
9324     self.remote_node_info = None
9325     self.node_secondary_ip = None
9326
9327   @staticmethod
9328   def CheckArguments(mode, remote_node, iallocator):
9329     """Helper function for users of this class.
9330
9331     """
9332     # check for valid parameter combination
9333     if mode == constants.REPLACE_DISK_CHG:
9334       if remote_node is None and iallocator is None:
9335         raise errors.OpPrereqError("When changing the secondary either an"
9336                                    " iallocator script must be used or the"
9337                                    " new node given", errors.ECODE_INVAL)
9338
9339       if remote_node is not None and iallocator is not None:
9340         raise errors.OpPrereqError("Give either the iallocator or the new"
9341                                    " secondary, not both", errors.ECODE_INVAL)
9342
9343     elif remote_node is not None or iallocator is not None:
9344       # Not replacing the secondary
9345       raise errors.OpPrereqError("The iallocator and new node options can"
9346                                  " only be used when changing the"
9347                                  " secondary node", errors.ECODE_INVAL)
9348
9349   @staticmethod
9350   def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
9351     """Compute a new secondary node using an IAllocator.
9352
9353     """
9354     ial = IAllocator(lu.cfg, lu.rpc,
9355                      mode=constants.IALLOCATOR_MODE_RELOC,
9356                      name=instance_name,
9357                      relocate_from=list(relocate_from))
9358
9359     ial.Run(iallocator_name)
9360
9361     if not ial.success:
9362       raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
9363                                  " %s" % (iallocator_name, ial.info),
9364                                  errors.ECODE_NORES)
9365
9366     if len(ial.result) != ial.required_nodes:
9367       raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9368                                  " of nodes (%s), required %s" %
9369                                  (iallocator_name,
9370                                   len(ial.result), ial.required_nodes),
9371                                  errors.ECODE_FAULT)
9372
9373     remote_node_name = ial.result[0]
9374
9375     lu.LogInfo("Selected new secondary for instance '%s': %s",
9376                instance_name, remote_node_name)
9377
9378     return remote_node_name
9379
9380   def _FindFaultyDisks(self, node_name):
9381     """Wrapper for L{_FindFaultyInstanceDisks}.
9382
9383     """
9384     return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9385                                     node_name, True)
9386
9387   def _CheckDisksActivated(self, instance):
9388     """Checks if the instance disks are activated.
9389
9390     @param instance: The instance to check disks
9391     @return: True if they are activated, False otherwise
9392
9393     """
9394     nodes = instance.all_nodes
9395
9396     for idx, dev in enumerate(instance.disks):
9397       for node in nodes:
9398         self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9399         self.cfg.SetDiskID(dev, node)
9400
9401         result = self.rpc.call_blockdev_find(node, dev)
9402
9403         if result.offline:
9404           continue
9405         elif result.fail_msg or not result.payload:
9406           return False
9407
9408     return True
9409
9410   def CheckPrereq(self):
9411     """Check prerequisites.
9412
9413     This checks that the instance is in the cluster.
9414
9415     """
9416     self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9417     assert instance is not None, \
9418       "Cannot retrieve locked instance %s" % self.instance_name
9419
9420     if instance.disk_template != constants.DT_DRBD8:
9421       raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9422                                  " instances", errors.ECODE_INVAL)
9423
9424     if len(instance.secondary_nodes) != 1:
9425       raise errors.OpPrereqError("The instance has a strange layout,"
9426                                  " expected one secondary but found %d" %
9427                                  len(instance.secondary_nodes),
9428                                  errors.ECODE_FAULT)
9429
9430     if not self.delay_iallocator:
9431       self._CheckPrereq2()
9432
9433   def _CheckPrereq2(self):
9434     """Check prerequisites, second part.
9435
9436     This function should always be part of CheckPrereq. It was separated and is
9437     now called from Exec because during node evacuation iallocator was only
9438     called with an unmodified cluster model, not taking planned changes into
9439     account.
9440
9441     """
9442     instance = self.instance
9443     secondary_node = instance.secondary_nodes[0]
9444
9445     if self.iallocator_name is None:
9446       remote_node = self.remote_node
9447     else:
9448       remote_node = self._RunAllocator(self.lu, self.iallocator_name,
9449                                        instance.name, instance.secondary_nodes)
9450
9451     if remote_node is None:
9452       self.remote_node_info = None
9453     else:
9454       assert remote_node in self.lu.owned_locks(locking.LEVEL_NODE), \
9455              "Remote node '%s' is not locked" % remote_node
9456
9457       self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9458       assert self.remote_node_info is not None, \
9459         "Cannot retrieve locked node %s" % remote_node
9460
9461     if remote_node == self.instance.primary_node:
9462       raise errors.OpPrereqError("The specified node is the primary node of"
9463                                  " the instance", errors.ECODE_INVAL)
9464
9465     if remote_node == secondary_node:
9466       raise errors.OpPrereqError("The specified node is already the"
9467                                  " secondary node of the instance",
9468                                  errors.ECODE_INVAL)
9469
9470     if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9471                                     constants.REPLACE_DISK_CHG):
9472       raise errors.OpPrereqError("Cannot specify disks to be replaced",
9473                                  errors.ECODE_INVAL)
9474
9475     if self.mode == constants.REPLACE_DISK_AUTO:
9476       if not self._CheckDisksActivated(instance):
9477         raise errors.OpPrereqError("Please run activate-disks on instance %s"
9478                                    " first" % self.instance_name,
9479                                    errors.ECODE_STATE)
9480       faulty_primary = self._FindFaultyDisks(instance.primary_node)
9481       faulty_secondary = self._FindFaultyDisks(secondary_node)
9482
9483       if faulty_primary and faulty_secondary:
9484         raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9485                                    " one node and can not be repaired"
9486                                    " automatically" % self.instance_name,
9487                                    errors.ECODE_STATE)
9488
9489       if faulty_primary:
9490         self.disks = faulty_primary
9491         self.target_node = instance.primary_node
9492         self.other_node = secondary_node
9493         check_nodes = [self.target_node, self.other_node]
9494       elif faulty_secondary:
9495         self.disks = faulty_secondary
9496         self.target_node = secondary_node
9497         self.other_node = instance.primary_node
9498         check_nodes = [self.target_node, self.other_node]
9499       else:
9500         self.disks = []
9501         check_nodes = []
9502
9503     else:
9504       # Non-automatic modes
9505       if self.mode == constants.REPLACE_DISK_PRI:
9506         self.target_node = instance.primary_node
9507         self.other_node = secondary_node
9508         check_nodes = [self.target_node, self.other_node]
9509
9510       elif self.mode == constants.REPLACE_DISK_SEC:
9511         self.target_node = secondary_node
9512         self.other_node = instance.primary_node
9513         check_nodes = [self.target_node, self.other_node]
9514
9515       elif self.mode == constants.REPLACE_DISK_CHG:
9516         self.new_node = remote_node
9517         self.other_node = instance.primary_node
9518         self.target_node = secondary_node
9519         check_nodes = [self.new_node, self.other_node]
9520
9521         _CheckNodeNotDrained(self.lu, remote_node)
9522         _CheckNodeVmCapable(self.lu, remote_node)
9523
9524         old_node_info = self.cfg.GetNodeInfo(secondary_node)
9525         assert old_node_info is not None
9526         if old_node_info.offline and not self.early_release:
9527           # doesn't make sense to delay the release
9528           self.early_release = True
9529           self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9530                           " early-release mode", secondary_node)
9531
9532       else:
9533         raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9534                                      self.mode)
9535
9536       # If not specified all disks should be replaced
9537       if not self.disks:
9538         self.disks = range(len(self.instance.disks))
9539
9540     for node in check_nodes:
9541       _CheckNodeOnline(self.lu, node)
9542
9543     touched_nodes = frozenset(node_name for node_name in [self.new_node,
9544                                                           self.other_node,
9545                                                           self.target_node]
9546                               if node_name is not None)
9547
9548     # Release unneeded node locks
9549     _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9550
9551     # Release any owned node group
9552     if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9553       _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9554
9555     # Check whether disks are valid
9556     for disk_idx in self.disks:
9557       instance.FindDisk(disk_idx)
9558
9559     # Get secondary node IP addresses
9560     self.node_secondary_ip = dict((name, node.secondary_ip) for (name, node)
9561                                   in self.cfg.GetMultiNodeInfo(touched_nodes))
9562
9563   def Exec(self, feedback_fn):
9564     """Execute disk replacement.
9565
9566     This dispatches the disk replacement to the appropriate handler.
9567
9568     """
9569     if self.delay_iallocator:
9570       self._CheckPrereq2()
9571
9572     if __debug__:
9573       # Verify owned locks before starting operation
9574       owned_nodes = self.lu.owned_locks(locking.LEVEL_NODE)
9575       assert set(owned_nodes) == set(self.node_secondary_ip), \
9576           ("Incorrect node locks, owning %s, expected %s" %
9577            (owned_nodes, self.node_secondary_ip.keys()))
9578
9579       owned_instances = self.lu.owned_locks(locking.LEVEL_INSTANCE)
9580       assert list(owned_instances) == [self.instance_name], \
9581           "Instance '%s' not locked" % self.instance_name
9582
9583       assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9584           "Should not own any node group lock at this point"
9585
9586     if not self.disks:
9587       feedback_fn("No disks need replacement")
9588       return
9589
9590     feedback_fn("Replacing disk(s) %s for %s" %
9591                 (utils.CommaJoin(self.disks), self.instance.name))
9592
9593     activate_disks = (not self.instance.admin_up)
9594
9595     # Activate the instance disks if we're replacing them on a down instance
9596     if activate_disks:
9597       _StartInstanceDisks(self.lu, self.instance, True)
9598
9599     try:
9600       # Should we replace the secondary node?
9601       if self.new_node is not None:
9602         fn = self._ExecDrbd8Secondary
9603       else:
9604         fn = self._ExecDrbd8DiskOnly
9605
9606       result = fn(feedback_fn)
9607     finally:
9608       # Deactivate the instance disks if we're replacing them on a
9609       # down instance
9610       if activate_disks:
9611         _SafeShutdownInstanceDisks(self.lu, self.instance)
9612
9613     if __debug__:
9614       # Verify owned locks
9615       owned_nodes = self.lu.owned_locks(locking.LEVEL_NODE)
9616       nodes = frozenset(self.node_secondary_ip)
9617       assert ((self.early_release and not owned_nodes) or
9618               (not self.early_release and not (set(owned_nodes) - nodes))), \
9619         ("Not owning the correct locks, early_release=%s, owned=%r,"
9620          " nodes=%r" % (self.early_release, owned_nodes, nodes))
9621
9622     return result
9623
9624   def _CheckVolumeGroup(self, nodes):
9625     self.lu.LogInfo("Checking volume groups")
9626
9627     vgname = self.cfg.GetVGName()
9628
9629     # Make sure volume group exists on all involved nodes
9630     results = self.rpc.call_vg_list(nodes)
9631     if not results:
9632       raise errors.OpExecError("Can't list volume groups on the nodes")
9633
9634     for node in nodes:
9635       res = results[node]
9636       res.Raise("Error checking node %s" % node)
9637       if vgname not in res.payload:
9638         raise errors.OpExecError("Volume group '%s' not found on node %s" %
9639                                  (vgname, node))
9640
9641   def _CheckDisksExistence(self, nodes):
9642     # Check disk existence
9643     for idx, dev in enumerate(self.instance.disks):
9644       if idx not in self.disks:
9645         continue
9646
9647       for node in nodes:
9648         self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9649         self.cfg.SetDiskID(dev, node)
9650
9651         result = self.rpc.call_blockdev_find(node, dev)
9652
9653         msg = result.fail_msg
9654         if msg or not result.payload:
9655           if not msg:
9656             msg = "disk not found"
9657           raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9658                                    (idx, node, msg))
9659
9660   def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9661     for idx, dev in enumerate(self.instance.disks):
9662       if idx not in self.disks:
9663         continue
9664
9665       self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9666                       (idx, node_name))
9667
9668       if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9669                                    ldisk=ldisk):
9670         raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9671                                  " replace disks for instance %s" %
9672                                  (node_name, self.instance.name))
9673
9674   def _CreateNewStorage(self, node_name):
9675     """Create new storage on the primary or secondary node.
9676
9677     This is only used for same-node replaces, not for changing the
9678     secondary node, hence we don't want to modify the existing disk.
9679
9680     """
9681     iv_names = {}
9682
9683     for idx, dev in enumerate(self.instance.disks):
9684       if idx not in self.disks:
9685         continue
9686
9687       self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
9688
9689       self.cfg.SetDiskID(dev, node_name)
9690
9691       lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9692       names = _GenerateUniqueNames(self.lu, lv_names)
9693
9694       vg_data = dev.children[0].logical_id[0]
9695       lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9696                              logical_id=(vg_data, names[0]))
9697       vg_meta = dev.children[1].logical_id[0]
9698       lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9699                              logical_id=(vg_meta, names[1]))
9700
9701       new_lvs = [lv_data, lv_meta]
9702       old_lvs = [child.Copy() for child in dev.children]
9703       iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9704
9705       # we pass force_create=True to force the LVM creation
9706       for new_lv in new_lvs:
9707         _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9708                         _GetInstanceInfoText(self.instance), False)
9709
9710     return iv_names
9711
9712   def _CheckDevices(self, node_name, iv_names):
9713     for name, (dev, _, _) in iv_names.iteritems():
9714       self.cfg.SetDiskID(dev, node_name)
9715
9716       result = self.rpc.call_blockdev_find(node_name, dev)
9717
9718       msg = result.fail_msg
9719       if msg or not result.payload:
9720         if not msg:
9721           msg = "disk not found"
9722         raise errors.OpExecError("Can't find DRBD device %s: %s" %
9723                                  (name, msg))
9724
9725       if result.payload.is_degraded:
9726         raise errors.OpExecError("DRBD device %s is degraded!" % name)
9727
9728   def _RemoveOldStorage(self, node_name, iv_names):
9729     for name, (_, old_lvs, _) in iv_names.iteritems():
9730       self.lu.LogInfo("Remove logical volumes for %s" % name)
9731
9732       for lv in old_lvs:
9733         self.cfg.SetDiskID(lv, node_name)
9734
9735         msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9736         if msg:
9737           self.lu.LogWarning("Can't remove old LV: %s" % msg,
9738                              hint="remove unused LVs manually")
9739
9740   def _ExecDrbd8DiskOnly(self, feedback_fn): # pylint: disable=W0613
9741     """Replace a disk on the primary or secondary for DRBD 8.
9742
9743     The algorithm for replace is quite complicated:
9744
9745       1. for each disk to be replaced:
9746
9747         1. create new LVs on the target node with unique names
9748         1. detach old LVs from the drbd device
9749         1. rename old LVs to name_replaced.<time_t>
9750         1. rename new LVs to old LVs
9751         1. attach the new LVs (with the old names now) to the drbd device
9752
9753       1. wait for sync across all devices
9754
9755       1. for each modified disk:
9756
9757         1. remove old LVs (which have the name name_replaces.<time_t>)
9758
9759     Failures are not very well handled.
9760
9761     """
9762     steps_total = 6
9763
9764     # Step: check device activation
9765     self.lu.LogStep(1, steps_total, "Check device existence")
9766     self._CheckDisksExistence([self.other_node, self.target_node])
9767     self._CheckVolumeGroup([self.target_node, self.other_node])
9768
9769     # Step: check other node consistency
9770     self.lu.LogStep(2, steps_total, "Check peer consistency")
9771     self._CheckDisksConsistency(self.other_node,
9772                                 self.other_node == self.instance.primary_node,
9773                                 False)
9774
9775     # Step: create new storage
9776     self.lu.LogStep(3, steps_total, "Allocate new storage")
9777     iv_names = self._CreateNewStorage(self.target_node)
9778
9779     # Step: for each lv, detach+rename*2+attach
9780     self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9781     for dev, old_lvs, new_lvs in iv_names.itervalues():
9782       self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9783
9784       result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9785                                                      old_lvs)
9786       result.Raise("Can't detach drbd from local storage on node"
9787                    " %s for device %s" % (self.target_node, dev.iv_name))
9788       #dev.children = []
9789       #cfg.Update(instance)
9790
9791       # ok, we created the new LVs, so now we know we have the needed
9792       # storage; as such, we proceed on the target node to rename
9793       # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9794       # using the assumption that logical_id == physical_id (which in
9795       # turn is the unique_id on that node)
9796
9797       # FIXME(iustin): use a better name for the replaced LVs
9798       temp_suffix = int(time.time())
9799       ren_fn = lambda d, suff: (d.physical_id[0],
9800                                 d.physical_id[1] + "_replaced-%s" % suff)
9801
9802       # Build the rename list based on what LVs exist on the node
9803       rename_old_to_new = []
9804       for to_ren in old_lvs:
9805         result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9806         if not result.fail_msg and result.payload:
9807           # device exists
9808           rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9809
9810       self.lu.LogInfo("Renaming the old LVs on the target node")
9811       result = self.rpc.call_blockdev_rename(self.target_node,
9812                                              rename_old_to_new)
9813       result.Raise("Can't rename old LVs on node %s" % self.target_node)
9814
9815       # Now we rename the new LVs to the old LVs
9816       self.lu.LogInfo("Renaming the new LVs on the target node")
9817       rename_new_to_old = [(new, old.physical_id)
9818                            for old, new in zip(old_lvs, new_lvs)]
9819       result = self.rpc.call_blockdev_rename(self.target_node,
9820                                              rename_new_to_old)
9821       result.Raise("Can't rename new LVs on node %s" % self.target_node)
9822
9823       # Intermediate steps of in memory modifications
9824       for old, new in zip(old_lvs, new_lvs):
9825         new.logical_id = old.logical_id
9826         self.cfg.SetDiskID(new, self.target_node)
9827
9828       # We need to modify old_lvs so that removal later removes the
9829       # right LVs, not the newly added ones; note that old_lvs is a
9830       # copy here
9831       for disk in old_lvs:
9832         disk.logical_id = ren_fn(disk, temp_suffix)
9833         self.cfg.SetDiskID(disk, self.target_node)
9834
9835       # Now that the new lvs have the old name, we can add them to the device
9836       self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9837       result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9838                                                   new_lvs)
9839       msg = result.fail_msg
9840       if msg:
9841         for new_lv in new_lvs:
9842           msg2 = self.rpc.call_blockdev_remove(self.target_node,
9843                                                new_lv).fail_msg
9844           if msg2:
9845             self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9846                                hint=("cleanup manually the unused logical"
9847                                      "volumes"))
9848         raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9849
9850     cstep = 5
9851     if self.early_release:
9852       self.lu.LogStep(cstep, steps_total, "Removing old storage")
9853       cstep += 1
9854       self._RemoveOldStorage(self.target_node, iv_names)
9855       # WARNING: we release both node locks here, do not do other RPCs
9856       # than WaitForSync to the primary node
9857       _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9858                     names=[self.target_node, self.other_node])
9859
9860     # Wait for sync
9861     # This can fail as the old devices are degraded and _WaitForSync
9862     # does a combined result over all disks, so we don't check its return value
9863     self.lu.LogStep(cstep, steps_total, "Sync devices")
9864     cstep += 1
9865     _WaitForSync(self.lu, self.instance)
9866
9867     # Check all devices manually
9868     self._CheckDevices(self.instance.primary_node, iv_names)
9869
9870     # Step: remove old storage
9871     if not self.early_release:
9872       self.lu.LogStep(cstep, steps_total, "Removing old storage")
9873       cstep += 1
9874       self._RemoveOldStorage(self.target_node, iv_names)
9875
9876   def _ExecDrbd8Secondary(self, feedback_fn):
9877     """Replace the secondary node for DRBD 8.
9878
9879     The algorithm for replace is quite complicated:
9880       - for all disks of the instance:
9881         - create new LVs on the new node with same names
9882         - shutdown the drbd device on the old secondary
9883         - disconnect the drbd network on the primary
9884         - create the drbd device on the new secondary
9885         - network attach the drbd on the primary, using an artifice:
9886           the drbd code for Attach() will connect to the network if it
9887           finds a device which is connected to the good local disks but
9888           not network enabled
9889       - wait for sync across all devices
9890       - remove all disks from the old secondary
9891
9892     Failures are not very well handled.
9893
9894     """
9895     steps_total = 6
9896
9897     pnode = self.instance.primary_node
9898
9899     # Step: check device activation
9900     self.lu.LogStep(1, steps_total, "Check device existence")
9901     self._CheckDisksExistence([self.instance.primary_node])
9902     self._CheckVolumeGroup([self.instance.primary_node])
9903
9904     # Step: check other node consistency
9905     self.lu.LogStep(2, steps_total, "Check peer consistency")
9906     self._CheckDisksConsistency(self.instance.primary_node, True, True)
9907
9908     # Step: create new storage
9909     self.lu.LogStep(3, steps_total, "Allocate new storage")
9910     for idx, dev in enumerate(self.instance.disks):
9911       self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9912                       (self.new_node, idx))
9913       # we pass force_create=True to force LVM creation
9914       for new_lv in dev.children:
9915         _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9916                         _GetInstanceInfoText(self.instance), False)
9917
9918     # Step 4: dbrd minors and drbd setups changes
9919     # after this, we must manually remove the drbd minors on both the
9920     # error and the success paths
9921     self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9922     minors = self.cfg.AllocateDRBDMinor([self.new_node
9923                                          for dev in self.instance.disks],
9924                                         self.instance.name)
9925     logging.debug("Allocated minors %r", minors)
9926
9927     iv_names = {}
9928     for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9929       self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9930                       (self.new_node, idx))
9931       # create new devices on new_node; note that we create two IDs:
9932       # one without port, so the drbd will be activated without
9933       # networking information on the new node at this stage, and one
9934       # with network, for the latter activation in step 4
9935       (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9936       if self.instance.primary_node == o_node1:
9937         p_minor = o_minor1
9938       else:
9939         assert self.instance.primary_node == o_node2, "Three-node instance?"
9940         p_minor = o_minor2
9941
9942       new_alone_id = (self.instance.primary_node, self.new_node, None,
9943                       p_minor, new_minor, o_secret)
9944       new_net_id = (self.instance.primary_node, self.new_node, o_port,
9945                     p_minor, new_minor, o_secret)
9946
9947       iv_names[idx] = (dev, dev.children, new_net_id)
9948       logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9949                     new_net_id)
9950       new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9951                               logical_id=new_alone_id,
9952                               children=dev.children,
9953                               size=dev.size)
9954       try:
9955         _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9956                               _GetInstanceInfoText(self.instance), False)
9957       except errors.GenericError:
9958         self.cfg.ReleaseDRBDMinors(self.instance.name)
9959         raise
9960
9961     # We have new devices, shutdown the drbd on the old secondary
9962     for idx, dev in enumerate(self.instance.disks):
9963       self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9964       self.cfg.SetDiskID(dev, self.target_node)
9965       msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9966       if msg:
9967         self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9968                            "node: %s" % (idx, msg),
9969                            hint=("Please cleanup this device manually as"
9970                                  " soon as possible"))
9971
9972     self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9973     result = self.rpc.call_drbd_disconnect_net([pnode], self.node_secondary_ip,
9974                                                self.instance.disks)[pnode]
9975
9976     msg = result.fail_msg
9977     if msg:
9978       # detaches didn't succeed (unlikely)
9979       self.cfg.ReleaseDRBDMinors(self.instance.name)
9980       raise errors.OpExecError("Can't detach the disks from the network on"
9981                                " old node: %s" % (msg,))
9982
9983     # if we managed to detach at least one, we update all the disks of
9984     # the instance to point to the new secondary
9985     self.lu.LogInfo("Updating instance configuration")
9986     for dev, _, new_logical_id in iv_names.itervalues():
9987       dev.logical_id = new_logical_id
9988       self.cfg.SetDiskID(dev, self.instance.primary_node)
9989
9990     self.cfg.Update(self.instance, feedback_fn)
9991
9992     # and now perform the drbd attach
9993     self.lu.LogInfo("Attaching primary drbds to new secondary"
9994                     " (standalone => connected)")
9995     result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9996                                             self.new_node],
9997                                            self.node_secondary_ip,
9998                                            self.instance.disks,
9999                                            self.instance.name,
10000                                            False)
10001     for to_node, to_result in result.items():
10002       msg = to_result.fail_msg
10003       if msg:
10004         self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
10005                            to_node, msg,
10006                            hint=("please do a gnt-instance info to see the"
10007                                  " status of disks"))
10008     cstep = 5
10009     if self.early_release:
10010       self.lu.LogStep(cstep, steps_total, "Removing old storage")
10011       cstep += 1
10012       self._RemoveOldStorage(self.target_node, iv_names)
10013       # WARNING: we release all node locks here, do not do other RPCs
10014       # than WaitForSync to the primary node
10015       _ReleaseLocks(self.lu, locking.LEVEL_NODE,
10016                     names=[self.instance.primary_node,
10017                            self.target_node,
10018                            self.new_node])
10019
10020     # Wait for sync
10021     # This can fail as the old devices are degraded and _WaitForSync
10022     # does a combined result over all disks, so we don't check its return value
10023     self.lu.LogStep(cstep, steps_total, "Sync devices")
10024     cstep += 1
10025     _WaitForSync(self.lu, self.instance)
10026
10027     # Check all devices manually
10028     self._CheckDevices(self.instance.primary_node, iv_names)
10029
10030     # Step: remove old storage
10031     if not self.early_release:
10032       self.lu.LogStep(cstep, steps_total, "Removing old storage")
10033       self._RemoveOldStorage(self.target_node, iv_names)
10034
10035
10036 class LURepairNodeStorage(NoHooksLU):
10037   """Repairs the volume group on a node.
10038
10039   """
10040   REQ_BGL = False
10041
10042   def CheckArguments(self):
10043     self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
10044
10045     storage_type = self.op.storage_type
10046
10047     if (constants.SO_FIX_CONSISTENCY not in
10048         constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
10049       raise errors.OpPrereqError("Storage units of type '%s' can not be"
10050                                  " repaired" % storage_type,
10051                                  errors.ECODE_INVAL)
10052
10053   def ExpandNames(self):
10054     self.needed_locks = {
10055       locking.LEVEL_NODE: [self.op.node_name],
10056       }
10057
10058   def _CheckFaultyDisks(self, instance, node_name):
10059     """Ensure faulty disks abort the opcode or at least warn."""
10060     try:
10061       if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
10062                                   node_name, True):
10063         raise errors.OpPrereqError("Instance '%s' has faulty disks on"
10064                                    " node '%s'" % (instance.name, node_name),
10065                                    errors.ECODE_STATE)
10066     except errors.OpPrereqError, err:
10067       if self.op.ignore_consistency:
10068         self.proc.LogWarning(str(err.args[0]))
10069       else:
10070         raise
10071
10072   def CheckPrereq(self):
10073     """Check prerequisites.
10074
10075     """
10076     # Check whether any instance on this node has faulty disks
10077     for inst in _GetNodeInstances(self.cfg, self.op.node_name):
10078       if not inst.admin_up:
10079         continue
10080       check_nodes = set(inst.all_nodes)
10081       check_nodes.discard(self.op.node_name)
10082       for inst_node_name in check_nodes:
10083         self._CheckFaultyDisks(inst, inst_node_name)
10084
10085   def Exec(self, feedback_fn):
10086     feedback_fn("Repairing storage unit '%s' on %s ..." %
10087                 (self.op.name, self.op.node_name))
10088
10089     st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
10090     result = self.rpc.call_storage_execute(self.op.node_name,
10091                                            self.op.storage_type, st_args,
10092                                            self.op.name,
10093                                            constants.SO_FIX_CONSISTENCY)
10094     result.Raise("Failed to repair storage unit '%s' on %s" %
10095                  (self.op.name, self.op.node_name))
10096
10097
10098 class LUNodeEvacuate(NoHooksLU):
10099   """Evacuates instances off a list of nodes.
10100
10101   """
10102   REQ_BGL = False
10103
10104   def CheckArguments(self):
10105     _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
10106
10107   def ExpandNames(self):
10108     self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
10109
10110     if self.op.remote_node is not None:
10111       self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10112       assert self.op.remote_node
10113
10114       if self.op.remote_node == self.op.node_name:
10115         raise errors.OpPrereqError("Can not use evacuated node as a new"
10116                                    " secondary node", errors.ECODE_INVAL)
10117
10118       if self.op.mode != constants.IALLOCATOR_NEVAC_SEC:
10119         raise errors.OpPrereqError("Without the use of an iallocator only"
10120                                    " secondary instances can be evacuated",
10121                                    errors.ECODE_INVAL)
10122
10123     # Declare locks
10124     self.share_locks = _ShareAll()
10125     self.needed_locks = {
10126       locking.LEVEL_INSTANCE: [],
10127       locking.LEVEL_NODEGROUP: [],
10128       locking.LEVEL_NODE: [],
10129       }
10130
10131     # Determine nodes (via group) optimistically, needs verification once locks
10132     # have been acquired
10133     self.lock_nodes = self._DetermineNodes()
10134
10135   def _DetermineNodes(self):
10136     """Gets the list of nodes to operate on.
10137
10138     """
10139     if self.op.remote_node is None:
10140       # Iallocator will choose any node(s) in the same group
10141       group_nodes = self.cfg.GetNodeGroupMembersByNodes([self.op.node_name])
10142     else:
10143       group_nodes = frozenset([self.op.remote_node])
10144
10145     # Determine nodes to be locked
10146     return set([self.op.node_name]) | group_nodes
10147
10148   def _DetermineInstances(self):
10149     """Builds list of instances to operate on.
10150
10151     """
10152     assert self.op.mode in constants.IALLOCATOR_NEVAC_MODES
10153
10154     if self.op.mode == constants.IALLOCATOR_NEVAC_PRI:
10155       # Primary instances only
10156       inst_fn = _GetNodePrimaryInstances
10157       assert self.op.remote_node is None, \
10158         "Evacuating primary instances requires iallocator"
10159     elif self.op.mode == constants.IALLOCATOR_NEVAC_SEC:
10160       # Secondary instances only
10161       inst_fn = _GetNodeSecondaryInstances
10162     else:
10163       # All instances
10164       assert self.op.mode == constants.IALLOCATOR_NEVAC_ALL
10165       inst_fn = _GetNodeInstances
10166       # TODO: In 2.6, change the iallocator interface to take an evacuation mode
10167       # per instance
10168       raise errors.OpPrereqError("Due to an issue with the iallocator"
10169                                  " interface it is not possible to evacuate"
10170                                  " all instances at once; specify explicitly"
10171                                  " whether to evacuate primary or secondary"
10172                                  " instances",
10173                                  errors.ECODE_INVAL)
10174
10175     return inst_fn(self.cfg, self.op.node_name)
10176
10177   def DeclareLocks(self, level):
10178     if level == locking.LEVEL_INSTANCE:
10179       # Lock instances optimistically, needs verification once node and group
10180       # locks have been acquired
10181       self.needed_locks[locking.LEVEL_INSTANCE] = \
10182         set(i.name for i in self._DetermineInstances())
10183
10184     elif level == locking.LEVEL_NODEGROUP:
10185       # Lock node groups for all potential target nodes optimistically, needs
10186       # verification once nodes have been acquired
10187       self.needed_locks[locking.LEVEL_NODEGROUP] = \
10188         self.cfg.GetNodeGroupsFromNodes(self.lock_nodes)
10189
10190     elif level == locking.LEVEL_NODE:
10191       self.needed_locks[locking.LEVEL_NODE] = self.lock_nodes
10192
10193   def CheckPrereq(self):
10194     # Verify locks
10195     owned_instances = self.owned_locks(locking.LEVEL_INSTANCE)
10196     owned_nodes = self.owned_locks(locking.LEVEL_NODE)
10197     owned_groups = self.owned_locks(locking.LEVEL_NODEGROUP)
10198
10199     need_nodes = self._DetermineNodes()
10200
10201     if not owned_nodes.issuperset(need_nodes):
10202       raise errors.OpPrereqError("Nodes in same group as '%s' changed since"
10203                                  " locks were acquired, current nodes are"
10204                                  " are '%s', used to be '%s'; retry the"
10205                                  " operation" %
10206                                  (self.op.node_name,
10207                                   utils.CommaJoin(need_nodes),
10208                                   utils.CommaJoin(owned_nodes)),
10209                                  errors.ECODE_STATE)
10210
10211     wanted_groups = self.cfg.GetNodeGroupsFromNodes(owned_nodes)
10212     if owned_groups != wanted_groups:
10213       raise errors.OpExecError("Node groups changed since locks were acquired,"
10214                                " current groups are '%s', used to be '%s';"
10215                                " retry the operation" %
10216                                (utils.CommaJoin(wanted_groups),
10217                                 utils.CommaJoin(owned_groups)))
10218
10219     # Determine affected instances
10220     self.instances = self._DetermineInstances()
10221     self.instance_names = [i.name for i in self.instances]
10222
10223     if set(self.instance_names) != owned_instances:
10224       raise errors.OpExecError("Instances on node '%s' changed since locks"
10225                                " were acquired, current instances are '%s',"
10226                                " used to be '%s'; retry the operation" %
10227                                (self.op.node_name,
10228                                 utils.CommaJoin(self.instance_names),
10229                                 utils.CommaJoin(owned_instances)))
10230
10231     if self.instance_names:
10232       self.LogInfo("Evacuating instances from node '%s': %s",
10233                    self.op.node_name,
10234                    utils.CommaJoin(utils.NiceSort(self.instance_names)))
10235     else:
10236       self.LogInfo("No instances to evacuate from node '%s'",
10237                    self.op.node_name)
10238
10239     if self.op.remote_node is not None:
10240       for i in self.instances:
10241         if i.primary_node == self.op.remote_node:
10242           raise errors.OpPrereqError("Node %s is the primary node of"
10243                                      " instance %s, cannot use it as"
10244                                      " secondary" %
10245                                      (self.op.remote_node, i.name),
10246                                      errors.ECODE_INVAL)
10247
10248   def Exec(self, feedback_fn):
10249     assert (self.op.iallocator is not None) ^ (self.op.remote_node is not None)
10250
10251     if not self.instance_names:
10252       # No instances to evacuate
10253       jobs = []
10254
10255     elif self.op.iallocator is not None:
10256       # TODO: Implement relocation to other group
10257       ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_NODE_EVAC,
10258                        evac_mode=self.op.mode,
10259                        instances=list(self.instance_names))
10260
10261       ial.Run(self.op.iallocator)
10262
10263       if not ial.success:
10264         raise errors.OpPrereqError("Can't compute node evacuation using"
10265                                    " iallocator '%s': %s" %
10266                                    (self.op.iallocator, ial.info),
10267                                    errors.ECODE_NORES)
10268
10269       jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, True)
10270
10271     elif self.op.remote_node is not None:
10272       assert self.op.mode == constants.IALLOCATOR_NEVAC_SEC
10273       jobs = [
10274         [opcodes.OpInstanceReplaceDisks(instance_name=instance_name,
10275                                         remote_node=self.op.remote_node,
10276                                         disks=[],
10277                                         mode=constants.REPLACE_DISK_CHG,
10278                                         early_release=self.op.early_release)]
10279         for instance_name in self.instance_names
10280         ]
10281
10282     else:
10283       raise errors.ProgrammerError("No iallocator or remote node")
10284
10285     return ResultWithJobs(jobs)
10286
10287
10288 def _SetOpEarlyRelease(early_release, op):
10289   """Sets C{early_release} flag on opcodes if available.
10290
10291   """
10292   try:
10293     op.early_release = early_release
10294   except AttributeError:
10295     assert not isinstance(op, opcodes.OpInstanceReplaceDisks)
10296
10297   return op
10298
10299
10300 def _NodeEvacDest(use_nodes, group, nodes):
10301   """Returns group or nodes depending on caller's choice.
10302
10303   """
10304   if use_nodes:
10305     return utils.CommaJoin(nodes)
10306   else:
10307     return group
10308
10309
10310 def _LoadNodeEvacResult(lu, alloc_result, early_release, use_nodes):
10311   """Unpacks the result of change-group and node-evacuate iallocator requests.
10312
10313   Iallocator modes L{constants.IALLOCATOR_MODE_NODE_EVAC} and
10314   L{constants.IALLOCATOR_MODE_CHG_GROUP}.
10315
10316   @type lu: L{LogicalUnit}
10317   @param lu: Logical unit instance
10318   @type alloc_result: tuple/list
10319   @param alloc_result: Result from iallocator
10320   @type early_release: bool
10321   @param early_release: Whether to release locks early if possible
10322   @type use_nodes: bool
10323   @param use_nodes: Whether to display node names instead of groups
10324
10325   """
10326   (moved, failed, jobs) = alloc_result
10327
10328   if failed:
10329     failreason = utils.CommaJoin("%s (%s)" % (name, reason)
10330                                  for (name, reason) in failed)
10331     lu.LogWarning("Unable to evacuate instances %s", failreason)
10332     raise errors.OpExecError("Unable to evacuate instances %s" % failreason)
10333
10334   if moved:
10335     lu.LogInfo("Instances to be moved: %s",
10336                utils.CommaJoin("%s (to %s)" %
10337                                (name, _NodeEvacDest(use_nodes, group, nodes))
10338                                for (name, group, nodes) in moved))
10339
10340   return [map(compat.partial(_SetOpEarlyRelease, early_release),
10341               map(opcodes.OpCode.LoadOpCode, ops))
10342           for ops in jobs]
10343
10344
10345 class LUInstanceGrowDisk(LogicalUnit):
10346   """Grow a disk of an instance.
10347
10348   """
10349   HPATH = "disk-grow"
10350   HTYPE = constants.HTYPE_INSTANCE
10351   REQ_BGL = False
10352
10353   def ExpandNames(self):
10354     self._ExpandAndLockInstance()
10355     self.needed_locks[locking.LEVEL_NODE] = []
10356     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10357
10358   def DeclareLocks(self, level):
10359     if level == locking.LEVEL_NODE:
10360       self._LockInstancesNodes()
10361
10362   def BuildHooksEnv(self):
10363     """Build hooks env.
10364
10365     This runs on the master, the primary and all the secondaries.
10366
10367     """
10368     env = {
10369       "DISK": self.op.disk,
10370       "AMOUNT": self.op.amount,
10371       }
10372     env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10373     return env
10374
10375   def BuildHooksNodes(self):
10376     """Build hooks nodes.
10377
10378     """
10379     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10380     return (nl, nl)
10381
10382   def CheckPrereq(self):
10383     """Check prerequisites.
10384
10385     This checks that the instance is in the cluster.
10386
10387     """
10388     instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10389     assert instance is not None, \
10390       "Cannot retrieve locked instance %s" % self.op.instance_name
10391     nodenames = list(instance.all_nodes)
10392     for node in nodenames:
10393       _CheckNodeOnline(self, node)
10394
10395     self.instance = instance
10396
10397     if instance.disk_template not in constants.DTS_GROWABLE:
10398       raise errors.OpPrereqError("Instance's disk layout does not support"
10399                                  " growing", errors.ECODE_INVAL)
10400
10401     self.disk = instance.FindDisk(self.op.disk)
10402
10403     if instance.disk_template not in (constants.DT_FILE,
10404                                       constants.DT_SHARED_FILE):
10405       # TODO: check the free disk space for file, when that feature will be
10406       # supported
10407       _CheckNodesFreeDiskPerVG(self, nodenames,
10408                                self.disk.ComputeGrowth(self.op.amount))
10409
10410   def Exec(self, feedback_fn):
10411     """Execute disk grow.
10412
10413     """
10414     instance = self.instance
10415     disk = self.disk
10416
10417     disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
10418     if not disks_ok:
10419       raise errors.OpExecError("Cannot activate block device to grow")
10420
10421     # First run all grow ops in dry-run mode
10422     for node in instance.all_nodes:
10423       self.cfg.SetDiskID(disk, node)
10424       result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
10425       result.Raise("Grow request failed to node %s" % node)
10426
10427     # We know that (as far as we can test) operations across different
10428     # nodes will succeed, time to run it for real
10429     for node in instance.all_nodes:
10430       self.cfg.SetDiskID(disk, node)
10431       result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
10432       result.Raise("Grow request failed to node %s" % node)
10433
10434       # TODO: Rewrite code to work properly
10435       # DRBD goes into sync mode for a short amount of time after executing the
10436       # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
10437       # calling "resize" in sync mode fails. Sleeping for a short amount of
10438       # time is a work-around.
10439       time.sleep(5)
10440
10441     disk.RecordGrow(self.op.amount)
10442     self.cfg.Update(instance, feedback_fn)
10443     if self.op.wait_for_sync:
10444       disk_abort = not _WaitForSync(self, instance, disks=[disk])
10445       if disk_abort:
10446         self.proc.LogWarning("Disk sync-ing has not returned a good"
10447                              " status; please check the instance")
10448       if not instance.admin_up:
10449         _SafeShutdownInstanceDisks(self, instance, disks=[disk])
10450     elif not instance.admin_up:
10451       self.proc.LogWarning("Not shutting down the disk even if the instance is"
10452                            " not supposed to be running because no wait for"
10453                            " sync mode was requested")
10454
10455
10456 class LUInstanceQueryData(NoHooksLU):
10457   """Query runtime instance data.
10458
10459   """
10460   REQ_BGL = False
10461
10462   def ExpandNames(self):
10463     self.needed_locks = {}
10464
10465     # Use locking if requested or when non-static information is wanted
10466     if not (self.op.static or self.op.use_locking):
10467       self.LogWarning("Non-static data requested, locks need to be acquired")
10468       self.op.use_locking = True
10469
10470     if self.op.instances or not self.op.use_locking:
10471       # Expand instance names right here
10472       self.wanted_names = _GetWantedInstances(self, self.op.instances)
10473     else:
10474       # Will use acquired locks
10475       self.wanted_names = None
10476
10477     if self.op.use_locking:
10478       self.share_locks = _ShareAll()
10479
10480       if self.wanted_names is None:
10481         self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
10482       else:
10483         self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
10484
10485       self.needed_locks[locking.LEVEL_NODE] = []
10486       self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10487
10488   def DeclareLocks(self, level):
10489     if self.op.use_locking and level == locking.LEVEL_NODE:
10490       self._LockInstancesNodes()
10491
10492   def CheckPrereq(self):
10493     """Check prerequisites.
10494
10495     This only checks the optional instance list against the existing names.
10496
10497     """
10498     if self.wanted_names is None:
10499       assert self.op.use_locking, "Locking was not used"
10500       self.wanted_names = self.owned_locks(locking.LEVEL_INSTANCE)
10501
10502     self.wanted_instances = \
10503         map(compat.snd, self.cfg.GetMultiInstanceInfo(self.wanted_names))
10504
10505   def _ComputeBlockdevStatus(self, node, instance_name, dev):
10506     """Returns the status of a block device
10507
10508     """
10509     if self.op.static or not node:
10510       return None
10511
10512     self.cfg.SetDiskID(dev, node)
10513
10514     result = self.rpc.call_blockdev_find(node, dev)
10515     if result.offline:
10516       return None
10517
10518     result.Raise("Can't compute disk status for %s" % instance_name)
10519
10520     status = result.payload
10521     if status is None:
10522       return None
10523
10524     return (status.dev_path, status.major, status.minor,
10525             status.sync_percent, status.estimated_time,
10526             status.is_degraded, status.ldisk_status)
10527
10528   def _ComputeDiskStatus(self, instance, snode, dev):
10529     """Compute block device status.
10530
10531     """
10532     if dev.dev_type in constants.LDS_DRBD:
10533       # we change the snode then (otherwise we use the one passed in)
10534       if dev.logical_id[0] == instance.primary_node:
10535         snode = dev.logical_id[1]
10536       else:
10537         snode = dev.logical_id[0]
10538
10539     dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
10540                                               instance.name, dev)
10541     dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
10542
10543     if dev.children:
10544       dev_children = map(compat.partial(self._ComputeDiskStatus,
10545                                         instance, snode),
10546                          dev.children)
10547     else:
10548       dev_children = []
10549
10550     return {
10551       "iv_name": dev.iv_name,
10552       "dev_type": dev.dev_type,
10553       "logical_id": dev.logical_id,
10554       "physical_id": dev.physical_id,
10555       "pstatus": dev_pstatus,
10556       "sstatus": dev_sstatus,
10557       "children": dev_children,
10558       "mode": dev.mode,
10559       "size": dev.size,
10560       }
10561
10562   def Exec(self, feedback_fn):
10563     """Gather and return data"""
10564     result = {}
10565
10566     cluster = self.cfg.GetClusterInfo()
10567
10568     pri_nodes = self.cfg.GetMultiNodeInfo(i.primary_node
10569                                           for i in self.wanted_instances)
10570     for instance, (_, pnode) in zip(self.wanted_instances, pri_nodes):
10571       if self.op.static or pnode.offline:
10572         remote_state = None
10573         if pnode.offline:
10574           self.LogWarning("Primary node %s is marked offline, returning static"
10575                           " information only for instance %s" %
10576                           (pnode.name, instance.name))
10577       else:
10578         remote_info = self.rpc.call_instance_info(instance.primary_node,
10579                                                   instance.name,
10580                                                   instance.hypervisor)
10581         remote_info.Raise("Error checking node %s" % instance.primary_node)
10582         remote_info = remote_info.payload
10583         if remote_info and "state" in remote_info:
10584           remote_state = "up"
10585         else:
10586           remote_state = "down"
10587
10588       if instance.admin_up:
10589         config_state = "up"
10590       else:
10591         config_state = "down"
10592
10593       disks = map(compat.partial(self._ComputeDiskStatus, instance, None),
10594                   instance.disks)
10595
10596       result[instance.name] = {
10597         "name": instance.name,
10598         "config_state": config_state,
10599         "run_state": remote_state,
10600         "pnode": instance.primary_node,
10601         "snodes": instance.secondary_nodes,
10602         "os": instance.os,
10603         # this happens to be the same format used for hooks
10604         "nics": _NICListToTuple(self, instance.nics),
10605         "disk_template": instance.disk_template,
10606         "disks": disks,
10607         "hypervisor": instance.hypervisor,
10608         "network_port": instance.network_port,
10609         "hv_instance": instance.hvparams,
10610         "hv_actual": cluster.FillHV(instance, skip_globals=True),
10611         "be_instance": instance.beparams,
10612         "be_actual": cluster.FillBE(instance),
10613         "os_instance": instance.osparams,
10614         "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
10615         "serial_no": instance.serial_no,
10616         "mtime": instance.mtime,
10617         "ctime": instance.ctime,
10618         "uuid": instance.uuid,
10619         }
10620
10621     return result
10622
10623
10624 class LUInstanceSetParams(LogicalUnit):
10625   """Modifies an instances's parameters.
10626
10627   """
10628   HPATH = "instance-modify"
10629   HTYPE = constants.HTYPE_INSTANCE
10630   REQ_BGL = False
10631
10632   def CheckArguments(self):
10633     if not (self.op.nics or self.op.disks or self.op.disk_template or
10634             self.op.hvparams or self.op.beparams or self.op.os_name):
10635       raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
10636
10637     if self.op.hvparams:
10638       _CheckGlobalHvParams(self.op.hvparams)
10639
10640     # Disk validation
10641     disk_addremove = 0
10642     for disk_op, disk_dict in self.op.disks:
10643       utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
10644       if disk_op == constants.DDM_REMOVE:
10645         disk_addremove += 1
10646         continue
10647       elif disk_op == constants.DDM_ADD:
10648         disk_addremove += 1
10649       else:
10650         if not isinstance(disk_op, int):
10651           raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
10652         if not isinstance(disk_dict, dict):
10653           msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
10654           raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10655
10656       if disk_op == constants.DDM_ADD:
10657         mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
10658         if mode not in constants.DISK_ACCESS_SET:
10659           raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
10660                                      errors.ECODE_INVAL)
10661         size = disk_dict.get(constants.IDISK_SIZE, None)
10662         if size is None:
10663           raise errors.OpPrereqError("Required disk parameter size missing",
10664                                      errors.ECODE_INVAL)
10665         try:
10666           size = int(size)
10667         except (TypeError, ValueError), err:
10668           raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10669                                      str(err), errors.ECODE_INVAL)
10670         disk_dict[constants.IDISK_SIZE] = size
10671       else:
10672         # modification of disk
10673         if constants.IDISK_SIZE in disk_dict:
10674           raise errors.OpPrereqError("Disk size change not possible, use"
10675                                      " grow-disk", errors.ECODE_INVAL)
10676
10677     if disk_addremove > 1:
10678       raise errors.OpPrereqError("Only one disk add or remove operation"
10679                                  " supported at a time", errors.ECODE_INVAL)
10680
10681     if self.op.disks and self.op.disk_template is not None:
10682       raise errors.OpPrereqError("Disk template conversion and other disk"
10683                                  " changes not supported at the same time",
10684                                  errors.ECODE_INVAL)
10685
10686     if (self.op.disk_template and
10687         self.op.disk_template in constants.DTS_INT_MIRROR and
10688         self.op.remote_node is None):
10689       raise errors.OpPrereqError("Changing the disk template to a mirrored"
10690                                  " one requires specifying a secondary node",
10691                                  errors.ECODE_INVAL)
10692
10693     # NIC validation
10694     nic_addremove = 0
10695     for nic_op, nic_dict in self.op.nics:
10696       utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10697       if nic_op == constants.DDM_REMOVE:
10698         nic_addremove += 1
10699         continue
10700       elif nic_op == constants.DDM_ADD:
10701         nic_addremove += 1
10702       else:
10703         if not isinstance(nic_op, int):
10704           raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10705         if not isinstance(nic_dict, dict):
10706           msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10707           raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10708
10709       # nic_dict should be a dict
10710       nic_ip = nic_dict.get(constants.INIC_IP, None)
10711       if nic_ip is not None:
10712         if nic_ip.lower() == constants.VALUE_NONE:
10713           nic_dict[constants.INIC_IP] = None
10714         else:
10715           if not netutils.IPAddress.IsValid(nic_ip):
10716             raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10717                                        errors.ECODE_INVAL)
10718
10719       nic_bridge = nic_dict.get("bridge", None)
10720       nic_link = nic_dict.get(constants.INIC_LINK, None)
10721       if nic_bridge and nic_link:
10722         raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10723                                    " at the same time", errors.ECODE_INVAL)
10724       elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10725         nic_dict["bridge"] = None
10726       elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10727         nic_dict[constants.INIC_LINK] = None
10728
10729       if nic_op == constants.DDM_ADD:
10730         nic_mac = nic_dict.get(constants.INIC_MAC, None)
10731         if nic_mac is None:
10732           nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10733
10734       if constants.INIC_MAC in nic_dict:
10735         nic_mac = nic_dict[constants.INIC_MAC]
10736         if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10737           nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10738
10739         if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10740           raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10741                                      " modifying an existing nic",
10742                                      errors.ECODE_INVAL)
10743
10744     if nic_addremove > 1:
10745       raise errors.OpPrereqError("Only one NIC add or remove operation"
10746                                  " supported at a time", errors.ECODE_INVAL)
10747
10748   def ExpandNames(self):
10749     self._ExpandAndLockInstance()
10750     self.needed_locks[locking.LEVEL_NODE] = []
10751     self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10752
10753   def DeclareLocks(self, level):
10754     if level == locking.LEVEL_NODE:
10755       self._LockInstancesNodes()
10756       if self.op.disk_template and self.op.remote_node:
10757         self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10758         self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10759
10760   def BuildHooksEnv(self):
10761     """Build hooks env.
10762
10763     This runs on the master, primary and secondaries.
10764
10765     """
10766     args = dict()
10767     if constants.BE_MEMORY in self.be_new:
10768       args["memory"] = self.be_new[constants.BE_MEMORY]
10769     if constants.BE_VCPUS in self.be_new:
10770       args["vcpus"] = self.be_new[constants.BE_VCPUS]
10771     # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10772     # information at all.
10773     if self.op.nics:
10774       args["nics"] = []
10775       nic_override = dict(self.op.nics)
10776       for idx, nic in enumerate(self.instance.nics):
10777         if idx in nic_override:
10778           this_nic_override = nic_override[idx]
10779         else:
10780           this_nic_override = {}
10781         if constants.INIC_IP in this_nic_override:
10782           ip = this_nic_override[constants.INIC_IP]
10783         else:
10784           ip = nic.ip
10785         if constants.INIC_MAC in this_nic_override:
10786           mac = this_nic_override[constants.INIC_MAC]
10787         else:
10788           mac = nic.mac
10789         if idx in self.nic_pnew:
10790           nicparams = self.nic_pnew[idx]
10791         else:
10792           nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10793         mode = nicparams[constants.NIC_MODE]
10794         link = nicparams[constants.NIC_LINK]
10795         args["nics"].append((ip, mac, mode, link))
10796       if constants.DDM_ADD in nic_override:
10797         ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10798         mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10799         nicparams = self.nic_pnew[constants.DDM_ADD]
10800         mode = nicparams[constants.NIC_MODE]
10801         link = nicparams[constants.NIC_LINK]
10802         args["nics"].append((ip, mac, mode, link))
10803       elif constants.DDM_REMOVE in nic_override:
10804         del args["nics"][-1]
10805
10806     env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10807     if self.op.disk_template:
10808       env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10809
10810     return env
10811
10812   def BuildHooksNodes(self):
10813     """Build hooks nodes.
10814
10815     """
10816     nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10817     return (nl, nl)
10818
10819   def CheckPrereq(self):
10820     """Check prerequisites.
10821
10822     This only checks the instance list against the existing names.
10823
10824     """
10825     # checking the new params on the primary/secondary nodes
10826
10827     instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10828     cluster = self.cluster = self.cfg.GetClusterInfo()
10829     assert self.instance is not None, \
10830       "Cannot retrieve locked instance %s" % self.op.instance_name
10831     pnode = instance.primary_node
10832     nodelist = list(instance.all_nodes)
10833
10834     # OS change
10835     if self.op.os_name and not self.op.force:
10836       _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10837                       self.op.force_variant)
10838       instance_os = self.op.os_name
10839     else:
10840       instance_os = instance.os
10841
10842     if self.op.disk_template:
10843       if instance.disk_template == self.op.disk_template:
10844         raise errors.OpPrereqError("Instance already has disk template %s" %
10845                                    instance.disk_template, errors.ECODE_INVAL)
10846
10847       if (instance.disk_template,
10848           self.op.disk_template) not in self._DISK_CONVERSIONS:
10849         raise errors.OpPrereqError("Unsupported disk template conversion from"
10850                                    " %s to %s" % (instance.disk_template,
10851                                                   self.op.disk_template),
10852                                    errors.ECODE_INVAL)
10853       _CheckInstanceDown(self, instance, "cannot change disk template")
10854       if self.op.disk_template in constants.DTS_INT_MIRROR:
10855         if self.op.remote_node == pnode:
10856           raise errors.OpPrereqError("Given new secondary node %s is the same"
10857                                      " as the primary node of the instance" %
10858                                      self.op.remote_node, errors.ECODE_STATE)
10859         _CheckNodeOnline(self, self.op.remote_node)
10860         _CheckNodeNotDrained(self, self.op.remote_node)
10861         # FIXME: here we assume that the old instance type is DT_PLAIN
10862         assert instance.disk_template == constants.DT_PLAIN
10863         disks = [{constants.IDISK_SIZE: d.size,
10864                   constants.IDISK_VG: d.logical_id[0]}
10865                  for d in instance.disks]
10866         required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10867         _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10868
10869     # hvparams processing
10870     if self.op.hvparams:
10871       hv_type = instance.hypervisor
10872       i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10873       utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10874       hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10875
10876       # local check
10877       hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10878       _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10879       self.hv_new = hv_new # the new actual values
10880       self.hv_inst = i_hvdict # the new dict (without defaults)
10881     else:
10882       self.hv_new = self.hv_inst = {}
10883
10884     # beparams processing
10885     if self.op.beparams:
10886       i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10887                                    use_none=True)
10888       utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10889       be_new = cluster.SimpleFillBE(i_bedict)
10890       self.be_new = be_new # the new actual values
10891       self.be_inst = i_bedict # the new dict (without defaults)
10892     else:
10893       self.be_new = self.be_inst = {}
10894     be_old = cluster.FillBE(instance)
10895
10896     # osparams processing
10897     if self.op.osparams:
10898       i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10899       _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10900       self.os_inst = i_osdict # the new dict (without defaults)
10901     else:
10902       self.os_inst = {}
10903
10904     self.warn = []
10905
10906     if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10907         be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10908       mem_check_list = [pnode]
10909       if be_new[constants.BE_AUTO_BALANCE]:
10910         # either we changed auto_balance to yes or it was from before
10911         mem_check_list.extend(instance.secondary_nodes)
10912       instance_info = self.rpc.call_instance_info(pnode, instance.name,
10913                                                   instance.hypervisor)
10914       nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10915                                          instance.hypervisor)
10916       pninfo = nodeinfo[pnode]
10917       msg = pninfo.fail_msg
10918       if msg:
10919         # Assume the primary node is unreachable and go ahead
10920         self.warn.append("Can't get info from primary node %s: %s" %
10921                          (pnode, msg))
10922       elif not isinstance(pninfo.payload.get("memory_free", None), int):
10923         self.warn.append("Node data from primary node %s doesn't contain"
10924                          " free memory information" % pnode)
10925       elif instance_info.fail_msg:
10926         self.warn.append("Can't get instance runtime information: %s" %
10927                         instance_info.fail_msg)
10928       else:
10929         if instance_info.payload:
10930           current_mem = int(instance_info.payload["memory"])
10931         else:
10932           # Assume instance not running
10933           # (there is a slight race condition here, but it's not very probable,
10934           # and we have no other way to check)
10935           current_mem = 0
10936         miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10937                     pninfo.payload["memory_free"])
10938         if miss_mem > 0:
10939           raise errors.OpPrereqError("This change will prevent the instance"
10940                                      " from starting, due to %d MB of memory"
10941                                      " missing on its primary node" % miss_mem,
10942                                      errors.ECODE_NORES)
10943
10944       if be_new[constants.BE_AUTO_BALANCE]:
10945         for node, nres in nodeinfo.items():
10946           if node not in instance.secondary_nodes:
10947             continue
10948           nres.Raise("Can't get info from secondary node %s" % node,
10949                      prereq=True, ecode=errors.ECODE_STATE)
10950           if not isinstance(nres.payload.get("memory_free", None), int):
10951             raise errors.OpPrereqError("Secondary node %s didn't return free"
10952                                        " memory information" % node,
10953                                        errors.ECODE_STATE)
10954           elif be_new[constants.BE_MEMORY] > nres.payload["memory_free"]:
10955             raise errors.OpPrereqError("This change will prevent the instance"
10956                                        " from failover to its secondary node"
10957                                        " %s, due to not enough memory" % node,
10958                                        errors.ECODE_STATE)
10959
10960     # NIC processing
10961     self.nic_pnew = {}
10962     self.nic_pinst = {}
10963     for nic_op, nic_dict in self.op.nics:
10964       if nic_op == constants.DDM_REMOVE:
10965         if not instance.nics:
10966           raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10967                                      errors.ECODE_INVAL)
10968         continue
10969       if nic_op != constants.DDM_ADD:
10970         # an existing nic
10971         if not instance.nics:
10972           raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10973                                      " no NICs" % nic_op,
10974                                      errors.ECODE_INVAL)
10975         if nic_op < 0 or nic_op >= len(instance.nics):
10976           raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10977                                      " are 0 to %d" %
10978                                      (nic_op, len(instance.nics) - 1),
10979                                      errors.ECODE_INVAL)
10980         old_nic_params = instance.nics[nic_op].nicparams
10981         old_nic_ip = instance.nics[nic_op].ip
10982       else:
10983         old_nic_params = {}
10984         old_nic_ip = None
10985
10986       update_params_dict = dict([(key, nic_dict[key])
10987                                  for key in constants.NICS_PARAMETERS
10988                                  if key in nic_dict])
10989
10990       if "bridge" in nic_dict:
10991         update_params_dict[constants.NIC_LINK] = nic_dict["bridge"]
10992
10993       new_nic_params = _GetUpdatedParams(old_nic_params,
10994                                          update_params_dict)
10995       utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10996       new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10997       objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10998       self.nic_pinst[nic_op] = new_nic_params
10999       self.nic_pnew[nic_op] = new_filled_nic_params
11000       new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
11001
11002       if new_nic_mode == constants.NIC_MODE_BRIDGED:
11003         nic_bridge = new_filled_nic_params[constants.NIC_LINK]
11004         msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
11005         if msg:
11006           msg = "Error checking bridges on node %s: %s" % (pnode, msg)
11007           if self.op.force:
11008             self.warn.append(msg)
11009           else:
11010             raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
11011       if new_nic_mode == constants.NIC_MODE_ROUTED:
11012         if constants.INIC_IP in nic_dict:
11013           nic_ip = nic_dict[constants.INIC_IP]
11014         else:
11015           nic_ip = old_nic_ip
11016         if nic_ip is None:
11017           raise errors.OpPrereqError("Cannot set the nic ip to None"
11018                                      " on a routed nic", errors.ECODE_INVAL)
11019       if constants.INIC_MAC in nic_dict:
11020         nic_mac = nic_dict[constants.INIC_MAC]
11021         if nic_mac is None:
11022           raise errors.OpPrereqError("Cannot set the nic mac to None",
11023                                      errors.ECODE_INVAL)
11024         elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
11025           # otherwise generate the mac
11026           nic_dict[constants.INIC_MAC] = \
11027             self.cfg.GenerateMAC(self.proc.GetECId())
11028         else:
11029           # or validate/reserve the current one
11030           try:
11031             self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
11032           except errors.ReservationError:
11033             raise errors.OpPrereqError("MAC address %s already in use"
11034                                        " in cluster" % nic_mac,
11035                                        errors.ECODE_NOTUNIQUE)
11036
11037     # DISK processing
11038     if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
11039       raise errors.OpPrereqError("Disk operations not supported for"
11040                                  " diskless instances",
11041                                  errors.ECODE_INVAL)
11042     for disk_op, _ in self.op.disks:
11043       if disk_op == constants.DDM_REMOVE:
11044         if len(instance.disks) == 1:
11045           raise errors.OpPrereqError("Cannot remove the last disk of"
11046                                      " an instance", errors.ECODE_INVAL)
11047         _CheckInstanceDown(self, instance, "cannot remove disks")
11048
11049       if (disk_op == constants.DDM_ADD and
11050           len(instance.disks) >= constants.MAX_DISKS):
11051         raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
11052                                    " add more" % constants.MAX_DISKS,
11053                                    errors.ECODE_STATE)
11054       if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
11055         # an existing disk
11056         if disk_op < 0 or disk_op >= len(instance.disks):
11057           raise errors.OpPrereqError("Invalid disk index %s, valid values"
11058                                      " are 0 to %d" %
11059                                      (disk_op, len(instance.disks)),
11060                                      errors.ECODE_INVAL)
11061
11062     return
11063
11064   def _ConvertPlainToDrbd(self, feedback_fn):
11065     """Converts an instance from plain to drbd.
11066
11067     """
11068     feedback_fn("Converting template to drbd")
11069     instance = self.instance
11070     pnode = instance.primary_node
11071     snode = self.op.remote_node
11072
11073     # create a fake disk info for _GenerateDiskTemplate
11074     disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
11075                   constants.IDISK_VG: d.logical_id[0]}
11076                  for d in instance.disks]
11077     new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
11078                                       instance.name, pnode, [snode],
11079                                       disk_info, None, None, 0, feedback_fn)
11080     info = _GetInstanceInfoText(instance)
11081     feedback_fn("Creating aditional volumes...")
11082     # first, create the missing data and meta devices
11083     for disk in new_disks:
11084       # unfortunately this is... not too nice
11085       _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
11086                             info, True)
11087       for child in disk.children:
11088         _CreateSingleBlockDev(self, snode, instance, child, info, True)
11089     # at this stage, all new LVs have been created, we can rename the
11090     # old ones
11091     feedback_fn("Renaming original volumes...")
11092     rename_list = [(o, n.children[0].logical_id)
11093                    for (o, n) in zip(instance.disks, new_disks)]
11094     result = self.rpc.call_blockdev_rename(pnode, rename_list)
11095     result.Raise("Failed to rename original LVs")
11096
11097     feedback_fn("Initializing DRBD devices...")
11098     # all child devices are in place, we can now create the DRBD devices
11099     for disk in new_disks:
11100       for node in [pnode, snode]:
11101         f_create = node == pnode
11102         _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
11103
11104     # at this point, the instance has been modified
11105     instance.disk_template = constants.DT_DRBD8
11106     instance.disks = new_disks
11107     self.cfg.Update(instance, feedback_fn)
11108
11109     # disks are created, waiting for sync
11110     disk_abort = not _WaitForSync(self, instance,
11111                                   oneshot=not self.op.wait_for_sync)
11112     if disk_abort:
11113       raise errors.OpExecError("There are some degraded disks for"
11114                                " this instance, please cleanup manually")
11115
11116   def _ConvertDrbdToPlain(self, feedback_fn):
11117     """Converts an instance from drbd to plain.
11118
11119     """
11120     instance = self.instance
11121     assert len(instance.secondary_nodes) == 1
11122     pnode = instance.primary_node
11123     snode = instance.secondary_nodes[0]
11124     feedback_fn("Converting template to plain")
11125
11126     old_disks = instance.disks
11127     new_disks = [d.children[0] for d in old_disks]
11128
11129     # copy over size and mode
11130     for parent, child in zip(old_disks, new_disks):
11131       child.size = parent.size
11132       child.mode = parent.mode
11133
11134     # update instance structure
11135     instance.disks = new_disks
11136     instance.disk_template = constants.DT_PLAIN
11137     self.cfg.Update(instance, feedback_fn)
11138
11139     feedback_fn("Removing volumes on the secondary node...")
11140     for disk in old_disks:
11141       self.cfg.SetDiskID(disk, snode)
11142       msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
11143       if msg:
11144         self.LogWarning("Could not remove block device %s on node %s,"
11145                         " continuing anyway: %s", disk.iv_name, snode, msg)
11146
11147     feedback_fn("Removing unneeded volumes on the primary node...")
11148     for idx, disk in enumerate(old_disks):
11149       meta = disk.children[1]
11150       self.cfg.SetDiskID(meta, pnode)
11151       msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
11152       if msg:
11153         self.LogWarning("Could not remove metadata for disk %d on node %s,"
11154                         " continuing anyway: %s", idx, pnode, msg)
11155
11156     # this is a DRBD disk, return its port to the pool
11157     for disk in old_disks:
11158       tcp_port = disk.logical_id[2]
11159       self.cfg.AddTcpUdpPort(tcp_port)
11160
11161   def Exec(self, feedback_fn):
11162     """Modifies an instance.
11163
11164     All parameters take effect only at the next restart of the instance.
11165
11166     """
11167     # Process here the warnings from CheckPrereq, as we don't have a
11168     # feedback_fn there.
11169     for warn in self.warn:
11170       feedback_fn("WARNING: %s" % warn)
11171
11172     result = []
11173     instance = self.instance
11174     # disk changes
11175     for disk_op, disk_dict in self.op.disks:
11176       if disk_op == constants.DDM_REMOVE:
11177         # remove the last disk
11178         device = instance.disks.pop()
11179         device_idx = len(instance.disks)
11180         for node, disk in device.ComputeNodeTree(instance.primary_node):
11181           self.cfg.SetDiskID(disk, node)
11182           msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
11183           if msg:
11184             self.LogWarning("Could not remove disk/%d on node %s: %s,"
11185                             " continuing anyway", device_idx, node, msg)
11186         result.append(("disk/%d" % device_idx, "remove"))
11187
11188         # if this is a DRBD disk, return its port to the pool
11189         if device.dev_type in constants.LDS_DRBD:
11190           tcp_port = device.logical_id[2]
11191           self.cfg.AddTcpUdpPort(tcp_port)
11192       elif disk_op == constants.DDM_ADD:
11193         # add a new disk
11194         if instance.disk_template in (constants.DT_FILE,
11195                                         constants.DT_SHARED_FILE):
11196           file_driver, file_path = instance.disks[0].logical_id
11197           file_path = os.path.dirname(file_path)
11198         else:
11199           file_driver = file_path = None
11200         disk_idx_base = len(instance.disks)
11201         new_disk = _GenerateDiskTemplate(self,
11202                                          instance.disk_template,
11203                                          instance.name, instance.primary_node,
11204                                          instance.secondary_nodes,
11205                                          [disk_dict],
11206                                          file_path,
11207                                          file_driver,
11208                                          disk_idx_base, feedback_fn)[0]
11209         instance.disks.append(new_disk)
11210         info = _GetInstanceInfoText(instance)
11211
11212         logging.info("Creating volume %s for instance %s",
11213                      new_disk.iv_name, instance.name)
11214         # Note: this needs to be kept in sync with _CreateDisks
11215         #HARDCODE
11216         for node in instance.all_nodes:
11217           f_create = node == instance.primary_node
11218           try:
11219             _CreateBlockDev(self, node, instance, new_disk,
11220                             f_create, info, f_create)
11221           except errors.OpExecError, err:
11222             self.LogWarning("Failed to create volume %s (%s) on"
11223                             " node %s: %s",
11224                             new_disk.iv_name, new_disk, node, err)
11225         result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
11226                        (new_disk.size, new_disk.mode)))
11227       else:
11228         # change a given disk
11229         instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
11230         result.append(("disk.mode/%d" % disk_op,
11231                        disk_dict[constants.IDISK_MODE]))
11232
11233     if self.op.disk_template:
11234       r_shut = _ShutdownInstanceDisks(self, instance)
11235       if not r_shut:
11236         raise errors.OpExecError("Cannot shutdown instance disks, unable to"
11237                                  " proceed with disk template conversion")
11238       mode = (instance.disk_template, self.op.disk_template)
11239       try:
11240         self._DISK_CONVERSIONS[mode](self, feedback_fn)
11241       except:
11242         self.cfg.ReleaseDRBDMinors(instance.name)
11243         raise
11244       result.append(("disk_template", self.op.disk_template))
11245
11246     # NIC changes
11247     for nic_op, nic_dict in self.op.nics:
11248       if nic_op == constants.DDM_REMOVE:
11249         # remove the last nic
11250         del instance.nics[-1]
11251         result.append(("nic.%d" % len(instance.nics), "remove"))
11252       elif nic_op == constants.DDM_ADD:
11253         # mac and bridge should be set, by now
11254         mac = nic_dict[constants.INIC_MAC]
11255         ip = nic_dict.get(constants.INIC_IP, None)
11256         nicparams = self.nic_pinst[constants.DDM_ADD]
11257         new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
11258         instance.nics.append(new_nic)
11259         result.append(("nic.%d" % (len(instance.nics) - 1),
11260                        "add:mac=%s,ip=%s,mode=%s,link=%s" %
11261                        (new_nic.mac, new_nic.ip,
11262                         self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
11263                         self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
11264                        )))
11265       else:
11266         for key in (constants.INIC_MAC, constants.INIC_IP):
11267           if key in nic_dict:
11268             setattr(instance.nics[nic_op], key, nic_dict[key])
11269         if nic_op in self.nic_pinst:
11270           instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
11271         for key, val in nic_dict.iteritems():
11272           result.append(("nic.%s/%d" % (key, nic_op), val))
11273
11274     # hvparams changes
11275     if self.op.hvparams:
11276       instance.hvparams = self.hv_inst
11277       for key, val in self.op.hvparams.iteritems():
11278         result.append(("hv/%s" % key, val))
11279
11280     # beparams changes
11281     if self.op.beparams:
11282       instance.beparams = self.be_inst
11283       for key, val in self.op.beparams.iteritems():
11284         result.append(("be/%s" % key, val))
11285
11286     # OS change
11287     if self.op.os_name:
11288       instance.os = self.op.os_name
11289
11290     # osparams changes
11291     if self.op.osparams:
11292       instance.osparams = self.os_inst
11293       for key, val in self.op.osparams.iteritems():
11294         result.append(("os/%s" % key, val))
11295
11296     self.cfg.Update(instance, feedback_fn)
11297
11298     return result
11299
11300   _DISK_CONVERSIONS = {
11301     (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
11302     (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
11303     }
11304
11305
11306 class LUInstanceChangeGroup(LogicalUnit):
11307   HPATH = "instance-change-group"
11308   HTYPE = constants.HTYPE_INSTANCE
11309   REQ_BGL = False
11310
11311   def ExpandNames(self):
11312     self.share_locks = _ShareAll()
11313     self.needed_locks = {
11314       locking.LEVEL_NODEGROUP: [],
11315       locking.LEVEL_NODE: [],
11316       }
11317
11318     self._ExpandAndLockInstance()
11319
11320     if self.op.target_groups:
11321       self.req_target_uuids = map(self.cfg.LookupNodeGroup,
11322                                   self.op.target_groups)
11323     else:
11324       self.req_target_uuids = None
11325
11326     self.op.iallocator = _GetDefaultIAllocator(self.cfg, self.op.iallocator)
11327
11328   def DeclareLocks(self, level):
11329     if level == locking.LEVEL_NODEGROUP:
11330       assert not self.needed_locks[locking.LEVEL_NODEGROUP]
11331
11332       if self.req_target_uuids:
11333         lock_groups = set(self.req_target_uuids)
11334
11335         # Lock all groups used by instance optimistically; this requires going
11336         # via the node before it's locked, requiring verification later on
11337         instance_groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
11338         lock_groups.update(instance_groups)
11339       else:
11340         # No target groups, need to lock all of them
11341         lock_groups = locking.ALL_SET
11342
11343       self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
11344
11345     elif level == locking.LEVEL_NODE:
11346       if self.req_target_uuids:
11347         # Lock all nodes used by instances
11348         self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
11349         self._LockInstancesNodes()
11350
11351         # Lock all nodes in all potential target groups
11352         lock_groups = (frozenset(self.owned_locks(locking.LEVEL_NODEGROUP)) -
11353                        self.cfg.GetInstanceNodeGroups(self.op.instance_name))
11354         member_nodes = [node_name
11355                         for group in lock_groups
11356                         for node_name in self.cfg.GetNodeGroup(group).members]
11357         self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
11358       else:
11359         # Lock all nodes as all groups are potential targets
11360         self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11361
11362   def CheckPrereq(self):
11363     owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
11364     owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
11365     owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
11366
11367     assert (self.req_target_uuids is None or
11368             owned_groups.issuperset(self.req_target_uuids))
11369     assert owned_instances == set([self.op.instance_name])
11370
11371     # Get instance information
11372     self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
11373
11374     # Check if node groups for locked instance are still correct
11375     assert owned_nodes.issuperset(self.instance.all_nodes), \
11376       ("Instance %s's nodes changed while we kept the lock" %
11377        self.op.instance_name)
11378
11379     inst_groups = _CheckInstanceNodeGroups(self.cfg, self.op.instance_name,
11380                                            owned_groups)
11381
11382     if self.req_target_uuids:
11383       # User requested specific target groups
11384       self.target_uuids = frozenset(self.req_target_uuids)
11385     else:
11386       # All groups except those used by the instance are potential targets
11387       self.target_uuids = owned_groups - inst_groups
11388
11389     conflicting_groups = self.target_uuids & inst_groups
11390     if conflicting_groups:
11391       raise errors.OpPrereqError("Can't use group(s) '%s' as targets, they are"
11392                                  " used by the instance '%s'" %
11393                                  (utils.CommaJoin(conflicting_groups),
11394                                   self.op.instance_name),
11395                                  errors.ECODE_INVAL)
11396
11397     if not self.target_uuids:
11398       raise errors.OpPrereqError("There are no possible target groups",
11399                                  errors.ECODE_INVAL)
11400
11401   def BuildHooksEnv(self):
11402     """Build hooks env.
11403
11404     """
11405     assert self.target_uuids
11406
11407     env = {
11408       "TARGET_GROUPS": " ".join(self.target_uuids),
11409       }
11410
11411     env.update(_BuildInstanceHookEnvByObject(self, self.instance))
11412
11413     return env
11414
11415   def BuildHooksNodes(self):
11416     """Build hooks nodes.
11417
11418     """
11419     mn = self.cfg.GetMasterNode()
11420     return ([mn], [mn])
11421
11422   def Exec(self, feedback_fn):
11423     instances = list(self.owned_locks(locking.LEVEL_INSTANCE))
11424
11425     assert instances == [self.op.instance_name], "Instance not locked"
11426
11427     ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
11428                      instances=instances, target_groups=list(self.target_uuids))
11429
11430     ial.Run(self.op.iallocator)
11431
11432     if not ial.success:
11433       raise errors.OpPrereqError("Can't compute solution for changing group of"
11434                                  " instance '%s' using iallocator '%s': %s" %
11435                                  (self.op.instance_name, self.op.iallocator,
11436                                   ial.info),
11437                                  errors.ECODE_NORES)
11438
11439     jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
11440
11441     self.LogInfo("Iallocator returned %s job(s) for changing group of"
11442                  " instance '%s'", len(jobs), self.op.instance_name)
11443
11444     return ResultWithJobs(jobs)
11445
11446
11447 class LUBackupQuery(NoHooksLU):
11448   """Query the exports list
11449
11450   """
11451   REQ_BGL = False
11452
11453   def ExpandNames(self):
11454     self.needed_locks = {}
11455     self.share_locks[locking.LEVEL_NODE] = 1
11456     if not self.op.nodes:
11457       self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11458     else:
11459       self.needed_locks[locking.LEVEL_NODE] = \
11460         _GetWantedNodes(self, self.op.nodes)
11461
11462   def Exec(self, feedback_fn):
11463     """Compute the list of all the exported system images.
11464
11465     @rtype: dict
11466     @return: a dictionary with the structure node->(export-list)
11467         where export-list is a list of the instances exported on
11468         that node.
11469
11470     """
11471     self.nodes = self.owned_locks(locking.LEVEL_NODE)
11472     rpcresult = self.rpc.call_export_list(self.nodes)
11473     result = {}
11474     for node in rpcresult:
11475       if rpcresult[node].fail_msg:
11476         result[node] = False
11477       else:
11478         result[node] = rpcresult[node].payload
11479
11480     return result
11481
11482
11483 class LUBackupPrepare(NoHooksLU):
11484   """Prepares an instance for an export and returns useful information.
11485
11486   """
11487   REQ_BGL = False
11488
11489   def ExpandNames(self):
11490     self._ExpandAndLockInstance()
11491
11492   def CheckPrereq(self):
11493     """Check prerequisites.
11494
11495     """
11496     instance_name = self.op.instance_name
11497
11498     self.instance = self.cfg.GetInstanceInfo(instance_name)
11499     assert self.instance is not None, \
11500           "Cannot retrieve locked instance %s" % self.op.instance_name
11501     _CheckNodeOnline(self, self.instance.primary_node)
11502
11503     self._cds = _GetClusterDomainSecret()
11504
11505   def Exec(self, feedback_fn):
11506     """Prepares an instance for an export.
11507
11508     """
11509     instance = self.instance
11510
11511     if self.op.mode == constants.EXPORT_MODE_REMOTE:
11512       salt = utils.GenerateSecret(8)
11513
11514       feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
11515       result = self.rpc.call_x509_cert_create(instance.primary_node,
11516                                               constants.RIE_CERT_VALIDITY)
11517       result.Raise("Can't create X509 key and certificate on %s" % result.node)
11518
11519       (name, cert_pem) = result.payload
11520
11521       cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
11522                                              cert_pem)
11523
11524       return {
11525         "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
11526         "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
11527                           salt),
11528         "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
11529         }
11530
11531     return None
11532
11533
11534 class LUBackupExport(LogicalUnit):
11535   """Export an instance to an image in the cluster.
11536
11537   """
11538   HPATH = "instance-export"
11539   HTYPE = constants.HTYPE_INSTANCE
11540   REQ_BGL = False
11541
11542   def CheckArguments(self):
11543     """Check the arguments.
11544
11545     """
11546     self.x509_key_name = self.op.x509_key_name
11547     self.dest_x509_ca_pem = self.op.destination_x509_ca
11548
11549     if self.op.mode == constants.EXPORT_MODE_REMOTE:
11550       if not self.x509_key_name:
11551         raise errors.OpPrereqError("Missing X509 key name for encryption",
11552                                    errors.ECODE_INVAL)
11553
11554       if not self.dest_x509_ca_pem:
11555         raise errors.OpPrereqError("Missing destination X509 CA",
11556                                    errors.ECODE_INVAL)
11557
11558   def ExpandNames(self):
11559     self._ExpandAndLockInstance()
11560
11561     # Lock all nodes for local exports
11562     if self.op.mode == constants.EXPORT_MODE_LOCAL:
11563       # FIXME: lock only instance primary and destination node
11564       #
11565       # Sad but true, for now we have do lock all nodes, as we don't know where
11566       # the previous export might be, and in this LU we search for it and
11567       # remove it from its current node. In the future we could fix this by:
11568       #  - making a tasklet to search (share-lock all), then create the
11569       #    new one, then one to remove, after
11570       #  - removing the removal operation altogether
11571       self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11572
11573   def DeclareLocks(self, level):
11574     """Last minute lock declaration."""
11575     # All nodes are locked anyway, so nothing to do here.
11576
11577   def BuildHooksEnv(self):
11578     """Build hooks env.
11579
11580     This will run on the master, primary node and target node.
11581
11582     """
11583     env = {
11584       "EXPORT_MODE": self.op.mode,
11585       "EXPORT_NODE": self.op.target_node,
11586       "EXPORT_DO_SHUTDOWN": self.op.shutdown,
11587       "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
11588       # TODO: Generic function for boolean env variables
11589       "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
11590       }
11591
11592     env.update(_BuildInstanceHookEnvByObject(self, self.instance))
11593
11594     return env
11595
11596   def BuildHooksNodes(self):
11597     """Build hooks nodes.
11598
11599     """
11600     nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
11601
11602     if self.op.mode == constants.EXPORT_MODE_LOCAL:
11603       nl.append(self.op.target_node)
11604
11605     return (nl, nl)
11606
11607   def CheckPrereq(self):
11608     """Check prerequisites.
11609
11610     This checks that the instance and node names are valid.
11611
11612     """
11613     instance_name = self.op.instance_name
11614
11615     self.instance = self.cfg.GetInstanceInfo(instance_name)
11616     assert self.instance is not None, \
11617           "Cannot retrieve locked instance %s" % self.op.instance_name
11618     _CheckNodeOnline(self, self.instance.primary_node)
11619
11620     if (self.op.remove_instance and self.instance.admin_up and
11621         not self.op.shutdown):
11622       raise errors.OpPrereqError("Can not remove instance without shutting it"
11623                                  " down before")
11624
11625     if self.op.mode == constants.EXPORT_MODE_LOCAL:
11626       self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
11627       self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
11628       assert self.dst_node is not None
11629
11630       _CheckNodeOnline(self, self.dst_node.name)
11631       _CheckNodeNotDrained(self, self.dst_node.name)
11632
11633       self._cds = None
11634       self.dest_disk_info = None
11635       self.dest_x509_ca = None
11636
11637     elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11638       self.dst_node = None
11639
11640       if len(self.op.target_node) != len(self.instance.disks):
11641         raise errors.OpPrereqError(("Received destination information for %s"
11642                                     " disks, but instance %s has %s disks") %
11643                                    (len(self.op.target_node), instance_name,
11644                                     len(self.instance.disks)),
11645                                    errors.ECODE_INVAL)
11646
11647       cds = _GetClusterDomainSecret()
11648
11649       # Check X509 key name
11650       try:
11651         (key_name, hmac_digest, hmac_salt) = self.x509_key_name
11652       except (TypeError, ValueError), err:
11653         raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
11654
11655       if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
11656         raise errors.OpPrereqError("HMAC for X509 key name is wrong",
11657                                    errors.ECODE_INVAL)
11658
11659       # Load and verify CA
11660       try:
11661         (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
11662       except OpenSSL.crypto.Error, err:
11663         raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
11664                                    (err, ), errors.ECODE_INVAL)
11665
11666       (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
11667       if errcode is not None:
11668         raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
11669                                    (msg, ), errors.ECODE_INVAL)
11670
11671       self.dest_x509_ca = cert
11672
11673       # Verify target information
11674       disk_info = []
11675       for idx, disk_data in enumerate(self.op.target_node):
11676         try:
11677           (host, port, magic) = \
11678             masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
11679         except errors.GenericError, err:
11680           raise errors.OpPrereqError("Target info for disk %s: %s" %
11681                                      (idx, err), errors.ECODE_INVAL)
11682
11683         disk_info.append((host, port, magic))
11684
11685       assert len(disk_info) == len(self.op.target_node)
11686       self.dest_disk_info = disk_info
11687
11688     else:
11689       raise errors.ProgrammerError("Unhandled export mode %r" %
11690                                    self.op.mode)
11691
11692     # instance disk type verification
11693     # TODO: Implement export support for file-based disks
11694     for disk in self.instance.disks:
11695       if disk.dev_type == constants.LD_FILE:
11696         raise errors.OpPrereqError("Export not supported for instances with"
11697                                    " file-based disks", errors.ECODE_INVAL)
11698
11699   def _CleanupExports(self, feedback_fn):
11700     """Removes exports of current instance from all other nodes.
11701
11702     If an instance in a cluster with nodes A..D was exported to node C, its
11703     exports will be removed from the nodes A, B and D.
11704
11705     """
11706     assert self.op.mode != constants.EXPORT_MODE_REMOTE
11707
11708     nodelist = self.cfg.GetNodeList()
11709     nodelist.remove(self.dst_node.name)
11710
11711     # on one-node clusters nodelist will be empty after the removal
11712     # if we proceed the backup would be removed because OpBackupQuery
11713     # substitutes an empty list with the full cluster node list.
11714     iname = self.instance.name
11715     if nodelist:
11716       feedback_fn("Removing old exports for instance %s" % iname)
11717       exportlist = self.rpc.call_export_list(nodelist)
11718       for node in exportlist:
11719         if exportlist[node].fail_msg:
11720           continue
11721         if iname in exportlist[node].payload:
11722           msg = self.rpc.call_export_remove(node, iname).fail_msg
11723           if msg:
11724             self.LogWarning("Could not remove older export for instance %s"
11725                             " on node %s: %s", iname, node, msg)
11726
11727   def Exec(self, feedback_fn):
11728     """Export an instance to an image in the cluster.
11729
11730     """
11731     assert self.op.mode in constants.EXPORT_MODES
11732
11733     instance = self.instance
11734     src_node = instance.primary_node
11735
11736     if self.op.shutdown:
11737       # shutdown the instance, but not the disks
11738       feedback_fn("Shutting down instance %s" % instance.name)
11739       result = self.rpc.call_instance_shutdown(src_node, instance,
11740                                                self.op.shutdown_timeout)
11741       # TODO: Maybe ignore failures if ignore_remove_failures is set
11742       result.Raise("Could not shutdown instance %s on"
11743                    " node %s" % (instance.name, src_node))
11744
11745     # set the disks ID correctly since call_instance_start needs the
11746     # correct drbd minor to create the symlinks
11747     for disk in instance.disks:
11748       self.cfg.SetDiskID(disk, src_node)
11749
11750     activate_disks = (not instance.admin_up)
11751
11752     if activate_disks:
11753       # Activate the instance disks if we'exporting a stopped instance
11754       feedback_fn("Activating disks for %s" % instance.name)
11755       _StartInstanceDisks(self, instance, None)
11756
11757     try:
11758       helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
11759                                                      instance)
11760
11761       helper.CreateSnapshots()
11762       try:
11763         if (self.op.shutdown and instance.admin_up and
11764             not self.op.remove_instance):
11765           assert not activate_disks
11766           feedback_fn("Starting instance %s" % instance.name)
11767           result = self.rpc.call_instance_start(src_node, instance,
11768                                                 None, None, False)
11769           msg = result.fail_msg
11770           if msg:
11771             feedback_fn("Failed to start instance: %s" % msg)
11772             _ShutdownInstanceDisks(self, instance)
11773             raise errors.OpExecError("Could not start instance: %s" % msg)
11774
11775         if self.op.mode == constants.EXPORT_MODE_LOCAL:
11776           (fin_resu, dresults) = helper.LocalExport(self.dst_node)
11777         elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11778           connect_timeout = constants.RIE_CONNECT_TIMEOUT
11779           timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
11780
11781           (key_name, _, _) = self.x509_key_name
11782
11783           dest_ca_pem = \
11784             OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
11785                                             self.dest_x509_ca)
11786
11787           (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
11788                                                      key_name, dest_ca_pem,
11789                                                      timeouts)
11790       finally:
11791         helper.Cleanup()
11792
11793       # Check for backwards compatibility
11794       assert len(dresults) == len(instance.disks)
11795       assert compat.all(isinstance(i, bool) for i in dresults), \
11796              "Not all results are boolean: %r" % dresults
11797
11798     finally:
11799       if activate_disks:
11800         feedback_fn("Deactivating disks for %s" % instance.name)
11801         _ShutdownInstanceDisks(self, instance)
11802
11803     if not (compat.all(dresults) and fin_resu):
11804       failures = []
11805       if not fin_resu:
11806         failures.append("export finalization")
11807       if not compat.all(dresults):
11808         fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
11809                                if not dsk)
11810         failures.append("disk export: disk(s) %s" % fdsk)
11811
11812       raise errors.OpExecError("Export failed, errors in %s" %
11813                                utils.CommaJoin(failures))
11814
11815     # At this point, the export was successful, we can cleanup/finish
11816
11817     # Remove instance if requested
11818     if self.op.remove_instance:
11819       feedback_fn("Removing instance %s" % instance.name)
11820       _RemoveInstance(self, feedback_fn, instance,
11821                       self.op.ignore_remove_failures)
11822
11823     if self.op.mode == constants.EXPORT_MODE_LOCAL:
11824       self._CleanupExports(feedback_fn)
11825
11826     return fin_resu, dresults
11827
11828
11829 class LUBackupRemove(NoHooksLU):
11830   """Remove exports related to the named instance.
11831
11832   """
11833   REQ_BGL = False
11834
11835   def ExpandNames(self):
11836     self.needed_locks = {}
11837     # We need all nodes to be locked in order for RemoveExport to work, but we
11838     # don't need to lock the instance itself, as nothing will happen to it (and
11839     # we can remove exports also for a removed instance)
11840     self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11841
11842   def Exec(self, feedback_fn):
11843     """Remove any export.
11844
11845     """
11846     instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11847     # If the instance was not found we'll try with the name that was passed in.
11848     # This will only work if it was an FQDN, though.
11849     fqdn_warn = False
11850     if not instance_name:
11851       fqdn_warn = True
11852       instance_name = self.op.instance_name
11853
11854     locked_nodes = self.owned_locks(locking.LEVEL_NODE)
11855     exportlist = self.rpc.call_export_list(locked_nodes)
11856     found = False
11857     for node in exportlist:
11858       msg = exportlist[node].fail_msg
11859       if msg:
11860         self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11861         continue
11862       if instance_name in exportlist[node].payload:
11863         found = True
11864         result = self.rpc.call_export_remove(node, instance_name)
11865         msg = result.fail_msg
11866         if msg:
11867           logging.error("Could not remove export for instance %s"
11868                         " on node %s: %s", instance_name, node, msg)
11869
11870     if fqdn_warn and not found:
11871       feedback_fn("Export not found. If trying to remove an export belonging"
11872                   " to a deleted instance please use its Fully Qualified"
11873                   " Domain Name.")
11874
11875
11876 class LUGroupAdd(LogicalUnit):
11877   """Logical unit for creating node groups.
11878
11879   """
11880   HPATH = "group-add"
11881   HTYPE = constants.HTYPE_GROUP
11882   REQ_BGL = False
11883
11884   def ExpandNames(self):
11885     # We need the new group's UUID here so that we can create and acquire the
11886     # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11887     # that it should not check whether the UUID exists in the configuration.
11888     self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11889     self.needed_locks = {}
11890     self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11891
11892   def CheckPrereq(self):
11893     """Check prerequisites.
11894
11895     This checks that the given group name is not an existing node group
11896     already.
11897
11898     """
11899     try:
11900       existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11901     except errors.OpPrereqError:
11902       pass
11903     else:
11904       raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11905                                  " node group (UUID: %s)" %
11906                                  (self.op.group_name, existing_uuid),
11907                                  errors.ECODE_EXISTS)
11908
11909     if self.op.ndparams:
11910       utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11911
11912   def BuildHooksEnv(self):
11913     """Build hooks env.
11914
11915     """
11916     return {
11917       "GROUP_NAME": self.op.group_name,
11918       }
11919
11920   def BuildHooksNodes(self):
11921     """Build hooks nodes.
11922
11923     """
11924     mn = self.cfg.GetMasterNode()
11925     return ([mn], [mn])
11926
11927   def Exec(self, feedback_fn):
11928     """Add the node group to the cluster.
11929
11930     """
11931     group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11932                                   uuid=self.group_uuid,
11933                                   alloc_policy=self.op.alloc_policy,
11934                                   ndparams=self.op.ndparams)
11935
11936     self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11937     del self.remove_locks[locking.LEVEL_NODEGROUP]
11938
11939
11940 class LUGroupAssignNodes(NoHooksLU):
11941   """Logical unit for assigning nodes to groups.
11942
11943   """
11944   REQ_BGL = False
11945
11946   def ExpandNames(self):
11947     # These raise errors.OpPrereqError on their own:
11948     self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11949     self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11950
11951     # We want to lock all the affected nodes and groups. We have readily
11952     # available the list of nodes, and the *destination* group. To gather the
11953     # list of "source" groups, we need to fetch node information later on.
11954     self.needed_locks = {
11955       locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11956       locking.LEVEL_NODE: self.op.nodes,
11957       }
11958
11959   def DeclareLocks(self, level):
11960     if level == locking.LEVEL_NODEGROUP:
11961       assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11962
11963       # Try to get all affected nodes' groups without having the group or node
11964       # lock yet. Needs verification later in the code flow.
11965       groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11966
11967       self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11968
11969   def CheckPrereq(self):
11970     """Check prerequisites.
11971
11972     """
11973     assert self.needed_locks[locking.LEVEL_NODEGROUP]
11974     assert (frozenset(self.owned_locks(locking.LEVEL_NODE)) ==
11975             frozenset(self.op.nodes))
11976
11977     expected_locks = (set([self.group_uuid]) |
11978                       self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11979     actual_locks = self.owned_locks(locking.LEVEL_NODEGROUP)
11980     if actual_locks != expected_locks:
11981       raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11982                                " current groups are '%s', used to be '%s'" %
11983                                (utils.CommaJoin(expected_locks),
11984                                 utils.CommaJoin(actual_locks)))
11985
11986     self.node_data = self.cfg.GetAllNodesInfo()
11987     self.group = self.cfg.GetNodeGroup(self.group_uuid)
11988     instance_data = self.cfg.GetAllInstancesInfo()
11989
11990     if self.group is None:
11991       raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11992                                (self.op.group_name, self.group_uuid))
11993
11994     (new_splits, previous_splits) = \
11995       self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11996                                              for node in self.op.nodes],
11997                                             self.node_data, instance_data)
11998
11999     if new_splits:
12000       fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
12001
12002       if not self.op.force:
12003         raise errors.OpExecError("The following instances get split by this"
12004                                  " change and --force was not given: %s" %
12005                                  fmt_new_splits)
12006       else:
12007         self.LogWarning("This operation will split the following instances: %s",
12008                         fmt_new_splits)
12009
12010         if previous_splits:
12011           self.LogWarning("In addition, these already-split instances continue"
12012                           " to be split across groups: %s",
12013                           utils.CommaJoin(utils.NiceSort(previous_splits)))
12014
12015   def Exec(self, feedback_fn):
12016     """Assign nodes to a new group.
12017
12018     """
12019     mods = [(node_name, self.group_uuid) for node_name in self.op.nodes]
12020
12021     self.cfg.AssignGroupNodes(mods)
12022
12023   @staticmethod
12024   def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
12025     """Check for split instances after a node assignment.
12026
12027     This method considers a series of node assignments as an atomic operation,
12028     and returns information about split instances after applying the set of
12029     changes.
12030
12031     In particular, it returns information about newly split instances, and
12032     instances that were already split, and remain so after the change.
12033
12034     Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
12035     considered.
12036
12037     @type changes: list of (node_name, new_group_uuid) pairs.
12038     @param changes: list of node assignments to consider.
12039     @param node_data: a dict with data for all nodes
12040     @param instance_data: a dict with all instances to consider
12041     @rtype: a two-tuple
12042     @return: a list of instances that were previously okay and result split as a
12043       consequence of this change, and a list of instances that were previously
12044       split and this change does not fix.
12045
12046     """
12047     changed_nodes = dict((node, group) for node, group in changes
12048                          if node_data[node].group != group)
12049
12050     all_split_instances = set()
12051     previously_split_instances = set()
12052
12053     def InstanceNodes(instance):
12054       return [instance.primary_node] + list(instance.secondary_nodes)
12055
12056     for inst in instance_data.values():
12057       if inst.disk_template not in constants.DTS_INT_MIRROR:
12058         continue
12059
12060       instance_nodes = InstanceNodes(inst)
12061
12062       if len(set(node_data[node].group for node in instance_nodes)) > 1:
12063         previously_split_instances.add(inst.name)
12064
12065       if len(set(changed_nodes.get(node, node_data[node].group)
12066                  for node in instance_nodes)) > 1:
12067         all_split_instances.add(inst.name)
12068
12069     return (list(all_split_instances - previously_split_instances),
12070             list(previously_split_instances & all_split_instances))
12071
12072
12073 class _GroupQuery(_QueryBase):
12074   FIELDS = query.GROUP_FIELDS
12075
12076   def ExpandNames(self, lu):
12077     lu.needed_locks = {}
12078
12079     self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
12080     name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
12081
12082     if not self.names:
12083       self.wanted = [name_to_uuid[name]
12084                      for name in utils.NiceSort(name_to_uuid.keys())]
12085     else:
12086       # Accept names to be either names or UUIDs.
12087       missing = []
12088       self.wanted = []
12089       all_uuid = frozenset(self._all_groups.keys())
12090
12091       for name in self.names:
12092         if name in all_uuid:
12093           self.wanted.append(name)
12094         elif name in name_to_uuid:
12095           self.wanted.append(name_to_uuid[name])
12096         else:
12097           missing.append(name)
12098
12099       if missing:
12100         raise errors.OpPrereqError("Some groups do not exist: %s" %
12101                                    utils.CommaJoin(missing),
12102                                    errors.ECODE_NOENT)
12103
12104   def DeclareLocks(self, lu, level):
12105     pass
12106
12107   def _GetQueryData(self, lu):
12108     """Computes the list of node groups and their attributes.
12109
12110     """
12111     do_nodes = query.GQ_NODE in self.requested_data
12112     do_instances = query.GQ_INST in self.requested_data
12113
12114     group_to_nodes = None
12115     group_to_instances = None
12116
12117     # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
12118     # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
12119     # latter GetAllInstancesInfo() is not enough, for we have to go through
12120     # instance->node. Hence, we will need to process nodes even if we only need
12121     # instance information.
12122     if do_nodes or do_instances:
12123       all_nodes = lu.cfg.GetAllNodesInfo()
12124       group_to_nodes = dict((uuid, []) for uuid in self.wanted)
12125       node_to_group = {}
12126
12127       for node in all_nodes.values():
12128         if node.group in group_to_nodes:
12129           group_to_nodes[node.group].append(node.name)
12130           node_to_group[node.name] = node.group
12131
12132       if do_instances:
12133         all_instances = lu.cfg.GetAllInstancesInfo()
12134         group_to_instances = dict((uuid, []) for uuid in self.wanted)
12135
12136         for instance in all_instances.values():
12137           node = instance.primary_node
12138           if node in node_to_group:
12139             group_to_instances[node_to_group[node]].append(instance.name)
12140
12141         if not do_nodes:
12142           # Do not pass on node information if it was not requested.
12143           group_to_nodes = None
12144
12145     return query.GroupQueryData([self._all_groups[uuid]
12146                                  for uuid in self.wanted],
12147                                 group_to_nodes, group_to_instances)
12148
12149
12150 class LUGroupQuery(NoHooksLU):
12151   """Logical unit for querying node groups.
12152
12153   """
12154   REQ_BGL = False
12155
12156   def CheckArguments(self):
12157     self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
12158                           self.op.output_fields, False)
12159
12160   def ExpandNames(self):
12161     self.gq.ExpandNames(self)
12162
12163   def DeclareLocks(self, level):
12164     self.gq.DeclareLocks(self, level)
12165
12166   def Exec(self, feedback_fn):
12167     return self.gq.OldStyleQuery(self)
12168
12169
12170 class LUGroupSetParams(LogicalUnit):
12171   """Modifies the parameters of a node group.
12172
12173   """
12174   HPATH = "group-modify"
12175   HTYPE = constants.HTYPE_GROUP
12176   REQ_BGL = False
12177
12178   def CheckArguments(self):
12179     all_changes = [
12180       self.op.ndparams,
12181       self.op.alloc_policy,
12182       ]
12183
12184     if all_changes.count(None) == len(all_changes):
12185       raise errors.OpPrereqError("Please pass at least one modification",
12186                                  errors.ECODE_INVAL)
12187
12188   def ExpandNames(self):
12189     # This raises errors.OpPrereqError on its own:
12190     self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12191
12192     self.needed_locks = {
12193       locking.LEVEL_NODEGROUP: [self.group_uuid],
12194       }
12195
12196   def CheckPrereq(self):
12197     """Check prerequisites.
12198
12199     """
12200     self.group = self.cfg.GetNodeGroup(self.group_uuid)
12201
12202     if self.group is None:
12203       raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
12204                                (self.op.group_name, self.group_uuid))
12205
12206     if self.op.ndparams:
12207       new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
12208       utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
12209       self.new_ndparams = new_ndparams
12210
12211   def BuildHooksEnv(self):
12212     """Build hooks env.
12213
12214     """
12215     return {
12216       "GROUP_NAME": self.op.group_name,
12217       "NEW_ALLOC_POLICY": self.op.alloc_policy,
12218       }
12219
12220   def BuildHooksNodes(self):
12221     """Build hooks nodes.
12222
12223     """
12224     mn = self.cfg.GetMasterNode()
12225     return ([mn], [mn])
12226
12227   def Exec(self, feedback_fn):
12228     """Modifies the node group.
12229
12230     """
12231     result = []
12232
12233     if self.op.ndparams:
12234       self.group.ndparams = self.new_ndparams
12235       result.append(("ndparams", str(self.group.ndparams)))
12236
12237     if self.op.alloc_policy:
12238       self.group.alloc_policy = self.op.alloc_policy
12239
12240     self.cfg.Update(self.group, feedback_fn)
12241     return result
12242
12243
12244 class LUGroupRemove(LogicalUnit):
12245   HPATH = "group-remove"
12246   HTYPE = constants.HTYPE_GROUP
12247   REQ_BGL = False
12248
12249   def ExpandNames(self):
12250     # This will raises errors.OpPrereqError on its own:
12251     self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12252     self.needed_locks = {
12253       locking.LEVEL_NODEGROUP: [self.group_uuid],
12254       }
12255
12256   def CheckPrereq(self):
12257     """Check prerequisites.
12258
12259     This checks that the given group name exists as a node group, that is
12260     empty (i.e., contains no nodes), and that is not the last group of the
12261     cluster.
12262
12263     """
12264     # Verify that the group is empty.
12265     group_nodes = [node.name
12266                    for node in self.cfg.GetAllNodesInfo().values()
12267                    if node.group == self.group_uuid]
12268
12269     if group_nodes:
12270       raise errors.OpPrereqError("Group '%s' not empty, has the following"
12271                                  " nodes: %s" %
12272                                  (self.op.group_name,
12273                                   utils.CommaJoin(utils.NiceSort(group_nodes))),
12274                                  errors.ECODE_STATE)
12275
12276     # Verify the cluster would not be left group-less.
12277     if len(self.cfg.GetNodeGroupList()) == 1:
12278       raise errors.OpPrereqError("Group '%s' is the only group,"
12279                                  " cannot be removed" %
12280                                  self.op.group_name,
12281                                  errors.ECODE_STATE)
12282
12283   def BuildHooksEnv(self):
12284     """Build hooks env.
12285
12286     """
12287     return {
12288       "GROUP_NAME": self.op.group_name,
12289       }
12290
12291   def BuildHooksNodes(self):
12292     """Build hooks nodes.
12293
12294     """
12295     mn = self.cfg.GetMasterNode()
12296     return ([mn], [mn])
12297
12298   def Exec(self, feedback_fn):
12299     """Remove the node group.
12300
12301     """
12302     try:
12303       self.cfg.RemoveNodeGroup(self.group_uuid)
12304     except errors.ConfigurationError:
12305       raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
12306                                (self.op.group_name, self.group_uuid))
12307
12308     self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
12309
12310
12311 class LUGroupRename(LogicalUnit):
12312   HPATH = "group-rename"
12313   HTYPE = constants.HTYPE_GROUP
12314   REQ_BGL = False
12315
12316   def ExpandNames(self):
12317     # This raises errors.OpPrereqError on its own:
12318     self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12319
12320     self.needed_locks = {
12321       locking.LEVEL_NODEGROUP: [self.group_uuid],
12322       }
12323
12324   def CheckPrereq(self):
12325     """Check prerequisites.
12326
12327     Ensures requested new name is not yet used.
12328
12329     """
12330     try:
12331       new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
12332     except errors.OpPrereqError:
12333       pass
12334     else:
12335       raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
12336                                  " node group (UUID: %s)" %
12337                                  (self.op.new_name, new_name_uuid),
12338                                  errors.ECODE_EXISTS)
12339
12340   def BuildHooksEnv(self):
12341     """Build hooks env.
12342
12343     """
12344     return {
12345       "OLD_NAME": self.op.group_name,
12346       "NEW_NAME": self.op.new_name,
12347       }
12348
12349   def BuildHooksNodes(self):
12350     """Build hooks nodes.
12351
12352     """
12353     mn = self.cfg.GetMasterNode()
12354
12355     all_nodes = self.cfg.GetAllNodesInfo()
12356     all_nodes.pop(mn, None)
12357
12358     run_nodes = [mn]
12359     run_nodes.extend(node.name for node in all_nodes.values()
12360                      if node.group == self.group_uuid)
12361
12362     return (run_nodes, run_nodes)
12363
12364   def Exec(self, feedback_fn):
12365     """Rename the node group.
12366
12367     """
12368     group = self.cfg.GetNodeGroup(self.group_uuid)
12369
12370     if group is None:
12371       raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
12372                                (self.op.group_name, self.group_uuid))
12373
12374     group.name = self.op.new_name
12375     self.cfg.Update(group, feedback_fn)
12376
12377     return self.op.new_name
12378
12379
12380 class LUGroupEvacuate(LogicalUnit):
12381   HPATH = "group-evacuate"
12382   HTYPE = constants.HTYPE_GROUP
12383   REQ_BGL = False
12384
12385   def ExpandNames(self):
12386     # This raises errors.OpPrereqError on its own:
12387     self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12388
12389     if self.op.target_groups:
12390       self.req_target_uuids = map(self.cfg.LookupNodeGroup,
12391                                   self.op.target_groups)
12392     else:
12393       self.req_target_uuids = []
12394
12395     if self.group_uuid in self.req_target_uuids:
12396       raise errors.OpPrereqError("Group to be evacuated (%s) can not be used"
12397                                  " as a target group (targets are %s)" %
12398                                  (self.group_uuid,
12399                                   utils.CommaJoin(self.req_target_uuids)),
12400                                  errors.ECODE_INVAL)
12401
12402     self.op.iallocator = _GetDefaultIAllocator(self.cfg, self.op.iallocator)
12403
12404     self.share_locks = _ShareAll()
12405     self.needed_locks = {
12406       locking.LEVEL_INSTANCE: [],
12407       locking.LEVEL_NODEGROUP: [],
12408       locking.LEVEL_NODE: [],
12409       }
12410
12411   def DeclareLocks(self, level):
12412     if level == locking.LEVEL_INSTANCE:
12413       assert not self.needed_locks[locking.LEVEL_INSTANCE]
12414
12415       # Lock instances optimistically, needs verification once node and group
12416       # locks have been acquired
12417       self.needed_locks[locking.LEVEL_INSTANCE] = \
12418         self.cfg.GetNodeGroupInstances(self.group_uuid)
12419
12420     elif level == locking.LEVEL_NODEGROUP:
12421       assert not self.needed_locks[locking.LEVEL_NODEGROUP]
12422
12423       if self.req_target_uuids:
12424         lock_groups = set([self.group_uuid] + self.req_target_uuids)
12425
12426         # Lock all groups used by instances optimistically; this requires going
12427         # via the node before it's locked, requiring verification later on
12428         lock_groups.update(group_uuid
12429                            for instance_name in
12430                              self.owned_locks(locking.LEVEL_INSTANCE)
12431                            for group_uuid in
12432                              self.cfg.GetInstanceNodeGroups(instance_name))
12433       else:
12434         # No target groups, need to lock all of them
12435         lock_groups = locking.ALL_SET
12436
12437       self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
12438
12439     elif level == locking.LEVEL_NODE:
12440       # This will only lock the nodes in the group to be evacuated which
12441       # contain actual instances
12442       self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
12443       self._LockInstancesNodes()
12444
12445       # Lock all nodes in group to be evacuated and target groups
12446       owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
12447       assert self.group_uuid in owned_groups
12448       member_nodes = [node_name
12449                       for group in owned_groups
12450                       for node_name in self.cfg.GetNodeGroup(group).members]
12451       self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
12452
12453   def CheckPrereq(self):
12454     owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
12455     owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
12456     owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
12457
12458     assert owned_groups.issuperset(self.req_target_uuids)
12459     assert self.group_uuid in owned_groups
12460
12461     # Check if locked instances are still correct
12462     _CheckNodeGroupInstances(self.cfg, self.group_uuid, owned_instances)
12463
12464     # Get instance information
12465     self.instances = dict(self.cfg.GetMultiInstanceInfo(owned_instances))
12466
12467     # Check if node groups for locked instances are still correct
12468     for instance_name in owned_instances:
12469       inst = self.instances[instance_name]
12470       assert owned_nodes.issuperset(inst.all_nodes), \
12471         "Instance %s's nodes changed while we kept the lock" % instance_name
12472
12473       inst_groups = _CheckInstanceNodeGroups(self.cfg, instance_name,
12474                                              owned_groups)
12475
12476       assert self.group_uuid in inst_groups, \
12477         "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
12478
12479     if self.req_target_uuids:
12480       # User requested specific target groups
12481       self.target_uuids = self.req_target_uuids
12482     else:
12483       # All groups except the one to be evacuated are potential targets
12484       self.target_uuids = [group_uuid for group_uuid in owned_groups
12485                            if group_uuid != self.group_uuid]
12486
12487       if not self.target_uuids:
12488         raise errors.OpPrereqError("There are no possible target groups",
12489                                    errors.ECODE_INVAL)
12490
12491   def BuildHooksEnv(self):
12492     """Build hooks env.
12493
12494     """
12495     return {
12496       "GROUP_NAME": self.op.group_name,
12497       "TARGET_GROUPS": " ".join(self.target_uuids),
12498       }
12499
12500   def BuildHooksNodes(self):
12501     """Build hooks nodes.
12502
12503     """
12504     mn = self.cfg.GetMasterNode()
12505
12506     assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
12507
12508     run_nodes = [mn] + self.cfg.GetNodeGroup(self.group_uuid).members
12509
12510     return (run_nodes, run_nodes)
12511
12512   def Exec(self, feedback_fn):
12513     instances = list(self.owned_locks(locking.LEVEL_INSTANCE))
12514
12515     assert self.group_uuid not in self.target_uuids
12516
12517     ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
12518                      instances=instances, target_groups=self.target_uuids)
12519
12520     ial.Run(self.op.iallocator)
12521
12522     if not ial.success:
12523       raise errors.OpPrereqError("Can't compute group evacuation using"
12524                                  " iallocator '%s': %s" %
12525                                  (self.op.iallocator, ial.info),
12526                                  errors.ECODE_NORES)
12527
12528     jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
12529
12530     self.LogInfo("Iallocator returned %s job(s) for evacuating node group %s",
12531                  len(jobs), self.op.group_name)
12532
12533     return ResultWithJobs(jobs)
12534
12535
12536 class TagsLU(NoHooksLU): # pylint: disable=W0223
12537   """Generic tags LU.
12538
12539   This is an abstract class which is the parent of all the other tags LUs.
12540
12541   """
12542   def ExpandNames(self):
12543     self.group_uuid = None
12544     self.needed_locks = {}
12545     if self.op.kind == constants.TAG_NODE:
12546       self.op.name = _ExpandNodeName(self.cfg, self.op.name)
12547       self.needed_locks[locking.LEVEL_NODE] = self.op.name
12548     elif self.op.kind == constants.TAG_INSTANCE:
12549       self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
12550       self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
12551     elif self.op.kind == constants.TAG_NODEGROUP:
12552       self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
12553
12554     # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
12555     # not possible to acquire the BGL based on opcode parameters)
12556
12557   def CheckPrereq(self):
12558     """Check prerequisites.
12559
12560     """
12561     if self.op.kind == constants.TAG_CLUSTER:
12562       self.target = self.cfg.GetClusterInfo()
12563     elif self.op.kind == constants.TAG_NODE:
12564       self.target = self.cfg.GetNodeInfo(self.op.name)
12565     elif self.op.kind == constants.TAG_INSTANCE:
12566       self.target = self.cfg.GetInstanceInfo(self.op.name)
12567     elif self.op.kind == constants.TAG_NODEGROUP:
12568       self.target = self.cfg.GetNodeGroup(self.group_uuid)
12569     else:
12570       raise errors.OpPrereqError("Wrong tag type requested (%s)" %
12571                                  str(self.op.kind), errors.ECODE_INVAL)
12572
12573
12574 class LUTagsGet(TagsLU):
12575   """Returns the tags of a given object.
12576
12577   """
12578   REQ_BGL = False
12579
12580   def ExpandNames(self):
12581     TagsLU.ExpandNames(self)
12582
12583     # Share locks as this is only a read operation
12584     self.share_locks = _ShareAll()
12585
12586   def Exec(self, feedback_fn):
12587     """Returns the tag list.
12588
12589     """
12590     return list(self.target.GetTags())
12591
12592
12593 class LUTagsSearch(NoHooksLU):
12594   """Searches the tags for a given pattern.
12595
12596   """
12597   REQ_BGL = False
12598
12599   def ExpandNames(self):
12600     self.needed_locks = {}
12601
12602   def CheckPrereq(self):
12603     """Check prerequisites.
12604
12605     This checks the pattern passed for validity by compiling it.
12606
12607     """
12608     try:
12609       self.re = re.compile(self.op.pattern)
12610     except re.error, err:
12611       raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
12612                                  (self.op.pattern, err), errors.ECODE_INVAL)
12613
12614   def Exec(self, feedback_fn):
12615     """Returns the tag list.
12616
12617     """
12618     cfg = self.cfg
12619     tgts = [("/cluster", cfg.GetClusterInfo())]
12620     ilist = cfg.GetAllInstancesInfo().values()
12621     tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
12622     nlist = cfg.GetAllNodesInfo().values()
12623     tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
12624     tgts.extend(("/nodegroup/%s" % n.name, n)
12625                 for n in cfg.GetAllNodeGroupsInfo().values())
12626     results = []
12627     for path, target in tgts:
12628       for tag in target.GetTags():
12629         if self.re.search(tag):
12630           results.append((path, tag))
12631     return results
12632
12633
12634 class LUTagsSet(TagsLU):
12635   """Sets a tag on a given object.
12636
12637   """
12638   REQ_BGL = False
12639
12640   def CheckPrereq(self):
12641     """Check prerequisites.
12642
12643     This checks the type and length of the tag name and value.
12644
12645     """
12646     TagsLU.CheckPrereq(self)
12647     for tag in self.op.tags:
12648       objects.TaggableObject.ValidateTag(tag)
12649
12650   def Exec(self, feedback_fn):
12651     """Sets the tag.
12652
12653     """
12654     try:
12655       for tag in self.op.tags:
12656         self.target.AddTag(tag)
12657     except errors.TagError, err:
12658       raise errors.OpExecError("Error while setting tag: %s" % str(err))
12659     self.cfg.Update(self.target, feedback_fn)
12660
12661
12662 class LUTagsDel(TagsLU):
12663   """Delete a list of tags from a given object.
12664
12665   """
12666   REQ_BGL = False
12667
12668   def CheckPrereq(self):
12669     """Check prerequisites.
12670
12671     This checks that we have the given tag.
12672
12673     """
12674     TagsLU.CheckPrereq(self)
12675     for tag in self.op.tags:
12676       objects.TaggableObject.ValidateTag(tag)
12677     del_tags = frozenset(self.op.tags)
12678     cur_tags = self.target.GetTags()
12679
12680     diff_tags = del_tags - cur_tags
12681     if diff_tags:
12682       diff_names = ("'%s'" % i for i in sorted(diff_tags))
12683       raise errors.OpPrereqError("Tag(s) %s not found" %
12684                                  (utils.CommaJoin(diff_names), ),
12685                                  errors.ECODE_NOENT)
12686
12687   def Exec(self, feedback_fn):
12688     """Remove the tag from the object.
12689
12690     """
12691     for tag in self.op.tags:
12692       self.target.RemoveTag(tag)
12693     self.cfg.Update(self.target, feedback_fn)
12694
12695
12696 class LUTestDelay(NoHooksLU):
12697   """Sleep for a specified amount of time.
12698
12699   This LU sleeps on the master and/or nodes for a specified amount of
12700   time.
12701
12702   """
12703   REQ_BGL = False
12704
12705   def ExpandNames(self):
12706     """Expand names and set required locks.
12707
12708     This expands the node list, if any.
12709
12710     """
12711     self.needed_locks = {}
12712     if self.op.on_nodes:
12713       # _GetWantedNodes can be used here, but is not always appropriate to use
12714       # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
12715       # more information.
12716       self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
12717       self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
12718
12719   def _TestDelay(self):
12720     """Do the actual sleep.
12721
12722     """
12723     if self.op.on_master:
12724       if not utils.TestDelay(self.op.duration):
12725         raise errors.OpExecError("Error during master delay test")
12726     if self.op.on_nodes:
12727       result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
12728       for node, node_result in result.items():
12729         node_result.Raise("Failure during rpc call to node %s" % node)
12730
12731   def Exec(self, feedback_fn):
12732     """Execute the test delay opcode, with the wanted repetitions.
12733
12734     """
12735     if self.op.repeat == 0:
12736       self._TestDelay()
12737     else:
12738       top_value = self.op.repeat - 1
12739       for i in range(self.op.repeat):
12740         self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
12741         self._TestDelay()
12742
12743
12744 class LUTestJqueue(NoHooksLU):
12745   """Utility LU to test some aspects of the job queue.
12746
12747   """
12748   REQ_BGL = False
12749
12750   # Must be lower than default timeout for WaitForJobChange to see whether it
12751   # notices changed jobs
12752   _CLIENT_CONNECT_TIMEOUT = 20.0
12753   _CLIENT_CONFIRM_TIMEOUT = 60.0
12754
12755   @classmethod
12756   def _NotifyUsingSocket(cls, cb, errcls):
12757     """Opens a Unix socket and waits for another program to connect.
12758
12759     @type cb: callable
12760     @param cb: Callback to send socket name to client
12761     @type errcls: class
12762     @param errcls: Exception class to use for errors
12763
12764     """
12765     # Using a temporary directory as there's no easy way to create temporary
12766     # sockets without writing a custom loop around tempfile.mktemp and
12767     # socket.bind
12768     tmpdir = tempfile.mkdtemp()
12769     try:
12770       tmpsock = utils.PathJoin(tmpdir, "sock")
12771
12772       logging.debug("Creating temporary socket at %s", tmpsock)
12773       sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
12774       try:
12775         sock.bind(tmpsock)
12776         sock.listen(1)
12777
12778         # Send details to client
12779         cb(tmpsock)
12780
12781         # Wait for client to connect before continuing
12782         sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
12783         try:
12784           (conn, _) = sock.accept()
12785         except socket.error, err:
12786           raise errcls("Client didn't connect in time (%s)" % err)
12787       finally:
12788         sock.close()
12789     finally:
12790       # Remove as soon as client is connected
12791       shutil.rmtree(tmpdir)
12792
12793     # Wait for client to close
12794     try:
12795       try:
12796         # pylint: disable=E1101
12797         # Instance of '_socketobject' has no ... member
12798         conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
12799         conn.recv(1)
12800       except socket.error, err:
12801         raise errcls("Client failed to confirm notification (%s)" % err)
12802     finally:
12803       conn.close()
12804
12805   def _SendNotification(self, test, arg, sockname):
12806     """Sends a notification to the client.
12807
12808     @type test: string
12809     @param test: Test name
12810     @param arg: Test argument (depends on test)
12811     @type sockname: string
12812     @param sockname: Socket path
12813
12814     """
12815     self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
12816
12817   def _Notify(self, prereq, test, arg):
12818     """Notifies the client of a test.
12819
12820     @type prereq: bool
12821     @param prereq: Whether this is a prereq-phase test
12822     @type test: string
12823     @param test: Test name
12824     @param arg: Test argument (depends on test)
12825
12826     """
12827     if prereq:
12828       errcls = errors.OpPrereqError
12829     else:
12830       errcls = errors.OpExecError
12831
12832     return self._NotifyUsingSocket(compat.partial(self._SendNotification,
12833                                                   test, arg),
12834                                    errcls)
12835
12836   def CheckArguments(self):
12837     self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
12838     self.expandnames_calls = 0
12839
12840   def ExpandNames(self):
12841     checkargs_calls = getattr(self, "checkargs_calls", 0)
12842     if checkargs_calls < 1:
12843       raise errors.ProgrammerError("CheckArguments was not called")
12844
12845     self.expandnames_calls += 1
12846
12847     if self.op.notify_waitlock:
12848       self._Notify(True, constants.JQT_EXPANDNAMES, None)
12849
12850     self.LogInfo("Expanding names")
12851
12852     # Get lock on master node (just to get a lock, not for a particular reason)
12853     self.needed_locks = {
12854       locking.LEVEL_NODE: self.cfg.GetMasterNode(),
12855       }
12856
12857   def Exec(self, feedback_fn):
12858     if self.expandnames_calls < 1:
12859       raise errors.ProgrammerError("ExpandNames was not called")
12860
12861     if self.op.notify_exec:
12862       self._Notify(False, constants.JQT_EXEC, None)
12863
12864     self.LogInfo("Executing")
12865
12866     if self.op.log_messages:
12867       self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
12868       for idx, msg in enumerate(self.op.log_messages):
12869         self.LogInfo("Sending log message %s", idx + 1)
12870         feedback_fn(constants.JQT_MSGPREFIX + msg)
12871         # Report how many test messages have been sent
12872         self._Notify(False, constants.JQT_LOGMSG, idx + 1)
12873
12874     if self.op.fail:
12875       raise errors.OpExecError("Opcode failure was requested")
12876
12877     return True
12878
12879
12880 class IAllocator(object):
12881   """IAllocator framework.
12882
12883   An IAllocator instance has three sets of attributes:
12884     - cfg that is needed to query the cluster
12885     - input data (all members of the _KEYS class attribute are required)
12886     - four buffer attributes (in|out_data|text), that represent the
12887       input (to the external script) in text and data structure format,
12888       and the output from it, again in two formats
12889     - the result variables from the script (success, info, nodes) for
12890       easy usage
12891
12892   """
12893   # pylint: disable=R0902
12894   # lots of instance attributes
12895
12896   def __init__(self, cfg, rpc, mode, **kwargs):
12897     self.cfg = cfg
12898     self.rpc = rpc
12899     # init buffer variables
12900     self.in_text = self.out_text = self.in_data = self.out_data = None
12901     # init all input fields so that pylint is happy
12902     self.mode = mode
12903     self.memory = self.disks = self.disk_template = None
12904     self.os = self.tags = self.nics = self.vcpus = None
12905     self.hypervisor = None
12906     self.relocate_from = None
12907     self.name = None
12908     self.instances = None
12909     self.evac_mode = None
12910     self.target_groups = []
12911     # computed fields
12912     self.required_nodes = None
12913     # init result fields
12914     self.success = self.info = self.result = None
12915
12916     try:
12917       (fn, keydata, self._result_check) = self._MODE_DATA[self.mode]
12918     except KeyError:
12919       raise errors.ProgrammerError("Unknown mode '%s' passed to the"
12920                                    " IAllocator" % self.mode)
12921
12922     keyset = [n for (n, _) in keydata]
12923
12924     for key in kwargs:
12925       if key not in keyset:
12926         raise errors.ProgrammerError("Invalid input parameter '%s' to"
12927                                      " IAllocator" % key)
12928       setattr(self, key, kwargs[key])
12929
12930     for key in keyset:
12931       if key not in kwargs:
12932         raise errors.ProgrammerError("Missing input parameter '%s' to"
12933                                      " IAllocator" % key)
12934     self._BuildInputData(compat.partial(fn, self), keydata)
12935
12936   def _ComputeClusterData(self):
12937     """Compute the generic allocator input data.
12938
12939     This is the data that is independent of the actual operation.
12940
12941     """
12942     cfg = self.cfg
12943     cluster_info = cfg.GetClusterInfo()
12944     # cluster data
12945     data = {
12946       "version": constants.IALLOCATOR_VERSION,
12947       "cluster_name": cfg.GetClusterName(),
12948       "cluster_tags": list(cluster_info.GetTags()),
12949       "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
12950       # we don't have job IDs
12951       }
12952     ninfo = cfg.GetAllNodesInfo()
12953     iinfo = cfg.GetAllInstancesInfo().values()
12954     i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
12955
12956     # node data
12957     node_list = [n.name for n in ninfo.values() if n.vm_capable]
12958
12959     if self.mode == constants.IALLOCATOR_MODE_ALLOC:
12960       hypervisor_name = self.hypervisor
12961     elif self.mode == constants.IALLOCATOR_MODE_RELOC:
12962       hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
12963     else:
12964       hypervisor_name = cluster_info.enabled_hypervisors[0]
12965
12966     node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
12967                                         hypervisor_name)
12968     node_iinfo = \
12969       self.rpc.call_all_instances_info(node_list,
12970                                        cluster_info.enabled_hypervisors)
12971
12972     data["nodegroups"] = self._ComputeNodeGroupData(cfg)
12973
12974     config_ndata = self._ComputeBasicNodeData(ninfo)
12975     data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12976                                                  i_list, config_ndata)
12977     assert len(data["nodes"]) == len(ninfo), \
12978         "Incomplete node data computed"
12979
12980     data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12981
12982     self.in_data = data
12983
12984   @staticmethod
12985   def _ComputeNodeGroupData(cfg):
12986     """Compute node groups data.
12987
12988     """
12989     ng = dict((guuid, {
12990       "name": gdata.name,
12991       "alloc_policy": gdata.alloc_policy,
12992       })
12993       for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12994
12995     return ng
12996
12997   @staticmethod
12998   def _ComputeBasicNodeData(node_cfg):
12999     """Compute global node data.
13000
13001     @rtype: dict
13002     @returns: a dict of name: (node dict, node config)
13003
13004     """
13005     # fill in static (config-based) values
13006     node_results = dict((ninfo.name, {
13007       "tags": list(ninfo.GetTags()),
13008       "primary_ip": ninfo.primary_ip,
13009       "secondary_ip": ninfo.secondary_ip,
13010       "offline": ninfo.offline,
13011       "drained": ninfo.drained,
13012       "master_candidate": ninfo.master_candidate,
13013       "group": ninfo.group,
13014       "master_capable": ninfo.master_capable,
13015       "vm_capable": ninfo.vm_capable,
13016       })
13017       for ninfo in node_cfg.values())
13018
13019     return node_results
13020
13021   @staticmethod
13022   def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
13023                               node_results):
13024     """Compute global node data.
13025
13026     @param node_results: the basic node structures as filled from the config
13027
13028     """
13029     # make a copy of the current dict
13030     node_results = dict(node_results)
13031     for nname, nresult in node_data.items():
13032       assert nname in node_results, "Missing basic data for node %s" % nname
13033       ninfo = node_cfg[nname]
13034
13035       if not (ninfo.offline or ninfo.drained):
13036         nresult.Raise("Can't get data for node %s" % nname)
13037         node_iinfo[nname].Raise("Can't get node instance info from node %s" %
13038                                 nname)
13039         remote_info = nresult.payload
13040
13041         for attr in ["memory_total", "memory_free", "memory_dom0",
13042                      "vg_size", "vg_free", "cpu_total"]:
13043           if attr not in remote_info:
13044             raise errors.OpExecError("Node '%s' didn't return attribute"
13045                                      " '%s'" % (nname, attr))
13046           if not isinstance(remote_info[attr], int):
13047             raise errors.OpExecError("Node '%s' returned invalid value"
13048                                      " for '%s': %s" %
13049                                      (nname, attr, remote_info[attr]))
13050         # compute memory used by primary instances
13051         i_p_mem = i_p_up_mem = 0
13052         for iinfo, beinfo in i_list:
13053           if iinfo.primary_node == nname:
13054             i_p_mem += beinfo[constants.BE_MEMORY]
13055             if iinfo.name not in node_iinfo[nname].payload:
13056               i_used_mem = 0
13057             else:
13058               i_used_mem = int(node_iinfo[nname].payload[iinfo.name]["memory"])
13059             i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
13060             remote_info["memory_free"] -= max(0, i_mem_diff)
13061
13062             if iinfo.admin_up:
13063               i_p_up_mem += beinfo[constants.BE_MEMORY]
13064
13065         # compute memory used by instances
13066         pnr_dyn = {
13067           "total_memory": remote_info["memory_total"],
13068           "reserved_memory": remote_info["memory_dom0"],
13069           "free_memory": remote_info["memory_free"],
13070           "total_disk": remote_info["vg_size"],
13071           "free_disk": remote_info["vg_free"],
13072           "total_cpus": remote_info["cpu_total"],
13073           "i_pri_memory": i_p_mem,
13074           "i_pri_up_memory": i_p_up_mem,
13075           }
13076         pnr_dyn.update(node_results[nname])
13077         node_results[nname] = pnr_dyn
13078
13079     return node_results
13080
13081   @staticmethod
13082   def _ComputeInstanceData(cluster_info, i_list):
13083     """Compute global instance data.
13084
13085     """
13086     instance_data = {}
13087     for iinfo, beinfo in i_list:
13088       nic_data = []
13089       for nic in iinfo.nics:
13090         filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
13091         nic_dict = {
13092           "mac": nic.mac,
13093           "ip": nic.ip,
13094           "mode": filled_params[constants.NIC_MODE],
13095           "link": filled_params[constants.NIC_LINK],
13096           }
13097         if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
13098           nic_dict["bridge"] = filled_params[constants.NIC_LINK]
13099         nic_data.append(nic_dict)
13100       pir = {
13101         "tags": list(iinfo.GetTags()),
13102         "admin_up": iinfo.admin_up,
13103         "vcpus": beinfo[constants.BE_VCPUS],
13104         "memory": beinfo[constants.BE_MEMORY],
13105         "os": iinfo.os,
13106         "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
13107         "nics": nic_data,
13108         "disks": [{constants.IDISK_SIZE: dsk.size,
13109                    constants.IDISK_MODE: dsk.mode}
13110                   for dsk in iinfo.disks],
13111         "disk_template": iinfo.disk_template,
13112         "hypervisor": iinfo.hypervisor,
13113         }
13114       pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
13115                                                  pir["disks"])
13116       instance_data[iinfo.name] = pir
13117
13118     return instance_data
13119
13120   def _AddNewInstance(self):
13121     """Add new instance data to allocator structure.
13122
13123     This in combination with _AllocatorGetClusterData will create the
13124     correct structure needed as input for the allocator.
13125
13126     The checks for the completeness of the opcode must have already been
13127     done.
13128
13129     """
13130     disk_space = _ComputeDiskSize(self.disk_template, self.disks)
13131
13132     if self.disk_template in constants.DTS_INT_MIRROR:
13133       self.required_nodes = 2
13134     else:
13135       self.required_nodes = 1
13136
13137     request = {
13138       "name": self.name,
13139       "disk_template": self.disk_template,
13140       "tags": self.tags,
13141       "os": self.os,
13142       "vcpus": self.vcpus,
13143       "memory": self.memory,
13144       "disks": self.disks,
13145       "disk_space_total": disk_space,
13146       "nics": self.nics,
13147       "required_nodes": self.required_nodes,
13148       "hypervisor": self.hypervisor,
13149       }
13150
13151     return request
13152
13153   def _AddRelocateInstance(self):
13154     """Add relocate instance data to allocator structure.
13155
13156     This in combination with _IAllocatorGetClusterData will create the
13157     correct structure needed as input for the allocator.
13158
13159     The checks for the completeness of the opcode must have already been
13160     done.
13161
13162     """
13163     instance = self.cfg.GetInstanceInfo(self.name)
13164     if instance is None:
13165       raise errors.ProgrammerError("Unknown instance '%s' passed to"
13166                                    " IAllocator" % self.name)
13167
13168     if instance.disk_template not in constants.DTS_MIRRORED:
13169       raise errors.OpPrereqError("Can't relocate non-mirrored instances",
13170                                  errors.ECODE_INVAL)
13171
13172     if instance.disk_template in constants.DTS_INT_MIRROR and \
13173         len(instance.secondary_nodes) != 1:
13174       raise errors.OpPrereqError("Instance has not exactly one secondary node",
13175                                  errors.ECODE_STATE)
13176
13177     self.required_nodes = 1
13178     disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
13179     disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
13180
13181     request = {
13182       "name": self.name,
13183       "disk_space_total": disk_space,
13184       "required_nodes": self.required_nodes,
13185       "relocate_from": self.relocate_from,
13186       }
13187     return request
13188
13189   def _AddNodeEvacuate(self):
13190     """Get data for node-evacuate requests.
13191
13192     """
13193     return {
13194       "instances": self.instances,
13195       "evac_mode": self.evac_mode,
13196       }
13197
13198   def _AddChangeGroup(self):
13199     """Get data for node-evacuate requests.
13200
13201     """
13202     return {
13203       "instances": self.instances,
13204       "target_groups": self.target_groups,
13205       }
13206
13207   def _BuildInputData(self, fn, keydata):
13208     """Build input data structures.
13209
13210     """
13211     self._ComputeClusterData()
13212
13213     request = fn()
13214     request["type"] = self.mode
13215     for keyname, keytype in keydata:
13216       if keyname not in request:
13217         raise errors.ProgrammerError("Request parameter %s is missing" %
13218                                      keyname)
13219       val = request[keyname]
13220       if not keytype(val):
13221         raise errors.ProgrammerError("Request parameter %s doesn't pass"
13222                                      " validation, value %s, expected"
13223                                      " type %s" % (keyname, val, keytype))
13224     self.in_data["request"] = request
13225
13226     self.in_text = serializer.Dump(self.in_data)
13227
13228   _STRING_LIST = ht.TListOf(ht.TString)
13229   _JOB_LIST = ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
13230      # pylint: disable=E1101
13231      # Class '...' has no 'OP_ID' member
13232      "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
13233                           opcodes.OpInstanceMigrate.OP_ID,
13234                           opcodes.OpInstanceReplaceDisks.OP_ID])
13235      })))
13236
13237   _NEVAC_MOVED = \
13238     ht.TListOf(ht.TAnd(ht.TIsLength(3),
13239                        ht.TItems([ht.TNonEmptyString,
13240                                   ht.TNonEmptyString,
13241                                   ht.TListOf(ht.TNonEmptyString),
13242                                  ])))
13243   _NEVAC_FAILED = \
13244     ht.TListOf(ht.TAnd(ht.TIsLength(2),
13245                        ht.TItems([ht.TNonEmptyString,
13246                                   ht.TMaybeString,
13247                                  ])))
13248   _NEVAC_RESULT = ht.TAnd(ht.TIsLength(3),
13249                           ht.TItems([_NEVAC_MOVED, _NEVAC_FAILED, _JOB_LIST]))
13250
13251   _MODE_DATA = {
13252     constants.IALLOCATOR_MODE_ALLOC:
13253       (_AddNewInstance,
13254        [
13255         ("name", ht.TString),
13256         ("memory", ht.TInt),
13257         ("disks", ht.TListOf(ht.TDict)),
13258         ("disk_template", ht.TString),
13259         ("os", ht.TString),
13260         ("tags", _STRING_LIST),
13261         ("nics", ht.TListOf(ht.TDict)),
13262         ("vcpus", ht.TInt),
13263         ("hypervisor", ht.TString),
13264         ], ht.TList),
13265     constants.IALLOCATOR_MODE_RELOC:
13266       (_AddRelocateInstance,
13267        [("name", ht.TString), ("relocate_from", _STRING_LIST)],
13268        ht.TList),
13269      constants.IALLOCATOR_MODE_NODE_EVAC:
13270       (_AddNodeEvacuate, [
13271         ("instances", _STRING_LIST),
13272         ("evac_mode", ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)),
13273         ], _NEVAC_RESULT),
13274      constants.IALLOCATOR_MODE_CHG_GROUP:
13275       (_AddChangeGroup, [
13276         ("instances", _STRING_LIST),
13277         ("target_groups", _STRING_LIST),
13278         ], _NEVAC_RESULT),
13279     }
13280
13281   def Run(self, name, validate=True, call_fn=None):
13282     """Run an instance allocator and return the results.
13283
13284     """
13285     if call_fn is None:
13286       call_fn = self.rpc.call_iallocator_runner
13287
13288     result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
13289     result.Raise("Failure while running the iallocator script")
13290
13291     self.out_text = result.payload
13292     if validate:
13293       self._ValidateResult()
13294
13295   def _ValidateResult(self):
13296     """Process the allocator results.
13297
13298     This will process and if successful save the result in
13299     self.out_data and the other parameters.
13300
13301     """
13302     try:
13303       rdict = serializer.Load(self.out_text)
13304     except Exception, err:
13305       raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
13306
13307     if not isinstance(rdict, dict):
13308       raise errors.OpExecError("Can't parse iallocator results: not a dict")
13309
13310     # TODO: remove backwards compatiblity in later versions
13311     if "nodes" in rdict and "result" not in rdict:
13312       rdict["result"] = rdict["nodes"]
13313       del rdict["nodes"]
13314
13315     for key in "success", "info", "result":
13316       if key not in rdict:
13317         raise errors.OpExecError("Can't parse iallocator results:"
13318                                  " missing key '%s'" % key)
13319       setattr(self, key, rdict[key])
13320
13321     if not self._result_check(self.result):
13322       raise errors.OpExecError("Iallocator returned invalid result,"
13323                                " expected %s, got %s" %
13324                                (self._result_check, self.result),
13325                                errors.ECODE_INVAL)
13326
13327     if self.mode == constants.IALLOCATOR_MODE_RELOC:
13328       assert self.relocate_from is not None
13329       assert self.required_nodes == 1
13330
13331       node2group = dict((name, ndata["group"])
13332                         for (name, ndata) in self.in_data["nodes"].items())
13333
13334       fn = compat.partial(self._NodesToGroups, node2group,
13335                           self.in_data["nodegroups"])
13336
13337       instance = self.cfg.GetInstanceInfo(self.name)
13338       request_groups = fn(self.relocate_from + [instance.primary_node])
13339       result_groups = fn(rdict["result"] + [instance.primary_node])
13340
13341       if self.success and not set(result_groups).issubset(request_groups):
13342         raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
13343                                  " differ from original groups (%s)" %
13344                                  (utils.CommaJoin(result_groups),
13345                                   utils.CommaJoin(request_groups)))
13346
13347     elif self.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
13348       assert self.evac_mode in constants.IALLOCATOR_NEVAC_MODES
13349
13350     self.out_data = rdict
13351
13352   @staticmethod
13353   def _NodesToGroups(node2group, groups, nodes):
13354     """Returns a list of unique group names for a list of nodes.
13355
13356     @type node2group: dict
13357     @param node2group: Map from node name to group UUID
13358     @type groups: dict
13359     @param groups: Group information
13360     @type nodes: list
13361     @param nodes: Node names
13362
13363     """
13364     result = set()
13365
13366     for node in nodes:
13367       try:
13368         group_uuid = node2group[node]
13369       except KeyError:
13370         # Ignore unknown node
13371         pass
13372       else:
13373         try:
13374           group = groups[group_uuid]
13375         except KeyError:
13376           # Can't find group, let's use UUID
13377           group_name = group_uuid
13378         else:
13379           group_name = group["name"]
13380
13381         result.add(group_name)
13382
13383     return sorted(result)
13384
13385
13386 class LUTestAllocator(NoHooksLU):
13387   """Run allocator tests.
13388
13389   This LU runs the allocator tests
13390
13391   """
13392   def CheckPrereq(self):
13393     """Check prerequisites.
13394
13395     This checks the opcode parameters depending on the director and mode test.
13396
13397     """
13398     if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
13399       for attr in ["memory", "disks", "disk_template",
13400                    "os", "tags", "nics", "vcpus"]:
13401         if not hasattr(self.op, attr):
13402           raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
13403                                      attr, errors.ECODE_INVAL)
13404       iname = self.cfg.ExpandInstanceName(self.op.name)
13405       if iname is not None:
13406         raise errors.OpPrereqError("Instance '%s' already in the cluster" %
13407                                    iname, errors.ECODE_EXISTS)
13408       if not isinstance(self.op.nics, list):
13409         raise errors.OpPrereqError("Invalid parameter 'nics'",
13410                                    errors.ECODE_INVAL)
13411       if not isinstance(self.op.disks, list):
13412         raise errors.OpPrereqError("Invalid parameter 'disks'",
13413                                    errors.ECODE_INVAL)
13414       for row in self.op.disks:
13415         if (not isinstance(row, dict) or
13416             constants.IDISK_SIZE not in row or
13417             not isinstance(row[constants.IDISK_SIZE], int) or
13418             constants.IDISK_MODE not in row or
13419             row[constants.IDISK_MODE] not in constants.DISK_ACCESS_SET):
13420           raise errors.OpPrereqError("Invalid contents of the 'disks'"
13421                                      " parameter", errors.ECODE_INVAL)
13422       if self.op.hypervisor is None:
13423         self.op.hypervisor = self.cfg.GetHypervisorType()
13424     elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
13425       fname = _ExpandInstanceName(self.cfg, self.op.name)
13426       self.op.name = fname
13427       self.relocate_from = \
13428           list(self.cfg.GetInstanceInfo(fname).secondary_nodes)
13429     elif self.op.mode in (constants.IALLOCATOR_MODE_CHG_GROUP,
13430                           constants.IALLOCATOR_MODE_NODE_EVAC):
13431       if not self.op.instances:
13432         raise errors.OpPrereqError("Missing instances", errors.ECODE_INVAL)
13433       self.op.instances = _GetWantedInstances(self, self.op.instances)
13434     else:
13435       raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
13436                                  self.op.mode, errors.ECODE_INVAL)
13437
13438     if self.op.direction == constants.IALLOCATOR_DIR_OUT:
13439       if self.op.allocator is None:
13440         raise errors.OpPrereqError("Missing allocator name",
13441                                    errors.ECODE_INVAL)
13442     elif self.op.direction != constants.IALLOCATOR_DIR_IN:
13443       raise errors.OpPrereqError("Wrong allocator test '%s'" %
13444                                  self.op.direction, errors.ECODE_INVAL)
13445
13446   def Exec(self, feedback_fn):
13447     """Run the allocator test.
13448
13449     """
13450     if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
13451       ial = IAllocator(self.cfg, self.rpc,
13452                        mode=self.op.mode,
13453                        name=self.op.name,
13454                        memory=self.op.memory,
13455                        disks=self.op.disks,
13456                        disk_template=self.op.disk_template,
13457                        os=self.op.os,
13458                        tags=self.op.tags,
13459                        nics=self.op.nics,
13460                        vcpus=self.op.vcpus,
13461                        hypervisor=self.op.hypervisor,
13462                        )
13463     elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
13464       ial = IAllocator(self.cfg, self.rpc,
13465                        mode=self.op.mode,
13466                        name=self.op.name,
13467                        relocate_from=list(self.relocate_from),
13468                        )
13469     elif self.op.mode == constants.IALLOCATOR_MODE_CHG_GROUP:
13470       ial = IAllocator(self.cfg, self.rpc,
13471                        mode=self.op.mode,
13472                        instances=self.op.instances,
13473                        target_groups=self.op.target_groups)
13474     elif self.op.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
13475       ial = IAllocator(self.cfg, self.rpc,
13476                        mode=self.op.mode,
13477                        instances=self.op.instances,
13478                        evac_mode=self.op.evac_mode)
13479     else:
13480       raise errors.ProgrammerError("Uncatched mode %s in"
13481                                    " LUTestAllocator.Exec", self.op.mode)
13482
13483     if self.op.direction == constants.IALLOCATOR_DIR_IN:
13484       result = ial.in_text
13485     else:
13486       ial.Run(self.op.allocator, validate=False)
13487       result = ial.out_text
13488     return result
13489
13490
13491 #: Query type implementations
13492 _QUERY_IMPL = {
13493   constants.QR_INSTANCE: _InstanceQuery,
13494   constants.QR_NODE: _NodeQuery,
13495   constants.QR_GROUP: _GroupQuery,
13496   constants.QR_OS: _OsQuery,
13497   }
13498
13499 assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
13500
13501
13502 def _GetQueryImplementation(name):
13503   """Returns the implemtnation for a query type.
13504
13505   @param name: Query type, must be one of L{constants.QR_VIA_OP}
13506
13507   """
13508   try:
13509     return _QUERY_IMPL[name]
13510   except KeyError:
13511     raise errors.OpPrereqError("Unknown query resource '%s'" % name,
13512                                errors.ECODE_INVAL)