DeprecationWarning fixes for pylint
[ganeti-local] / lib / opcodes.py
1 #
2 #
3
4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 # 02110-1301, USA.
20
21
22 """OpCodes module
23
24 This module implements the data structures which define the cluster
25 operations - the so-called opcodes.
26
27 Every operation which modifies the cluster state is expressed via
28 opcodes.
29
30 """
31
32 # this are practically structures, so disable the message about too
33 # few public methods:
34 # pylint: disable=R0903
35
36 import logging
37 import re
38
39 from ganeti import compat
40 from ganeti import constants
41 from ganeti import errors
42 from ganeti import ht
43
44
45 # Common opcode attributes
46
47 #: output fields for a query operation
48 _POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
49                   "Selected output fields")
50
51 #: the shutdown timeout
52 _PShutdownTimeout = \
53   ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
54    "How long to wait for instance to shut down")
55
56 #: the force parameter
57 _PForce = ("force", False, ht.TBool, "Whether to force the operation")
58
59 #: a required instance name (for single-instance LUs)
60 _PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString,
61                   "Instance name")
62
63 #: Whether to ignore offline nodes
64 _PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
65                         "Whether to ignore offline nodes")
66
67 #: a required node name (for single-node LUs)
68 _PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
69
70 #: a required node group name (for single-group LUs)
71 _PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
72
73 #: Migration type (live/non-live)
74 _PMigrationMode = ("mode", None,
75                    ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)),
76                    "Migration mode")
77
78 #: Obsolete 'live' migration mode (boolean)
79 _PMigrationLive = ("live", None, ht.TMaybeBool,
80                    "Legacy setting for live migration, do not use")
81
82 #: Tag type
83 _PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
84
85 #: List of tag strings
86 _PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
87
88 _PForceVariant = ("force_variant", False, ht.TBool,
89                   "Whether to force an unknown OS variant")
90
91 _PWaitForSync = ("wait_for_sync", True, ht.TBool,
92                  "Whether to wait for the disk to synchronize")
93
94 _PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
95                        "Whether to ignore disk consistency")
96
97 _PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
98
99 _PUseLocking = ("use_locking", False, ht.TBool,
100                 "Whether to use synchronization")
101
102 _PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
103
104 _PNodeGroupAllocPolicy = \
105   ("alloc_policy", None,
106    ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
107    "Instance allocation policy")
108
109 _PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
110                      "Default node parameters for group")
111
112 _PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
113                "Resource(s) to query for")
114
115 _PEarlyRelease = ("early_release", False, ht.TBool,
116                   "Whether to release locks as soon as possible")
117
118 _PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
119
120 #: Do not remember instance state changes
121 _PNoRemember = ("no_remember", False, ht.TBool,
122                 "Do not remember the state change")
123
124 #: Target node for instance migration/failover
125 _PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
126                          "Target node for shared-storage instances")
127
128 _PStartupPaused = ("startup_paused", False, ht.TBool,
129                    "Pause instance at startup")
130
131 _PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
132
133 # Parameters for cluster verification
134 _PDebugSimulateErrors = ("debug_simulate_errors", False, ht.TBool,
135                          "Whether to simulate errors (useful for debugging)")
136 _PErrorCodes = ("error_codes", False, ht.TBool, "Error codes")
137 _PSkipChecks = ("skip_checks", ht.EmptyList,
138                 ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)),
139                 "Which checks to skip")
140
141 #: OP_ID conversion regular expression
142 _OPID_RE = re.compile("([a-z])([A-Z])")
143
144 #: Utility function for L{OpClusterSetParams}
145 _TestClusterOsList = ht.TOr(ht.TNone,
146   ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
147     ht.TMap(ht.WithDesc("GetFirstItem")(compat.fst),
148             ht.TElemOf(constants.DDMS_VALUES)))))
149
150
151 # TODO: Generate check from constants.INIC_PARAMS_TYPES
152 #: Utility function for testing NIC definitions
153 _TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
154                          ht.TOr(ht.TNone, ht.TNonEmptyString))
155
156 _TSetParamsResultItemItems = [
157   ht.Comment("name of changed parameter")(ht.TNonEmptyString),
158   ht.TAny,
159   ]
160
161 _TSetParamsResult = \
162   ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
163                      ht.TItems(_TSetParamsResultItemItems)))
164
165 _SUMMARY_PREFIX = {
166   "CLUSTER_": "C_",
167   "GROUP_": "G_",
168   "NODE_": "N_",
169   "INSTANCE_": "I_",
170   }
171
172 #: Attribute name for dependencies
173 DEPEND_ATTR = "depends"
174
175 #: Attribute name for comment
176 COMMENT_ATTR = "comment"
177
178
179 def _NameToId(name):
180   """Convert an opcode class name to an OP_ID.
181
182   @type name: string
183   @param name: the class name, as OpXxxYyy
184   @rtype: string
185   @return: the name in the OP_XXXX_YYYY format
186
187   """
188   if not name.startswith("Op"):
189     return None
190   # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
191   # consume any input, and hence we would just have all the elements
192   # in the list, one by one; but it seems that split doesn't work on
193   # non-consuming input, hence we have to process the input string a
194   # bit
195   name = _OPID_RE.sub(r"\1,\2", name)
196   elems = name.split(",")
197   return "_".join(n.upper() for n in elems)
198
199
200 def RequireFileStorage():
201   """Checks that file storage is enabled.
202
203   While it doesn't really fit into this module, L{utils} was deemed too large
204   of a dependency to be imported for just one or two functions.
205
206   @raise errors.OpPrereqError: when file storage is disabled
207
208   """
209   if not constants.ENABLE_FILE_STORAGE:
210     raise errors.OpPrereqError("File storage disabled at configure time",
211                                errors.ECODE_INVAL)
212
213
214 def RequireSharedFileStorage():
215   """Checks that shared file storage is enabled.
216
217   While it doesn't really fit into this module, L{utils} was deemed too large
218   of a dependency to be imported for just one or two functions.
219
220   @raise errors.OpPrereqError: when shared file storage is disabled
221
222   """
223   if not constants.ENABLE_SHARED_FILE_STORAGE:
224     raise errors.OpPrereqError("Shared file storage disabled at"
225                                " configure time", errors.ECODE_INVAL)
226
227
228 @ht.WithDesc("CheckFileStorage")
229 def _CheckFileStorage(value):
230   """Ensures file storage is enabled if used.
231
232   """
233   if value == constants.DT_FILE:
234     RequireFileStorage()
235   elif value == constants.DT_SHARED_FILE:
236     RequireSharedFileStorage()
237   return True
238
239
240 _CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
241                              _CheckFileStorage)
242
243
244 def _CheckStorageType(storage_type):
245   """Ensure a given storage type is valid.
246
247   """
248   if storage_type not in constants.VALID_STORAGE_TYPES:
249     raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
250                                errors.ECODE_INVAL)
251   if storage_type == constants.ST_FILE:
252     RequireFileStorage()
253   return True
254
255
256 #: Storage type parameter
257 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
258                  "Storage type")
259
260
261 class _AutoOpParamSlots(type):
262   """Meta class for opcode definitions.
263
264   """
265   def __new__(mcs, name, bases, attrs):
266     """Called when a class should be created.
267
268     @param mcs: The meta class
269     @param name: Name of created class
270     @param bases: Base classes
271     @type attrs: dict
272     @param attrs: Class attributes
273
274     """
275     assert "__slots__" not in attrs, \
276       "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
277     assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
278
279     attrs["OP_ID"] = _NameToId(name)
280
281     # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
282     params = attrs.setdefault("OP_PARAMS", [])
283
284     # Use parameter names as slots
285     slots = [pname for (pname, _, _, _) in params]
286
287     assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
288       "Class '%s' uses unknown field in OP_DSC_FIELD" % name
289
290     attrs["__slots__"] = slots
291
292     return type.__new__(mcs, name, bases, attrs)
293
294
295 class BaseOpCode(object):
296   """A simple serializable object.
297
298   This object serves as a parent class for OpCode without any custom
299   field handling.
300
301   """
302   # pylint: disable=E1101
303   # as OP_ID is dynamically defined
304   __metaclass__ = _AutoOpParamSlots
305
306   def __init__(self, **kwargs):
307     """Constructor for BaseOpCode.
308
309     The constructor takes only keyword arguments and will set
310     attributes on this object based on the passed arguments. As such,
311     it means that you should not pass arguments which are not in the
312     __slots__ attribute for this class.
313
314     """
315     slots = self._all_slots()
316     for key in kwargs:
317       if key not in slots:
318         raise TypeError("Object %s doesn't support the parameter '%s'" %
319                         (self.__class__.__name__, key))
320       setattr(self, key, kwargs[key])
321
322   def __getstate__(self):
323     """Generic serializer.
324
325     This method just returns the contents of the instance as a
326     dictionary.
327
328     @rtype:  C{dict}
329     @return: the instance attributes and their values
330
331     """
332     state = {}
333     for name in self._all_slots():
334       if hasattr(self, name):
335         state[name] = getattr(self, name)
336     return state
337
338   def __setstate__(self, state):
339     """Generic unserializer.
340
341     This method just restores from the serialized state the attributes
342     of the current instance.
343
344     @param state: the serialized opcode data
345     @type state:  C{dict}
346
347     """
348     if not isinstance(state, dict):
349       raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
350                        type(state))
351
352     for name in self._all_slots():
353       if name not in state and hasattr(self, name):
354         delattr(self, name)
355
356     for name in state:
357       setattr(self, name, state[name])
358
359   @classmethod
360   def _all_slots(cls):
361     """Compute the list of all declared slots for a class.
362
363     """
364     slots = []
365     for parent in cls.__mro__:
366       slots.extend(getattr(parent, "__slots__", []))
367     return slots
368
369   @classmethod
370   def GetAllParams(cls):
371     """Compute list of all parameters for an opcode.
372
373     """
374     slots = []
375     for parent in cls.__mro__:
376       slots.extend(getattr(parent, "OP_PARAMS", []))
377     return slots
378
379   def Validate(self, set_defaults):
380     """Validate opcode parameters, optionally setting default values.
381
382     @type set_defaults: bool
383     @param set_defaults: Whether to set default values
384     @raise errors.OpPrereqError: When a parameter value doesn't match
385                                  requirements
386
387     """
388     for (attr_name, default, test, _) in self.GetAllParams():
389       assert test == ht.NoType or callable(test)
390
391       if not hasattr(self, attr_name):
392         if default == ht.NoDefault:
393           raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
394                                      (self.OP_ID, attr_name),
395                                      errors.ECODE_INVAL)
396         elif set_defaults:
397           if callable(default):
398             dval = default()
399           else:
400             dval = default
401           setattr(self, attr_name, dval)
402
403       if test == ht.NoType:
404         # no tests here
405         continue
406
407       if set_defaults or hasattr(self, attr_name):
408         attr_val = getattr(self, attr_name)
409         if not test(attr_val):
410           logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
411                         self.OP_ID, attr_name, type(attr_val), attr_val)
412           raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
413                                      (self.OP_ID, attr_name),
414                                      errors.ECODE_INVAL)
415
416
417 def _BuildJobDepCheck(relative):
418   """Builds check for job dependencies (L{DEPEND_ATTR}).
419
420   @type relative: bool
421   @param relative: Whether to accept relative job IDs (negative)
422   @rtype: callable
423
424   """
425   if relative:
426     job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
427   else:
428     job_id = ht.TJobId
429
430   job_dep = \
431     ht.TAnd(ht.TIsLength(2),
432             ht.TItems([job_id,
433                        ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
434
435   return ht.TOr(ht.TNone, ht.TListOf(job_dep))
436
437
438 TNoRelativeJobDependencies = _BuildJobDepCheck(False)
439
440 #: List of submission status and job ID as returned by C{SubmitManyJobs}
441 _TJobIdListItem = \
442   ht.TAnd(ht.TIsLength(2),
443           ht.TItems([ht.Comment("success")(ht.TBool),
444                      ht.Comment("Job ID if successful, error message"
445                                 " otherwise")(ht.TOr(ht.TString,
446                                                      ht.TJobId))]))
447 TJobIdList = ht.TListOf(_TJobIdListItem)
448
449 #: Result containing only list of submitted jobs
450 TJobIdListOnly = ht.TStrictDict(True, True, {
451   constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
452   })
453
454
455 class OpCode(BaseOpCode):
456   """Abstract OpCode.
457
458   This is the root of the actual OpCode hierarchy. All clases derived
459   from this class should override OP_ID.
460
461   @cvar OP_ID: The ID of this opcode. This should be unique amongst all
462                children of this class.
463   @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
464                       string returned by Summary(); see the docstring of that
465                       method for details).
466   @cvar OP_PARAMS: List of opcode attributes, the default values they should
467                    get if not already defined, and types they must match.
468   @cvar OP_RESULT: Callable to verify opcode result
469   @cvar WITH_LU: Boolean that specifies whether this should be included in
470       mcpu's dispatch table
471   @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
472                  the check steps
473   @ivar priority: Opcode priority for queue
474
475   """
476   # pylint: disable=E1101
477   # as OP_ID is dynamically defined
478   WITH_LU = True
479   OP_PARAMS = [
480     ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
481     ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
482     ("priority", constants.OP_PRIO_DEFAULT,
483      ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
484     (DEPEND_ATTR, None, _BuildJobDepCheck(True),
485      "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
486      " job IDs can be used"),
487     (COMMENT_ATTR, None, ht.TMaybeString,
488      "Comment describing the purpose of the opcode"),
489     ]
490   OP_RESULT = None
491
492   def __getstate__(self):
493     """Specialized getstate for opcodes.
494
495     This method adds to the state dictionary the OP_ID of the class,
496     so that on unload we can identify the correct class for
497     instantiating the opcode.
498
499     @rtype:   C{dict}
500     @return:  the state as a dictionary
501
502     """
503     data = BaseOpCode.__getstate__(self)
504     data["OP_ID"] = self.OP_ID
505     return data
506
507   @classmethod
508   def LoadOpCode(cls, data):
509     """Generic load opcode method.
510
511     The method identifies the correct opcode class from the dict-form
512     by looking for a OP_ID key, if this is not found, or its value is
513     not available in this module as a child of this class, we fail.
514
515     @type data:  C{dict}
516     @param data: the serialized opcode
517
518     """
519     if not isinstance(data, dict):
520       raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
521     if "OP_ID" not in data:
522       raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
523     op_id = data["OP_ID"]
524     op_class = None
525     if op_id in OP_MAPPING:
526       op_class = OP_MAPPING[op_id]
527     else:
528       raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
529                        op_id)
530     op = op_class()
531     new_data = data.copy()
532     del new_data["OP_ID"]
533     op.__setstate__(new_data)
534     return op
535
536   def Summary(self):
537     """Generates a summary description of this opcode.
538
539     The summary is the value of the OP_ID attribute (without the "OP_"
540     prefix), plus the value of the OP_DSC_FIELD attribute, if one was
541     defined; this field should allow to easily identify the operation
542     (for an instance creation job, e.g., it would be the instance
543     name).
544
545     """
546     assert self.OP_ID is not None and len(self.OP_ID) > 3
547     # all OP_ID start with OP_, we remove that
548     txt = self.OP_ID[3:]
549     field_name = getattr(self, "OP_DSC_FIELD", None)
550     if field_name:
551       field_value = getattr(self, field_name, None)
552       if isinstance(field_value, (list, tuple)):
553         field_value = ",".join(str(i) for i in field_value)
554       txt = "%s(%s)" % (txt, field_value)
555     return txt
556
557   def TinySummary(self):
558     """Generates a compact summary description of the opcode.
559
560     """
561     assert self.OP_ID.startswith("OP_")
562
563     text = self.OP_ID[3:]
564
565     for (prefix, supplement) in _SUMMARY_PREFIX.items():
566       if text.startswith(prefix):
567         return supplement + text[len(prefix):]
568
569     return text
570
571
572 # cluster opcodes
573
574 class OpClusterPostInit(OpCode):
575   """Post cluster initialization.
576
577   This opcode does not touch the cluster at all. Its purpose is to run hooks
578   after the cluster has been initialized.
579
580   """
581
582
583 class OpClusterDestroy(OpCode):
584   """Destroy the cluster.
585
586   This opcode has no other parameters. All the state is irreversibly
587   lost after the execution of this opcode.
588
589   """
590
591
592 class OpClusterQuery(OpCode):
593   """Query cluster information."""
594
595
596 class OpClusterVerify(OpCode):
597   """Submits all jobs necessary to verify the cluster.
598
599   """
600   OP_PARAMS = [
601     _PDebugSimulateErrors,
602     _PErrorCodes,
603     _PSkipChecks,
604     _PVerbose,
605     ("group_name", None, ht.TMaybeString, "Group to verify")
606     ]
607   OP_RESULT = TJobIdListOnly
608
609
610 class OpClusterVerifyConfig(OpCode):
611   """Verify the cluster config.
612
613   """
614   OP_PARAMS = [
615     _PDebugSimulateErrors,
616     _PErrorCodes,
617     _PVerbose,
618     ]
619   OP_RESULT = ht.TBool
620
621
622 class OpClusterVerifyGroup(OpCode):
623   """Run verify on a node group from the cluster.
624
625   @type skip_checks: C{list}
626   @ivar skip_checks: steps to be skipped from the verify process; this
627                      needs to be a subset of
628                      L{constants.VERIFY_OPTIONAL_CHECKS}; currently
629                      only L{constants.VERIFY_NPLUSONE_MEM} can be passed
630
631   """
632   OP_DSC_FIELD = "group_name"
633   OP_PARAMS = [
634     _PGroupName,
635     _PDebugSimulateErrors,
636     _PErrorCodes,
637     _PSkipChecks,
638     _PVerbose,
639     ]
640   OP_RESULT = ht.TBool
641
642
643 class OpClusterVerifyDisks(OpCode):
644   """Verify the cluster disks.
645
646   """
647   OP_RESULT = TJobIdListOnly
648
649
650 class OpGroupVerifyDisks(OpCode):
651   """Verifies the status of all disks in a node group.
652
653   Result: a tuple of three elements:
654     - dict of node names with issues (values: error msg)
655     - list of instances with degraded disks (that should be activated)
656     - dict of instances with missing logical volumes (values: (node, vol)
657       pairs with details about the missing volumes)
658
659   In normal operation, all lists should be empty. A non-empty instance
660   list (3rd element of the result) is still ok (errors were fixed) but
661   non-empty node list means some node is down, and probably there are
662   unfixable drbd errors.
663
664   Note that only instances that are drbd-based are taken into
665   consideration. This might need to be revisited in the future.
666
667   """
668   OP_DSC_FIELD = "group_name"
669   OP_PARAMS = [
670     _PGroupName,
671     ]
672   OP_RESULT = \
673     ht.TAnd(ht.TIsLength(3),
674             ht.TItems([ht.TDictOf(ht.TString, ht.TString),
675                        ht.TListOf(ht.TString),
676                        ht.TDictOf(ht.TString, ht.TListOf(ht.TString))]))
677
678
679 class OpClusterRepairDiskSizes(OpCode):
680   """Verify the disk sizes of the instances and fixes configuration
681   mimatches.
682
683   Parameters: optional instances list, in case we want to restrict the
684   checks to only a subset of the instances.
685
686   Result: a list of tuples, (instance, disk, new-size) for changed
687   configurations.
688
689   In normal operation, the list should be empty.
690
691   @type instances: list
692   @ivar instances: the list of instances to check, or empty for all instances
693
694   """
695   OP_PARAMS = [
696     ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
697     ]
698
699
700 class OpClusterConfigQuery(OpCode):
701   """Query cluster configuration values."""
702   OP_PARAMS = [
703     _POutputFields
704     ]
705
706
707 class OpClusterRename(OpCode):
708   """Rename the cluster.
709
710   @type name: C{str}
711   @ivar name: The new name of the cluster. The name and/or the master IP
712               address will be changed to match the new name and its IP
713               address.
714
715   """
716   OP_DSC_FIELD = "name"
717   OP_PARAMS = [
718     ("name", ht.NoDefault, ht.TNonEmptyString, None),
719     ]
720
721
722 class OpClusterSetParams(OpCode):
723   """Change the parameters of the cluster.
724
725   @type vg_name: C{str} or C{None}
726   @ivar vg_name: The new volume group name or None to disable LVM usage.
727
728   """
729   OP_PARAMS = [
730     ("vg_name", None, ht.TMaybeString, "Volume group name"),
731     ("enabled_hypervisors", None,
732      ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
733             ht.TNone),
734      "List of enabled hypervisors"),
735     ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
736                               ht.TNone),
737      "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
738     ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
739      "Cluster-wide backend parameter defaults"),
740     ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
741                             ht.TNone),
742      "Cluster-wide per-OS hypervisor parameter defaults"),
743     ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
744                               ht.TNone),
745      "Cluster-wide OS parameter defaults"),
746     ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
747      "Master candidate pool size"),
748     ("uid_pool", None, ht.NoType,
749      "Set UID pool, must be list of lists describing UID ranges (two items,"
750      " start and end inclusive)"),
751     ("add_uids", None, ht.NoType,
752      "Extend UID pool, must be list of lists describing UID ranges (two"
753      " items, start and end inclusive) to be added"),
754     ("remove_uids", None, ht.NoType,
755      "Shrink UID pool, must be list of lists describing UID ranges (two"
756      " items, start and end inclusive) to be removed"),
757     ("maintain_node_health", None, ht.TMaybeBool,
758      "Whether to automatically maintain node health"),
759     ("prealloc_wipe_disks", None, ht.TMaybeBool,
760      "Whether to wipe disks before allocating them to instances"),
761     ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
762     ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
763     ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
764     ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
765      "Default iallocator for cluster"),
766     ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
767      "Master network device"),
768     ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
769      "List of reserved LVs"),
770     ("hidden_os", None, _TestClusterOsList,
771      "Modify list of hidden operating systems. Each modification must have"
772      " two items, the operation and the OS name. The operation can be"
773      " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
774     ("blacklisted_os", None, _TestClusterOsList,
775      "Modify list of blacklisted operating systems. Each modification must have"
776      " two items, the operation and the OS name. The operation can be"
777      " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
778     ]
779
780
781 class OpClusterRedistConf(OpCode):
782   """Force a full push of the cluster configuration.
783
784   """
785
786
787 class OpQuery(OpCode):
788   """Query for resources/items.
789
790   @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
791   @ivar fields: List of fields to retrieve
792   @ivar filter: Query filter
793
794   """
795   OP_DSC_FIELD = "what"
796   OP_PARAMS = [
797     _PQueryWhat,
798     _PUseLocking,
799     ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
800      "Requested fields"),
801     ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
802      "Query filter"),
803     ]
804
805
806 class OpQueryFields(OpCode):
807   """Query for available resource/item fields.
808
809   @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
810   @ivar fields: List of fields to retrieve
811
812   """
813   OP_DSC_FIELD = "what"
814   OP_PARAMS = [
815     _PQueryWhat,
816     ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
817      "Requested fields; if not given, all are returned"),
818     ]
819
820
821 class OpOobCommand(OpCode):
822   """Interact with OOB."""
823   OP_PARAMS = [
824     ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
825      "List of nodes to run the OOB command against"),
826     ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
827      "OOB command to be run"),
828     ("timeout", constants.OOB_TIMEOUT, ht.TInt,
829      "Timeout before the OOB helper will be terminated"),
830     ("ignore_status", False, ht.TBool,
831      "Ignores the node offline status for power off"),
832     ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
833      "Time in seconds to wait between powering on nodes"),
834     ]
835
836
837 # node opcodes
838
839 class OpNodeRemove(OpCode):
840   """Remove a node.
841
842   @type node_name: C{str}
843   @ivar node_name: The name of the node to remove. If the node still has
844                    instances on it, the operation will fail.
845
846   """
847   OP_DSC_FIELD = "node_name"
848   OP_PARAMS = [
849     _PNodeName,
850     ]
851
852
853 class OpNodeAdd(OpCode):
854   """Add a node to the cluster.
855
856   @type node_name: C{str}
857   @ivar node_name: The name of the node to add. This can be a short name,
858                    but it will be expanded to the FQDN.
859   @type primary_ip: IP address
860   @ivar primary_ip: The primary IP of the node. This will be ignored when the
861                     opcode is submitted, but will be filled during the node
862                     add (so it will be visible in the job query).
863   @type secondary_ip: IP address
864   @ivar secondary_ip: The secondary IP of the node. This needs to be passed
865                       if the cluster has been initialized in 'dual-network'
866                       mode, otherwise it must not be given.
867   @type readd: C{bool}
868   @ivar readd: Whether to re-add an existing node to the cluster. If
869                this is not passed, then the operation will abort if the node
870                name is already in the cluster; use this parameter to 'repair'
871                a node that had its configuration broken, or was reinstalled
872                without removal from the cluster.
873   @type group: C{str}
874   @ivar group: The node group to which this node will belong.
875   @type vm_capable: C{bool}
876   @ivar vm_capable: The vm_capable node attribute
877   @type master_capable: C{bool}
878   @ivar master_capable: The master_capable node attribute
879
880   """
881   OP_DSC_FIELD = "node_name"
882   OP_PARAMS = [
883     _PNodeName,
884     ("primary_ip", None, ht.NoType, "Primary IP address"),
885     ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
886     ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
887     ("group", None, ht.TMaybeString, "Initial node group"),
888     ("master_capable", None, ht.TMaybeBool,
889      "Whether node can become master or master candidate"),
890     ("vm_capable", None, ht.TMaybeBool,
891      "Whether node can host instances"),
892     ("ndparams", None, ht.TMaybeDict, "Node parameters"),
893     ]
894
895
896 class OpNodeQuery(OpCode):
897   """Compute the list of nodes."""
898   OP_PARAMS = [
899     _POutputFields,
900     _PUseLocking,
901     ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
902      "Empty list to query all nodes, node names otherwise"),
903     ]
904
905
906 class OpNodeQueryvols(OpCode):
907   """Get list of volumes on node."""
908   OP_PARAMS = [
909     _POutputFields,
910     ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
911      "Empty list to query all nodes, node names otherwise"),
912     ]
913
914
915 class OpNodeQueryStorage(OpCode):
916   """Get information on storage for node(s)."""
917   OP_PARAMS = [
918     _POutputFields,
919     _PStorageType,
920     ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
921     ("name", None, ht.TMaybeString, "Storage name"),
922     ]
923
924
925 class OpNodeModifyStorage(OpCode):
926   """Modifies the properies of a storage unit"""
927   OP_PARAMS = [
928     _PNodeName,
929     _PStorageType,
930     _PStorageName,
931     ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
932     ]
933
934
935 class OpRepairNodeStorage(OpCode):
936   """Repairs the volume group on a node."""
937   OP_DSC_FIELD = "node_name"
938   OP_PARAMS = [
939     _PNodeName,
940     _PStorageType,
941     _PStorageName,
942     _PIgnoreConsistency,
943     ]
944
945
946 class OpNodeSetParams(OpCode):
947   """Change the parameters of a node."""
948   OP_DSC_FIELD = "node_name"
949   OP_PARAMS = [
950     _PNodeName,
951     _PForce,
952     ("master_candidate", None, ht.TMaybeBool,
953      "Whether the node should become a master candidate"),
954     ("offline", None, ht.TMaybeBool,
955      "Whether the node should be marked as offline"),
956     ("drained", None, ht.TMaybeBool,
957      "Whether the node should be marked as drained"),
958     ("auto_promote", False, ht.TBool,
959      "Whether node(s) should be promoted to master candidate if necessary"),
960     ("master_capable", None, ht.TMaybeBool,
961      "Denote whether node can become master or master candidate"),
962     ("vm_capable", None, ht.TMaybeBool,
963      "Denote whether node can host instances"),
964     ("secondary_ip", None, ht.TMaybeString,
965      "Change node's secondary IP address"),
966     ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
967     ("powered", None, ht.TMaybeBool,
968      "Whether the node should be marked as powered"),
969     ]
970   OP_RESULT = _TSetParamsResult
971
972
973 class OpNodePowercycle(OpCode):
974   """Tries to powercycle a node."""
975   OP_DSC_FIELD = "node_name"
976   OP_PARAMS = [
977     _PNodeName,
978     _PForce,
979     ]
980
981
982 class OpNodeMigrate(OpCode):
983   """Migrate all instances from a node."""
984   OP_DSC_FIELD = "node_name"
985   OP_PARAMS = [
986     _PNodeName,
987     _PMigrationMode,
988     _PMigrationLive,
989     _PMigrationTargetNode,
990     ("iallocator", None, ht.TMaybeString,
991      "Iallocator for deciding the target node for shared-storage instances"),
992     ]
993
994
995 class OpNodeEvacuate(OpCode):
996   """Evacuate instances off a number of nodes."""
997   OP_DSC_FIELD = "node_name"
998   OP_PARAMS = [
999     _PEarlyRelease,
1000     _PNodeName,
1001     ("remote_node", None, ht.TMaybeString, "New secondary node"),
1002     ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1003     ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
1004      "Node evacuation mode"),
1005     ]
1006   OP_RESULT = TJobIdListOnly
1007
1008
1009 # instance opcodes
1010
1011 class OpInstanceCreate(OpCode):
1012   """Create an instance.
1013
1014   @ivar instance_name: Instance name
1015   @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1016   @ivar source_handshake: Signed handshake from source (remote import only)
1017   @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1018   @ivar source_instance_name: Previous name of instance (remote import only)
1019   @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1020     (remote import only)
1021
1022   """
1023   OP_DSC_FIELD = "instance_name"
1024   OP_PARAMS = [
1025     _PInstanceName,
1026     _PForceVariant,
1027     _PWaitForSync,
1028     _PNameCheck,
1029     ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1030     ("disks", ht.NoDefault,
1031      # TODO: Generate check from constants.IDISK_PARAMS_TYPES
1032      ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
1033                            ht.TOr(ht.TNonEmptyString, ht.TInt))),
1034      "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1035      " each disk definition must contain a ``%s`` value and"
1036      " can contain an optional ``%s`` value denoting the disk access mode"
1037      " (%s)" %
1038      (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1039       constants.IDISK_MODE,
1040       " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1041     ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
1042     ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1043      "Driver for file-backed disks"),
1044     ("file_storage_dir", None, ht.TMaybeString,
1045      "Directory for storing file-backed disks"),
1046     ("hvparams", ht.EmptyDict, ht.TDict,
1047      "Hypervisor parameters for instance, hypervisor-dependent"),
1048     ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1049     ("iallocator", None, ht.TMaybeString,
1050      "Iallocator for deciding which node(s) to use"),
1051     ("identify_defaults", False, ht.TBool,
1052      "Reset instance parameters to default if equal"),
1053     ("ip_check", True, ht.TBool, _PIpCheckDoc),
1054     ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1055      "Instance creation mode"),
1056     ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1057      "List of NIC (network interface) definitions, for example"
1058      " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1059      " contain the optional values %s" %
1060      (constants.INIC_IP,
1061       ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1062     ("no_install", None, ht.TMaybeBool,
1063      "Do not install the OS (will disable automatic start)"),
1064     ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1065     ("os_type", None, ht.TMaybeString, "Operating system"),
1066     ("pnode", None, ht.TMaybeString, "Primary node"),
1067     ("snode", None, ht.TMaybeString, "Secondary node"),
1068     ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1069      "Signed handshake from source (remote import only)"),
1070     ("source_instance_name", None, ht.TMaybeString,
1071      "Source instance name (remote import only)"),
1072     ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1073      ht.TPositiveInt,
1074      "How long source instance was given to shut down (remote import only)"),
1075     ("source_x509_ca", None, ht.TMaybeString,
1076      "Source X509 CA in PEM format (remote import only)"),
1077     ("src_node", None, ht.TMaybeString, "Source node for import"),
1078     ("src_path", None, ht.TMaybeString, "Source directory for import"),
1079     ("start", True, ht.TBool, "Whether to start instance after creation"),
1080     ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1081     ]
1082   OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1083
1084
1085 class OpInstanceReinstall(OpCode):
1086   """Reinstall an instance's OS."""
1087   OP_DSC_FIELD = "instance_name"
1088   OP_PARAMS = [
1089     _PInstanceName,
1090     _PForceVariant,
1091     ("os_type", None, ht.TMaybeString, "Instance operating system"),
1092     ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1093     ]
1094
1095
1096 class OpInstanceRemove(OpCode):
1097   """Remove an instance."""
1098   OP_DSC_FIELD = "instance_name"
1099   OP_PARAMS = [
1100     _PInstanceName,
1101     _PShutdownTimeout,
1102     ("ignore_failures", False, ht.TBool,
1103      "Whether to ignore failures during removal"),
1104     ]
1105
1106
1107 class OpInstanceRename(OpCode):
1108   """Rename an instance."""
1109   OP_PARAMS = [
1110     _PInstanceName,
1111     _PNameCheck,
1112     ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1113     ("ip_check", False, ht.TBool, _PIpCheckDoc),
1114     ]
1115   OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1116
1117
1118 class OpInstanceStartup(OpCode):
1119   """Startup an instance."""
1120   OP_DSC_FIELD = "instance_name"
1121   OP_PARAMS = [
1122     _PInstanceName,
1123     _PForce,
1124     _PIgnoreOfflineNodes,
1125     ("hvparams", ht.EmptyDict, ht.TDict,
1126      "Temporary hypervisor parameters, hypervisor-dependent"),
1127     ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1128     _PNoRemember,
1129     _PStartupPaused,
1130     ]
1131
1132
1133 class OpInstanceShutdown(OpCode):
1134   """Shutdown an instance."""
1135   OP_DSC_FIELD = "instance_name"
1136   OP_PARAMS = [
1137     _PInstanceName,
1138     _PIgnoreOfflineNodes,
1139     ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1140      "How long to wait for instance to shut down"),
1141     _PNoRemember,
1142     ]
1143
1144
1145 class OpInstanceReboot(OpCode):
1146   """Reboot an instance."""
1147   OP_DSC_FIELD = "instance_name"
1148   OP_PARAMS = [
1149     _PInstanceName,
1150     _PShutdownTimeout,
1151     ("ignore_secondaries", False, ht.TBool,
1152      "Whether to start the instance even if secondary disks are failing"),
1153     ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1154      "How to reboot instance"),
1155     ]
1156
1157
1158 class OpInstanceReplaceDisks(OpCode):
1159   """Replace the disks of an instance."""
1160   OP_DSC_FIELD = "instance_name"
1161   OP_PARAMS = [
1162     _PInstanceName,
1163     _PEarlyRelease,
1164     ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1165      "Replacement mode"),
1166     ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1167      "Disk indexes"),
1168     ("remote_node", None, ht.TMaybeString, "New secondary node"),
1169     ("iallocator", None, ht.TMaybeString,
1170      "Iallocator for deciding new secondary node"),
1171     ]
1172
1173
1174 class OpInstanceFailover(OpCode):
1175   """Failover an instance."""
1176   OP_DSC_FIELD = "instance_name"
1177   OP_PARAMS = [
1178     _PInstanceName,
1179     _PShutdownTimeout,
1180     _PIgnoreConsistency,
1181     _PMigrationTargetNode,
1182     ("iallocator", None, ht.TMaybeString,
1183      "Iallocator for deciding the target node for shared-storage instances"),
1184     ]
1185
1186
1187 class OpInstanceMigrate(OpCode):
1188   """Migrate an instance.
1189
1190   This migrates (without shutting down an instance) to its secondary
1191   node.
1192
1193   @ivar instance_name: the name of the instance
1194   @ivar mode: the migration mode (live, non-live or None for auto)
1195
1196   """
1197   OP_DSC_FIELD = "instance_name"
1198   OP_PARAMS = [
1199     _PInstanceName,
1200     _PMigrationMode,
1201     _PMigrationLive,
1202     _PMigrationTargetNode,
1203     ("cleanup", False, ht.TBool,
1204      "Whether a previously failed migration should be cleaned up"),
1205     ("iallocator", None, ht.TMaybeString,
1206      "Iallocator for deciding the target node for shared-storage instances"),
1207     ("allow_failover", False, ht.TBool,
1208      "Whether we can fallback to failover if migration is not possible"),
1209     ]
1210
1211
1212 class OpInstanceMove(OpCode):
1213   """Move an instance.
1214
1215   This move (with shutting down an instance and data copying) to an
1216   arbitrary node.
1217
1218   @ivar instance_name: the name of the instance
1219   @ivar target_node: the destination node
1220
1221   """
1222   OP_DSC_FIELD = "instance_name"
1223   OP_PARAMS = [
1224     _PInstanceName,
1225     _PShutdownTimeout,
1226     ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1227     _PIgnoreConsistency,
1228     ]
1229
1230
1231 class OpInstanceConsole(OpCode):
1232   """Connect to an instance's console."""
1233   OP_DSC_FIELD = "instance_name"
1234   OP_PARAMS = [
1235     _PInstanceName
1236     ]
1237
1238
1239 class OpInstanceActivateDisks(OpCode):
1240   """Activate an instance's disks."""
1241   OP_DSC_FIELD = "instance_name"
1242   OP_PARAMS = [
1243     _PInstanceName,
1244     ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1245     ]
1246
1247
1248 class OpInstanceDeactivateDisks(OpCode):
1249   """Deactivate an instance's disks."""
1250   OP_DSC_FIELD = "instance_name"
1251   OP_PARAMS = [
1252     _PInstanceName,
1253     _PForce,
1254     ]
1255
1256
1257 class OpInstanceRecreateDisks(OpCode):
1258   """Deactivate an instance's disks."""
1259   OP_DSC_FIELD = "instance_name"
1260   OP_PARAMS = [
1261     _PInstanceName,
1262     ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1263      "List of disk indexes"),
1264     ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1265      "New instance nodes, if relocation is desired"),
1266     ]
1267
1268
1269 class OpInstanceQuery(OpCode):
1270   """Compute the list of instances."""
1271   OP_PARAMS = [
1272     _POutputFields,
1273     _PUseLocking,
1274     ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1275      "Empty list to query all instances, instance names otherwise"),
1276     ]
1277
1278
1279 class OpInstanceQueryData(OpCode):
1280   """Compute the run-time status of instances."""
1281   OP_PARAMS = [
1282     _PUseLocking,
1283     ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1284      "Instance names"),
1285     ("static", False, ht.TBool,
1286      "Whether to only return configuration data without querying"
1287      " nodes"),
1288     ]
1289
1290
1291 class OpInstanceSetParams(OpCode):
1292   """Change the parameters of an instance."""
1293   OP_DSC_FIELD = "instance_name"
1294   OP_PARAMS = [
1295     _PInstanceName,
1296     _PForce,
1297     _PForceVariant,
1298     # TODO: Use _TestNicDef
1299     ("nics", ht.EmptyList, ht.TList,
1300      "List of NIC changes. Each item is of the form ``(op, settings)``."
1301      " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1302      " ``%s`` to remove the last NIC or a number to modify the settings"
1303      " of the NIC with that index." %
1304      (constants.DDM_ADD, constants.DDM_REMOVE)),
1305     ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1306     ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1307     ("hvparams", ht.EmptyDict, ht.TDict,
1308      "Per-instance hypervisor parameters, hypervisor-dependent"),
1309     ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1310      "Disk template for instance"),
1311     ("remote_node", None, ht.TMaybeString,
1312      "Secondary node (used when changing disk template)"),
1313     ("os_name", None, ht.TMaybeString,
1314      "Change instance's OS name. Does not reinstall the instance."),
1315     ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1316     ("wait_for_sync", True, ht.TBool,
1317      "Whether to wait for the disk to synchronize, when changing template"),
1318     ]
1319   OP_RESULT = _TSetParamsResult
1320
1321
1322 class OpInstanceGrowDisk(OpCode):
1323   """Grow a disk of an instance."""
1324   OP_DSC_FIELD = "instance_name"
1325   OP_PARAMS = [
1326     _PInstanceName,
1327     _PWaitForSync,
1328     ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1329     ("amount", ht.NoDefault, ht.TInt,
1330      "Amount of disk space to add (megabytes)"),
1331     ]
1332
1333
1334 class OpInstanceChangeGroup(OpCode):
1335   """Moves an instance to another node group."""
1336   OP_DSC_FIELD = "instance_name"
1337   OP_PARAMS = [
1338     _PInstanceName,
1339     _PEarlyRelease,
1340     ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1341     ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1342      "Destination group names or UUIDs (defaults to \"all but current group\""),
1343     ]
1344   OP_RESULT = TJobIdListOnly
1345
1346
1347 # Node group opcodes
1348
1349 class OpGroupAdd(OpCode):
1350   """Add a node group to the cluster."""
1351   OP_DSC_FIELD = "group_name"
1352   OP_PARAMS = [
1353     _PGroupName,
1354     _PNodeGroupAllocPolicy,
1355     _PGroupNodeParams,
1356     ]
1357
1358
1359 class OpGroupAssignNodes(OpCode):
1360   """Assign nodes to a node group."""
1361   OP_DSC_FIELD = "group_name"
1362   OP_PARAMS = [
1363     _PGroupName,
1364     _PForce,
1365     ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1366      "List of nodes to assign"),
1367     ]
1368
1369
1370 class OpGroupQuery(OpCode):
1371   """Compute the list of node groups."""
1372   OP_PARAMS = [
1373     _POutputFields,
1374     ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1375      "Empty list to query all groups, group names otherwise"),
1376     ]
1377
1378
1379 class OpGroupSetParams(OpCode):
1380   """Change the parameters of a node group."""
1381   OP_DSC_FIELD = "group_name"
1382   OP_PARAMS = [
1383     _PGroupName,
1384     _PNodeGroupAllocPolicy,
1385     _PGroupNodeParams,
1386     ]
1387   OP_RESULT = _TSetParamsResult
1388
1389
1390 class OpGroupRemove(OpCode):
1391   """Remove a node group from the cluster."""
1392   OP_DSC_FIELD = "group_name"
1393   OP_PARAMS = [
1394     _PGroupName,
1395     ]
1396
1397
1398 class OpGroupRename(OpCode):
1399   """Rename a node group in the cluster."""
1400   OP_PARAMS = [
1401     _PGroupName,
1402     ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1403     ]
1404   OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1405
1406
1407 class OpGroupEvacuate(OpCode):
1408   """Evacuate a node group in the cluster."""
1409   OP_DSC_FIELD = "group_name"
1410   OP_PARAMS = [
1411     _PGroupName,
1412     _PEarlyRelease,
1413     ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1414     ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1415      "Destination group names or UUIDs"),
1416     ]
1417   OP_RESULT = TJobIdListOnly
1418
1419
1420 # OS opcodes
1421 class OpOsDiagnose(OpCode):
1422   """Compute the list of guest operating systems."""
1423   OP_PARAMS = [
1424     _POutputFields,
1425     ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1426      "Which operating systems to diagnose"),
1427     ]
1428
1429
1430 # Exports opcodes
1431 class OpBackupQuery(OpCode):
1432   """Compute the list of exported images."""
1433   OP_PARAMS = [
1434     _PUseLocking,
1435     ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1436      "Empty list to query all nodes, node names otherwise"),
1437     ]
1438
1439
1440 class OpBackupPrepare(OpCode):
1441   """Prepares an instance export.
1442
1443   @ivar instance_name: Instance name
1444   @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1445
1446   """
1447   OP_DSC_FIELD = "instance_name"
1448   OP_PARAMS = [
1449     _PInstanceName,
1450     ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1451      "Export mode"),
1452     ]
1453
1454
1455 class OpBackupExport(OpCode):
1456   """Export an instance.
1457
1458   For local exports, the export destination is the node name. For remote
1459   exports, the export destination is a list of tuples, each consisting of
1460   hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1461   the cluster domain secret over the value "${index}:${hostname}:${port}". The
1462   destination X509 CA must be a signed certificate.
1463
1464   @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1465   @ivar target_node: Export destination
1466   @ivar x509_key_name: X509 key to use (remote export only)
1467   @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1468                              only)
1469
1470   """
1471   OP_DSC_FIELD = "instance_name"
1472   OP_PARAMS = [
1473     _PInstanceName,
1474     _PShutdownTimeout,
1475     # TODO: Rename target_node as it changes meaning for different export modes
1476     # (e.g. "destination")
1477     ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1478      "Destination information, depends on export mode"),
1479     ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1480     ("remove_instance", False, ht.TBool,
1481      "Whether to remove instance after export"),
1482     ("ignore_remove_failures", False, ht.TBool,
1483      "Whether to ignore failures while removing instances"),
1484     ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1485      "Export mode"),
1486     ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1487      "Name of X509 key (remote export only)"),
1488     ("destination_x509_ca", None, ht.TMaybeString,
1489      "Destination X509 CA (remote export only)"),
1490     ]
1491
1492
1493 class OpBackupRemove(OpCode):
1494   """Remove an instance's export."""
1495   OP_DSC_FIELD = "instance_name"
1496   OP_PARAMS = [
1497     _PInstanceName,
1498     ]
1499
1500
1501 # Tags opcodes
1502 class OpTagsGet(OpCode):
1503   """Returns the tags of the given object."""
1504   OP_DSC_FIELD = "name"
1505   OP_PARAMS = [
1506     _PTagKind,
1507     # Name is only meaningful for nodes and instances
1508     ("name", ht.NoDefault, ht.TMaybeString, None),
1509     ]
1510
1511
1512 class OpTagsSearch(OpCode):
1513   """Searches the tags in the cluster for a given pattern."""
1514   OP_DSC_FIELD = "pattern"
1515   OP_PARAMS = [
1516     ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1517     ]
1518
1519
1520 class OpTagsSet(OpCode):
1521   """Add a list of tags on a given object."""
1522   OP_PARAMS = [
1523     _PTagKind,
1524     _PTags,
1525     # Name is only meaningful for nodes and instances
1526     ("name", ht.NoDefault, ht.TMaybeString, None),
1527     ]
1528
1529
1530 class OpTagsDel(OpCode):
1531   """Remove a list of tags from a given object."""
1532   OP_PARAMS = [
1533     _PTagKind,
1534     _PTags,
1535     # Name is only meaningful for nodes and instances
1536     ("name", ht.NoDefault, ht.TMaybeString, None),
1537     ]
1538
1539
1540 # Test opcodes
1541 class OpTestDelay(OpCode):
1542   """Sleeps for a configured amount of time.
1543
1544   This is used just for debugging and testing.
1545
1546   Parameters:
1547     - duration: the time to sleep
1548     - on_master: if true, sleep on the master
1549     - on_nodes: list of nodes in which to sleep
1550
1551   If the on_master parameter is true, it will execute a sleep on the
1552   master (before any node sleep).
1553
1554   If the on_nodes list is not empty, it will sleep on those nodes
1555   (after the sleep on the master, if that is enabled).
1556
1557   As an additional feature, the case of duration < 0 will be reported
1558   as an execution error, so this opcode can be used as a failure
1559   generator. The case of duration == 0 will not be treated specially.
1560
1561   """
1562   OP_DSC_FIELD = "duration"
1563   OP_PARAMS = [
1564     ("duration", ht.NoDefault, ht.TNumber, None),
1565     ("on_master", True, ht.TBool, None),
1566     ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1567     ("repeat", 0, ht.TPositiveInt, None),
1568     ]
1569
1570
1571 class OpTestAllocator(OpCode):
1572   """Allocator framework testing.
1573
1574   This opcode has two modes:
1575     - gather and return allocator input for a given mode (allocate new
1576       or replace secondary) and a given instance definition (direction
1577       'in')
1578     - run a selected allocator for a given operation (as above) and
1579       return the allocator output (direction 'out')
1580
1581   """
1582   OP_DSC_FIELD = "allocator"
1583   OP_PARAMS = [
1584     ("direction", ht.NoDefault,
1585      ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1586     ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1587     ("name", ht.NoDefault, ht.TNonEmptyString, None),
1588     ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1589      ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1590                 ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1591     ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1592     ("hypervisor", None, ht.TMaybeString, None),
1593     ("allocator", None, ht.TMaybeString, None),
1594     ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1595     ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1596     ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1597     ("os", None, ht.TMaybeString, None),
1598     ("disk_template", None, ht.TMaybeString, None),
1599     ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1600      None),
1601     ("evac_mode", None,
1602      ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1603     ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1604      None),
1605     ]
1606
1607
1608 class OpTestJqueue(OpCode):
1609   """Utility opcode to test some aspects of the job queue.
1610
1611   """
1612   OP_PARAMS = [
1613     ("notify_waitlock", False, ht.TBool, None),
1614     ("notify_exec", False, ht.TBool, None),
1615     ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1616     ("fail", False, ht.TBool, None),
1617     ]
1618
1619
1620 class OpTestDummy(OpCode):
1621   """Utility opcode used by unittests.
1622
1623   """
1624   OP_PARAMS = [
1625     ("result", ht.NoDefault, ht.NoType, None),
1626     ("messages", ht.NoDefault, ht.NoType, None),
1627     ("fail", ht.NoDefault, ht.NoType, None),
1628     ("submit_jobs", None, ht.NoType, None),
1629     ]
1630   WITH_LU = False
1631
1632
1633 def _GetOpList():
1634   """Returns list of all defined opcodes.
1635
1636   Does not eliminate duplicates by C{OP_ID}.
1637
1638   """
1639   return [v for v in globals().values()
1640           if (isinstance(v, type) and issubclass(v, OpCode) and
1641               hasattr(v, "OP_ID") and v is not OpCode)]
1642
1643
1644 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())