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