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