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