4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
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.
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.
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
24 This module implements the data structures which define the cluster
25 operations - the so-called opcodes.
27 Every operation which modifies the cluster state is expressed via
32 # this are practically structures, so disable the message about too
34 # pylint: disable=R0903
39 from ganeti import compat
40 from ganeti import constants
41 from ganeti import errors
45 # Common opcode attributes
47 #: output fields for a query operation
48 _POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
49 "Selected output fields")
51 #: the shutdown timeout
53 ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
54 "How long to wait for instance to shut down")
56 #: the force parameter
57 _PForce = ("force", False, ht.TBool, "Whether to force the operation")
59 #: a required instance name (for single-instance LUs)
60 _PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString,
63 #: Whether to ignore offline nodes
64 _PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
65 "Whether to ignore offline nodes")
67 #: a required node name (for single-node LUs)
68 _PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
70 #: a required node group name (for single-group LUs)
71 _PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
73 #: Migration type (live/non-live)
74 _PMigrationMode = ("mode", None,
75 ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)),
78 #: Obsolete 'live' migration mode (boolean)
79 _PMigrationLive = ("live", None, ht.TMaybeBool,
80 "Legacy setting for live migration, do not use")
83 _PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
85 #: List of tag strings
86 _PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
88 _PForceVariant = ("force_variant", False, ht.TBool,
89 "Whether to force an unknown OS variant")
91 _PWaitForSync = ("wait_for_sync", True, ht.TBool,
92 "Whether to wait for the disk to synchronize")
94 _PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
95 "Whether to ignore disk consistency")
97 _PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
99 _PUseLocking = ("use_locking", False, ht.TBool,
100 "Whether to use synchronization")
102 _PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
104 _PNodeGroupAllocPolicy = \
105 ("alloc_policy", None,
106 ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
107 "Instance allocation policy")
109 _PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
110 "Default node parameters for group")
112 _PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
113 "Resource(s) to query for")
115 _PEarlyRelease = ("early_release", False, ht.TBool,
116 "Whether to release locks as soon as possible")
118 _PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
120 #: Do not remember instance state changes
121 _PNoRemember = ("no_remember", False, ht.TBool,
122 "Do not remember the state change")
124 #: Target node for instance migration/failover
125 _PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
126 "Target node for shared-storage instances")
128 _PStartupPaused = ("startup_paused", False, ht.TBool,
129 "Pause instance at startup")
131 _PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
133 # Parameters for cluster verification
134 _PDebugSimulateErrors = ("debug_simulate_errors", False, ht.TBool,
135 "Whether to simulate errors (useful for debugging)")
136 _PErrorCodes = ("error_codes", False, ht.TBool, "Error codes")
137 _PSkipChecks = ("skip_checks", ht.EmptyList,
138 ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)),
139 "Which checks to skip")
140 _PIgnoreErrors = ("ignore_errors", ht.EmptyList,
141 ht.TListOf(ht.TElemOf(constants.CV_ALL_ECODES_STRINGS)),
142 "List of error codes that should be treated as warnings")
145 _PDiskParams = ("diskparams", None,
147 ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict),
149 "Disk templates' parameter defaults")
151 # Parameters for node resource model
152 _PHvState = ("hv_state", None, ht.TMaybeDict, "Set hypervisor states")
153 _PDiskState = ("disk_state", None, ht.TMaybeDict, "Set disk states")
155 #: OP_ID conversion regular expression
156 _OPID_RE = re.compile("([a-z])([A-Z])")
158 #: Utility function for L{OpClusterSetParams}
159 _TestClusterOsList = ht.TOr(ht.TNone,
160 ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
161 ht.TMap(ht.WithDesc("GetFirstItem")(compat.fst),
162 ht.TElemOf(constants.DDMS_VALUES)))))
165 # TODO: Generate check from constants.INIC_PARAMS_TYPES
166 #: Utility function for testing NIC definitions
167 _TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
168 ht.TOr(ht.TNone, ht.TNonEmptyString))
170 _TSetParamsResultItemItems = [
171 ht.Comment("name of changed parameter")(ht.TNonEmptyString),
172 ht.Comment("new value")(ht.TAny),
175 _TSetParamsResult = \
176 ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
177 ht.TItems(_TSetParamsResultItemItems)))
186 #: Attribute name for dependencies
187 DEPEND_ATTR = "depends"
189 #: Attribute name for comment
190 COMMENT_ATTR = "comment"
194 """Convert an opcode class name to an OP_ID.
197 @param name: the class name, as OpXxxYyy
199 @return: the name in the OP_XXXX_YYYY format
202 if not name.startswith("Op"):
204 # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
205 # consume any input, and hence we would just have all the elements
206 # in the list, one by one; but it seems that split doesn't work on
207 # non-consuming input, hence we have to process the input string a
209 name = _OPID_RE.sub(r"\1,\2", name)
210 elems = name.split(",")
211 return "_".join(n.upper() for n in elems)
214 def RequireFileStorage():
215 """Checks that file storage is enabled.
217 While it doesn't really fit into this module, L{utils} was deemed too large
218 of a dependency to be imported for just one or two functions.
220 @raise errors.OpPrereqError: when file storage is disabled
223 if not constants.ENABLE_FILE_STORAGE:
224 raise errors.OpPrereqError("File storage disabled at configure time",
228 def RequireSharedFileStorage():
229 """Checks that shared file storage is enabled.
231 While it doesn't really fit into this module, L{utils} was deemed too large
232 of a dependency to be imported for just one or two functions.
234 @raise errors.OpPrereqError: when shared file storage is disabled
237 if not constants.ENABLE_SHARED_FILE_STORAGE:
238 raise errors.OpPrereqError("Shared file storage disabled at"
239 " configure time", errors.ECODE_INVAL)
242 @ht.WithDesc("CheckFileStorage")
243 def _CheckFileStorage(value):
244 """Ensures file storage is enabled if used.
247 if value == constants.DT_FILE:
249 elif value == constants.DT_SHARED_FILE:
250 RequireSharedFileStorage()
254 def _BuildDiskTemplateCheck(accept_none):
255 """Builds check for disk template.
257 @type accept_none: bool
258 @param accept_none: whether to accept None as a correct value
262 template_check = ht.TElemOf(constants.DISK_TEMPLATES)
265 template_check = ht.TOr(template_check, ht.TNone)
267 return ht.TAnd(template_check, _CheckFileStorage)
270 def _CheckStorageType(storage_type):
271 """Ensure a given storage type is valid.
274 if storage_type not in constants.VALID_STORAGE_TYPES:
275 raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
277 if storage_type == constants.ST_FILE:
282 #: Storage type parameter
283 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
287 class _AutoOpParamSlots(type):
288 """Meta class for opcode definitions.
291 def __new__(mcs, name, bases, attrs):
292 """Called when a class should be created.
294 @param mcs: The meta class
295 @param name: Name of created class
296 @param bases: Base classes
298 @param attrs: Class attributes
301 assert "__slots__" not in attrs, \
302 "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
303 assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
305 attrs["OP_ID"] = _NameToId(name)
307 # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
308 params = attrs.setdefault("OP_PARAMS", [])
310 # Use parameter names as slots
311 slots = [pname for (pname, _, _, _) in params]
313 assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
314 "Class '%s' uses unknown field in OP_DSC_FIELD" % name
316 attrs["__slots__"] = slots
318 return type.__new__(mcs, name, bases, attrs)
321 class BaseOpCode(object):
322 """A simple serializable object.
324 This object serves as a parent class for OpCode without any custom
328 # pylint: disable=E1101
329 # as OP_ID is dynamically defined
330 __metaclass__ = _AutoOpParamSlots
332 def __init__(self, **kwargs):
333 """Constructor for BaseOpCode.
335 The constructor takes only keyword arguments and will set
336 attributes on this object based on the passed arguments. As such,
337 it means that you should not pass arguments which are not in the
338 __slots__ attribute for this class.
341 slots = self._all_slots()
344 raise TypeError("Object %s doesn't support the parameter '%s'" %
345 (self.__class__.__name__, key))
346 setattr(self, key, kwargs[key])
348 def __getstate__(self):
349 """Generic serializer.
351 This method just returns the contents of the instance as a
355 @return: the instance attributes and their values
359 for name in self._all_slots():
360 if hasattr(self, name):
361 state[name] = getattr(self, name)
364 def __setstate__(self, state):
365 """Generic unserializer.
367 This method just restores from the serialized state the attributes
368 of the current instance.
370 @param state: the serialized opcode data
374 if not isinstance(state, dict):
375 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
378 for name in self._all_slots():
379 if name not in state and hasattr(self, name):
383 setattr(self, name, state[name])
387 """Compute the list of all declared slots for a class.
391 for parent in cls.__mro__:
392 slots.extend(getattr(parent, "__slots__", []))
396 def GetAllParams(cls):
397 """Compute list of all parameters for an opcode.
401 for parent in cls.__mro__:
402 slots.extend(getattr(parent, "OP_PARAMS", []))
405 def Validate(self, set_defaults):
406 """Validate opcode parameters, optionally setting default values.
408 @type set_defaults: bool
409 @param set_defaults: Whether to set default values
410 @raise errors.OpPrereqError: When a parameter value doesn't match
414 for (attr_name, default, test, _) in self.GetAllParams():
415 assert test == ht.NoType or callable(test)
417 if not hasattr(self, attr_name):
418 if default == ht.NoDefault:
419 raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
420 (self.OP_ID, attr_name),
423 if callable(default):
427 setattr(self, attr_name, dval)
429 if test == ht.NoType:
433 if set_defaults or hasattr(self, attr_name):
434 attr_val = getattr(self, attr_name)
435 if not test(attr_val):
436 logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
437 self.OP_ID, attr_name, type(attr_val), attr_val)
438 raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
439 (self.OP_ID, attr_name),
443 def _BuildJobDepCheck(relative):
444 """Builds check for job dependencies (L{DEPEND_ATTR}).
447 @param relative: Whether to accept relative job IDs (negative)
452 job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
457 ht.TAnd(ht.TIsLength(2),
459 ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
461 return ht.TOr(ht.TNone, ht.TListOf(job_dep))
464 TNoRelativeJobDependencies = _BuildJobDepCheck(False)
466 #: List of submission status and job ID as returned by C{SubmitManyJobs}
468 ht.TAnd(ht.TIsLength(2),
469 ht.TItems([ht.Comment("success")(ht.TBool),
470 ht.Comment("Job ID if successful, error message"
471 " otherwise")(ht.TOr(ht.TString,
473 TJobIdList = ht.TListOf(_TJobIdListItem)
475 #: Result containing only list of submitted jobs
476 TJobIdListOnly = ht.TStrictDict(True, True, {
477 constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
481 class OpCode(BaseOpCode):
484 This is the root of the actual OpCode hierarchy. All clases derived
485 from this class should override OP_ID.
487 @cvar OP_ID: The ID of this opcode. This should be unique amongst all
488 children of this class.
489 @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
490 string returned by Summary(); see the docstring of that
492 @cvar OP_PARAMS: List of opcode attributes, the default values they should
493 get if not already defined, and types they must match.
494 @cvar OP_RESULT: Callable to verify opcode result
495 @cvar WITH_LU: Boolean that specifies whether this should be included in
496 mcpu's dispatch table
497 @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
499 @ivar priority: Opcode priority for queue
502 # pylint: disable=E1101
503 # as OP_ID is dynamically defined
506 ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
507 ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
508 ("priority", constants.OP_PRIO_DEFAULT,
509 ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
510 (DEPEND_ATTR, None, _BuildJobDepCheck(True),
511 "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
512 " job IDs can be used"),
513 (COMMENT_ATTR, None, ht.TMaybeString,
514 "Comment describing the purpose of the opcode"),
518 def __getstate__(self):
519 """Specialized getstate for opcodes.
521 This method adds to the state dictionary the OP_ID of the class,
522 so that on unload we can identify the correct class for
523 instantiating the opcode.
526 @return: the state as a dictionary
529 data = BaseOpCode.__getstate__(self)
530 data["OP_ID"] = self.OP_ID
534 def LoadOpCode(cls, data):
535 """Generic load opcode method.
537 The method identifies the correct opcode class from the dict-form
538 by looking for a OP_ID key, if this is not found, or its value is
539 not available in this module as a child of this class, we fail.
542 @param data: the serialized opcode
545 if not isinstance(data, dict):
546 raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
547 if "OP_ID" not in data:
548 raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
549 op_id = data["OP_ID"]
551 if op_id in OP_MAPPING:
552 op_class = OP_MAPPING[op_id]
554 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
557 new_data = data.copy()
558 del new_data["OP_ID"]
559 op.__setstate__(new_data)
563 """Generates a summary description of this opcode.
565 The summary is the value of the OP_ID attribute (without the "OP_"
566 prefix), plus the value of the OP_DSC_FIELD attribute, if one was
567 defined; this field should allow to easily identify the operation
568 (for an instance creation job, e.g., it would be the instance
572 assert self.OP_ID is not None and len(self.OP_ID) > 3
573 # all OP_ID start with OP_, we remove that
575 field_name = getattr(self, "OP_DSC_FIELD", None)
577 field_value = getattr(self, field_name, None)
578 if isinstance(field_value, (list, tuple)):
579 field_value = ",".join(str(i) for i in field_value)
580 txt = "%s(%s)" % (txt, field_value)
583 def TinySummary(self):
584 """Generates a compact summary description of the opcode.
587 assert self.OP_ID.startswith("OP_")
589 text = self.OP_ID[3:]
591 for (prefix, supplement) in _SUMMARY_PREFIX.items():
592 if text.startswith(prefix):
593 return supplement + text[len(prefix):]
600 class OpClusterPostInit(OpCode):
601 """Post cluster initialization.
603 This opcode does not touch the cluster at all. Its purpose is to run hooks
604 after the cluster has been initialized.
609 class OpClusterDestroy(OpCode):
610 """Destroy the cluster.
612 This opcode has no other parameters. All the state is irreversibly
613 lost after the execution of this opcode.
618 class OpClusterQuery(OpCode):
619 """Query cluster information."""
622 class OpClusterVerify(OpCode):
623 """Submits all jobs necessary to verify the cluster.
627 _PDebugSimulateErrors,
632 ("group_name", None, ht.TMaybeString, "Group to verify")
634 OP_RESULT = TJobIdListOnly
637 class OpClusterVerifyConfig(OpCode):
638 """Verify the cluster config.
642 _PDebugSimulateErrors,
650 class OpClusterVerifyGroup(OpCode):
651 """Run verify on a node group from the cluster.
653 @type skip_checks: C{list}
654 @ivar skip_checks: steps to be skipped from the verify process; this
655 needs to be a subset of
656 L{constants.VERIFY_OPTIONAL_CHECKS}; currently
657 only L{constants.VERIFY_NPLUSONE_MEM} can be passed
660 OP_DSC_FIELD = "group_name"
663 _PDebugSimulateErrors,
672 class OpClusterVerifyDisks(OpCode):
673 """Verify the cluster disks.
676 OP_RESULT = TJobIdListOnly
679 class OpGroupVerifyDisks(OpCode):
680 """Verifies the status of all disks in a node group.
682 Result: a tuple of three elements:
683 - dict of node names with issues (values: error msg)
684 - list of instances with degraded disks (that should be activated)
685 - dict of instances with missing logical volumes (values: (node, vol)
686 pairs with details about the missing volumes)
688 In normal operation, all lists should be empty. A non-empty instance
689 list (3rd element of the result) is still ok (errors were fixed) but
690 non-empty node list means some node is down, and probably there are
691 unfixable drbd errors.
693 Note that only instances that are drbd-based are taken into
694 consideration. This might need to be revisited in the future.
697 OP_DSC_FIELD = "group_name"
702 ht.TAnd(ht.TIsLength(3),
703 ht.TItems([ht.TDictOf(ht.TString, ht.TString),
704 ht.TListOf(ht.TString),
705 ht.TDictOf(ht.TString,
706 ht.TListOf(ht.TListOf(ht.TString)))]))
709 class OpClusterRepairDiskSizes(OpCode):
710 """Verify the disk sizes of the instances and fixes configuration
713 Parameters: optional instances list, in case we want to restrict the
714 checks to only a subset of the instances.
716 Result: a list of tuples, (instance, disk, new-size) for changed
719 In normal operation, the list should be empty.
721 @type instances: list
722 @ivar instances: the list of instances to check, or empty for all instances
726 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
730 class OpClusterConfigQuery(OpCode):
731 """Query cluster configuration values."""
737 class OpClusterRename(OpCode):
738 """Rename the cluster.
741 @ivar name: The new name of the cluster. The name and/or the master IP
742 address will be changed to match the new name and its IP
746 OP_DSC_FIELD = "name"
748 ("name", ht.NoDefault, ht.TNonEmptyString, None),
752 class OpClusterSetParams(OpCode):
753 """Change the parameters of the cluster.
755 @type vg_name: C{str} or C{None}
756 @ivar vg_name: The new volume group name or None to disable LVM usage.
762 ("vg_name", None, ht.TMaybeString, "Volume group name"),
763 ("enabled_hypervisors", None,
764 ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
766 "List of enabled hypervisors"),
767 ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
769 "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
770 ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
771 "Cluster-wide backend parameter defaults"),
772 ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
774 "Cluster-wide per-OS hypervisor parameter defaults"),
775 ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
777 "Cluster-wide OS parameter defaults"),
779 ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
780 "Master candidate pool size"),
781 ("uid_pool", None, ht.NoType,
782 "Set UID pool, must be list of lists describing UID ranges (two items,"
783 " start and end inclusive)"),
784 ("add_uids", None, ht.NoType,
785 "Extend UID pool, must be list of lists describing UID ranges (two"
786 " items, start and end inclusive) to be added"),
787 ("remove_uids", None, ht.NoType,
788 "Shrink UID pool, must be list of lists describing UID ranges (two"
789 " items, start and end inclusive) to be removed"),
790 ("maintain_node_health", None, ht.TMaybeBool,
791 "Whether to automatically maintain node health"),
792 ("prealloc_wipe_disks", None, ht.TMaybeBool,
793 "Whether to wipe disks before allocating them to instances"),
794 ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
795 ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
796 ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
797 ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
798 "Default iallocator for cluster"),
799 ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
800 "Master network device"),
801 ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
802 "Netmask of the master IP"),
803 ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
804 "List of reserved LVs"),
805 ("hidden_os", None, _TestClusterOsList,
806 "Modify list of hidden operating systems. Each modification must have"
807 " two items, the operation and the OS name. The operation can be"
808 " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
809 ("blacklisted_os", None, _TestClusterOsList,
810 "Modify list of blacklisted operating systems. Each modification must have"
811 " two items, the operation and the OS name. The operation can be"
812 " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
813 ("use_external_mip_script", None, ht.TMaybeBool,
814 "Whether to use an external master IP address setup script"),
818 class OpClusterRedistConf(OpCode):
819 """Force a full push of the cluster configuration.
824 class OpClusterActivateMasterIp(OpCode):
825 """Activate the master IP on the master node.
830 class OpClusterDeactivateMasterIp(OpCode):
831 """Deactivate the master IP on the master node.
836 class OpQuery(OpCode):
837 """Query for resources/items.
839 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
840 @ivar fields: List of fields to retrieve
841 @ivar qfilter: Query filter
844 OP_DSC_FIELD = "what"
848 ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
850 ("qfilter", None, ht.TOr(ht.TNone, ht.TListOf),
855 class OpQueryFields(OpCode):
856 """Query for available resource/item fields.
858 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
859 @ivar fields: List of fields to retrieve
862 OP_DSC_FIELD = "what"
865 ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
866 "Requested fields; if not given, all are returned"),
870 class OpOobCommand(OpCode):
871 """Interact with OOB."""
873 ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
874 "List of nodes to run the OOB command against"),
875 ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
876 "OOB command to be run"),
877 ("timeout", constants.OOB_TIMEOUT, ht.TInt,
878 "Timeout before the OOB helper will be terminated"),
879 ("ignore_status", False, ht.TBool,
880 "Ignores the node offline status for power off"),
881 ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
882 "Time in seconds to wait between powering on nodes"),
888 class OpNodeRemove(OpCode):
891 @type node_name: C{str}
892 @ivar node_name: The name of the node to remove. If the node still has
893 instances on it, the operation will fail.
896 OP_DSC_FIELD = "node_name"
902 class OpNodeAdd(OpCode):
903 """Add a node to the cluster.
905 @type node_name: C{str}
906 @ivar node_name: The name of the node to add. This can be a short name,
907 but it will be expanded to the FQDN.
908 @type primary_ip: IP address
909 @ivar primary_ip: The primary IP of the node. This will be ignored when the
910 opcode is submitted, but will be filled during the node
911 add (so it will be visible in the job query).
912 @type secondary_ip: IP address
913 @ivar secondary_ip: The secondary IP of the node. This needs to be passed
914 if the cluster has been initialized in 'dual-network'
915 mode, otherwise it must not be given.
917 @ivar readd: Whether to re-add an existing node to the cluster. If
918 this is not passed, then the operation will abort if the node
919 name is already in the cluster; use this parameter to 'repair'
920 a node that had its configuration broken, or was reinstalled
921 without removal from the cluster.
923 @ivar group: The node group to which this node will belong.
924 @type vm_capable: C{bool}
925 @ivar vm_capable: The vm_capable node attribute
926 @type master_capable: C{bool}
927 @ivar master_capable: The master_capable node attribute
930 OP_DSC_FIELD = "node_name"
933 ("primary_ip", None, ht.NoType, "Primary IP address"),
934 ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
935 ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
936 ("group", None, ht.TMaybeString, "Initial node group"),
937 ("master_capable", None, ht.TMaybeBool,
938 "Whether node can become master or master candidate"),
939 ("vm_capable", None, ht.TMaybeBool,
940 "Whether node can host instances"),
941 ("ndparams", None, ht.TMaybeDict, "Node parameters"),
945 class OpNodeQuery(OpCode):
946 """Compute the list of nodes."""
950 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
951 "Empty list to query all nodes, node names otherwise"),
955 class OpNodeQueryvols(OpCode):
956 """Get list of volumes on node."""
959 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
960 "Empty list to query all nodes, node names otherwise"),
964 class OpNodeQueryStorage(OpCode):
965 """Get information on storage for node(s)."""
969 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
970 ("name", None, ht.TMaybeString, "Storage name"),
974 class OpNodeModifyStorage(OpCode):
975 """Modifies the properies of a storage unit"""
980 ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
984 class OpRepairNodeStorage(OpCode):
985 """Repairs the volume group on a node."""
986 OP_DSC_FIELD = "node_name"
995 class OpNodeSetParams(OpCode):
996 """Change the parameters of a node."""
997 OP_DSC_FIELD = "node_name"
1003 ("master_candidate", None, ht.TMaybeBool,
1004 "Whether the node should become a master candidate"),
1005 ("offline", None, ht.TMaybeBool,
1006 "Whether the node should be marked as offline"),
1007 ("drained", None, ht.TMaybeBool,
1008 "Whether the node should be marked as drained"),
1009 ("auto_promote", False, ht.TBool,
1010 "Whether node(s) should be promoted to master candidate if necessary"),
1011 ("master_capable", None, ht.TMaybeBool,
1012 "Denote whether node can become master or master candidate"),
1013 ("vm_capable", None, ht.TMaybeBool,
1014 "Denote whether node can host instances"),
1015 ("secondary_ip", None, ht.TMaybeString,
1016 "Change node's secondary IP address"),
1017 ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1018 ("powered", None, ht.TMaybeBool,
1019 "Whether the node should be marked as powered"),
1021 OP_RESULT = _TSetParamsResult
1024 class OpNodePowercycle(OpCode):
1025 """Tries to powercycle a node."""
1026 OP_DSC_FIELD = "node_name"
1033 class OpNodeMigrate(OpCode):
1034 """Migrate all instances from a node."""
1035 OP_DSC_FIELD = "node_name"
1040 _PMigrationTargetNode,
1041 ("iallocator", None, ht.TMaybeString,
1042 "Iallocator for deciding the target node for shared-storage instances"),
1044 OP_RESULT = TJobIdListOnly
1047 class OpNodeEvacuate(OpCode):
1048 """Evacuate instances off a number of nodes."""
1049 OP_DSC_FIELD = "node_name"
1053 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1054 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1055 ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1056 "Node evacuation mode"),
1058 OP_RESULT = TJobIdListOnly
1063 class OpInstanceCreate(OpCode):
1064 """Create an instance.
1066 @ivar instance_name: Instance name
1067 @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1068 @ivar source_handshake: Signed handshake from source (remote import only)
1069 @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1070 @ivar source_instance_name: Previous name of instance (remote import only)
1071 @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1072 (remote import only)
1075 OP_DSC_FIELD = "instance_name"
1081 ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1082 ("disks", ht.NoDefault,
1083 # TODO: Generate check from constants.IDISK_PARAMS_TYPES
1084 ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
1085 ht.TOr(ht.TNonEmptyString, ht.TInt))),
1086 "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1087 " each disk definition must contain a ``%s`` value and"
1088 " can contain an optional ``%s`` value denoting the disk access mode"
1090 (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1091 constants.IDISK_MODE,
1092 " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1093 ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1095 ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1096 "Driver for file-backed disks"),
1097 ("file_storage_dir", None, ht.TMaybeString,
1098 "Directory for storing file-backed disks"),
1099 ("hvparams", ht.EmptyDict, ht.TDict,
1100 "Hypervisor parameters for instance, hypervisor-dependent"),
1101 ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1102 ("iallocator", None, ht.TMaybeString,
1103 "Iallocator for deciding which node(s) to use"),
1104 ("identify_defaults", False, ht.TBool,
1105 "Reset instance parameters to default if equal"),
1106 ("ip_check", True, ht.TBool, _PIpCheckDoc),
1107 ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1108 "Instance creation mode"),
1109 ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1110 "List of NIC (network interface) definitions, for example"
1111 " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1112 " contain the optional values %s" %
1114 ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1115 ("no_install", None, ht.TMaybeBool,
1116 "Do not install the OS (will disable automatic start)"),
1117 ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1118 ("os_type", None, ht.TMaybeString, "Operating system"),
1119 ("pnode", None, ht.TMaybeString, "Primary node"),
1120 ("snode", None, ht.TMaybeString, "Secondary node"),
1121 ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1122 "Signed handshake from source (remote import only)"),
1123 ("source_instance_name", None, ht.TMaybeString,
1124 "Source instance name (remote import only)"),
1125 ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1127 "How long source instance was given to shut down (remote import only)"),
1128 ("source_x509_ca", None, ht.TMaybeString,
1129 "Source X509 CA in PEM format (remote import only)"),
1130 ("src_node", None, ht.TMaybeString, "Source node for import"),
1131 ("src_path", None, ht.TMaybeString, "Source directory for import"),
1132 ("start", True, ht.TBool, "Whether to start instance after creation"),
1133 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1135 OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1138 class OpInstanceReinstall(OpCode):
1139 """Reinstall an instance's OS."""
1140 OP_DSC_FIELD = "instance_name"
1144 ("os_type", None, ht.TMaybeString, "Instance operating system"),
1145 ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1149 class OpInstanceRemove(OpCode):
1150 """Remove an instance."""
1151 OP_DSC_FIELD = "instance_name"
1155 ("ignore_failures", False, ht.TBool,
1156 "Whether to ignore failures during removal"),
1160 class OpInstanceRename(OpCode):
1161 """Rename an instance."""
1165 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1166 ("ip_check", False, ht.TBool, _PIpCheckDoc),
1168 OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1171 class OpInstanceStartup(OpCode):
1172 """Startup an instance."""
1173 OP_DSC_FIELD = "instance_name"
1177 _PIgnoreOfflineNodes,
1178 ("hvparams", ht.EmptyDict, ht.TDict,
1179 "Temporary hypervisor parameters, hypervisor-dependent"),
1180 ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1186 class OpInstanceShutdown(OpCode):
1187 """Shutdown an instance."""
1188 OP_DSC_FIELD = "instance_name"
1191 _PIgnoreOfflineNodes,
1192 ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1193 "How long to wait for instance to shut down"),
1198 class OpInstanceReboot(OpCode):
1199 """Reboot an instance."""
1200 OP_DSC_FIELD = "instance_name"
1204 ("ignore_secondaries", False, ht.TBool,
1205 "Whether to start the instance even if secondary disks are failing"),
1206 ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1207 "How to reboot instance"),
1211 class OpInstanceReplaceDisks(OpCode):
1212 """Replace the disks of an instance."""
1213 OP_DSC_FIELD = "instance_name"
1217 ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1218 "Replacement mode"),
1219 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1221 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1222 ("iallocator", None, ht.TMaybeString,
1223 "Iallocator for deciding new secondary node"),
1227 class OpInstanceFailover(OpCode):
1228 """Failover an instance."""
1229 OP_DSC_FIELD = "instance_name"
1233 _PIgnoreConsistency,
1234 _PMigrationTargetNode,
1235 ("iallocator", None, ht.TMaybeString,
1236 "Iallocator for deciding the target node for shared-storage instances"),
1240 class OpInstanceMigrate(OpCode):
1241 """Migrate an instance.
1243 This migrates (without shutting down an instance) to its secondary
1246 @ivar instance_name: the name of the instance
1247 @ivar mode: the migration mode (live, non-live or None for auto)
1250 OP_DSC_FIELD = "instance_name"
1255 _PMigrationTargetNode,
1256 ("cleanup", False, ht.TBool,
1257 "Whether a previously failed migration should be cleaned up"),
1258 ("iallocator", None, ht.TMaybeString,
1259 "Iallocator for deciding the target node for shared-storage instances"),
1260 ("allow_failover", False, ht.TBool,
1261 "Whether we can fallback to failover if migration is not possible"),
1265 class OpInstanceMove(OpCode):
1266 """Move an instance.
1268 This move (with shutting down an instance and data copying) to an
1271 @ivar instance_name: the name of the instance
1272 @ivar target_node: the destination node
1275 OP_DSC_FIELD = "instance_name"
1279 ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1280 _PIgnoreConsistency,
1284 class OpInstanceConsole(OpCode):
1285 """Connect to an instance's console."""
1286 OP_DSC_FIELD = "instance_name"
1292 class OpInstanceActivateDisks(OpCode):
1293 """Activate an instance's disks."""
1294 OP_DSC_FIELD = "instance_name"
1297 ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1301 class OpInstanceDeactivateDisks(OpCode):
1302 """Deactivate an instance's disks."""
1303 OP_DSC_FIELD = "instance_name"
1310 class OpInstanceRecreateDisks(OpCode):
1311 """Recreate an instance's disks."""
1312 OP_DSC_FIELD = "instance_name"
1315 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1316 "List of disk indexes"),
1317 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1318 "New instance nodes, if relocation is desired"),
1322 class OpInstanceQuery(OpCode):
1323 """Compute the list of instances."""
1327 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1328 "Empty list to query all instances, instance names otherwise"),
1332 class OpInstanceQueryData(OpCode):
1333 """Compute the run-time status of instances."""
1336 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1338 ("static", False, ht.TBool,
1339 "Whether to only return configuration data without querying"
1344 class OpInstanceSetParams(OpCode):
1345 """Change the parameters of an instance."""
1346 OP_DSC_FIELD = "instance_name"
1351 # TODO: Use _TestNicDef
1352 ("nics", ht.EmptyList, ht.TList,
1353 "List of NIC changes. Each item is of the form ``(op, settings)``."
1354 " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1355 " ``%s`` to remove the last NIC or a number to modify the settings"
1356 " of the NIC with that index." %
1357 (constants.DDM_ADD, constants.DDM_REMOVE)),
1358 ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1359 ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1360 ("hvparams", ht.EmptyDict, ht.TDict,
1361 "Per-instance hypervisor parameters, hypervisor-dependent"),
1362 ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1363 "Disk template for instance"),
1364 ("remote_node", None, ht.TMaybeString,
1365 "Secondary node (used when changing disk template)"),
1366 ("os_name", None, ht.TMaybeString,
1367 "Change instance's OS name. Does not reinstall the instance."),
1368 ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1369 ("wait_for_sync", True, ht.TBool,
1370 "Whether to wait for the disk to synchronize, when changing template"),
1371 ("offline_inst", False, ht.TBool,
1372 "Whether to turn off the down instance completely"),
1373 ("online_inst", False, ht.TBool,
1374 "Whether to enable the offline instance"),
1376 OP_RESULT = _TSetParamsResult
1379 class OpInstanceGrowDisk(OpCode):
1380 """Grow a disk of an instance."""
1381 OP_DSC_FIELD = "instance_name"
1385 ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1386 ("amount", ht.NoDefault, ht.TInt,
1387 "Amount of disk space to add (megabytes)"),
1391 class OpInstanceChangeGroup(OpCode):
1392 """Moves an instance to another node group."""
1393 OP_DSC_FIELD = "instance_name"
1397 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1398 ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1399 "Destination group names or UUIDs (defaults to \"all but current group\""),
1401 OP_RESULT = TJobIdListOnly
1404 # Node group opcodes
1406 class OpGroupAdd(OpCode):
1407 """Add a node group to the cluster."""
1408 OP_DSC_FIELD = "group_name"
1411 _PNodeGroupAllocPolicy,
1417 class OpGroupAssignNodes(OpCode):
1418 """Assign nodes to a node group."""
1419 OP_DSC_FIELD = "group_name"
1423 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1424 "List of nodes to assign"),
1428 class OpGroupQuery(OpCode):
1429 """Compute the list of node groups."""
1432 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1433 "Empty list to query all groups, group names otherwise"),
1437 class OpGroupSetParams(OpCode):
1438 """Change the parameters of a node group."""
1439 OP_DSC_FIELD = "group_name"
1442 _PNodeGroupAllocPolicy,
1448 OP_RESULT = _TSetParamsResult
1451 class OpGroupRemove(OpCode):
1452 """Remove a node group from the cluster."""
1453 OP_DSC_FIELD = "group_name"
1459 class OpGroupRename(OpCode):
1460 """Rename a node group in the cluster."""
1463 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1465 OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1468 class OpGroupEvacuate(OpCode):
1469 """Evacuate a node group in the cluster."""
1470 OP_DSC_FIELD = "group_name"
1474 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1475 ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1476 "Destination group names or UUIDs"),
1478 OP_RESULT = TJobIdListOnly
1482 class OpOsDiagnose(OpCode):
1483 """Compute the list of guest operating systems."""
1486 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1487 "Which operating systems to diagnose"),
1492 class OpBackupQuery(OpCode):
1493 """Compute the list of exported images."""
1496 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1497 "Empty list to query all nodes, node names otherwise"),
1501 class OpBackupPrepare(OpCode):
1502 """Prepares an instance export.
1504 @ivar instance_name: Instance name
1505 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1508 OP_DSC_FIELD = "instance_name"
1511 ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1516 class OpBackupExport(OpCode):
1517 """Export an instance.
1519 For local exports, the export destination is the node name. For remote
1520 exports, the export destination is a list of tuples, each consisting of
1521 hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1522 the cluster domain secret over the value "${index}:${hostname}:${port}". The
1523 destination X509 CA must be a signed certificate.
1525 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1526 @ivar target_node: Export destination
1527 @ivar x509_key_name: X509 key to use (remote export only)
1528 @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1532 OP_DSC_FIELD = "instance_name"
1536 # TODO: Rename target_node as it changes meaning for different export modes
1537 # (e.g. "destination")
1538 ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1539 "Destination information, depends on export mode"),
1540 ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1541 ("remove_instance", False, ht.TBool,
1542 "Whether to remove instance after export"),
1543 ("ignore_remove_failures", False, ht.TBool,
1544 "Whether to ignore failures while removing instances"),
1545 ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1547 ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1548 "Name of X509 key (remote export only)"),
1549 ("destination_x509_ca", None, ht.TMaybeString,
1550 "Destination X509 CA (remote export only)"),
1554 class OpBackupRemove(OpCode):
1555 """Remove an instance's export."""
1556 OP_DSC_FIELD = "instance_name"
1563 class OpTagsGet(OpCode):
1564 """Returns the tags of the given object."""
1565 OP_DSC_FIELD = "name"
1568 # Name is only meaningful for nodes and instances
1569 ("name", ht.NoDefault, ht.TMaybeString, None),
1573 class OpTagsSearch(OpCode):
1574 """Searches the tags in the cluster for a given pattern."""
1575 OP_DSC_FIELD = "pattern"
1577 ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1581 class OpTagsSet(OpCode):
1582 """Add a list of tags on a given object."""
1586 # Name is only meaningful for nodes and instances
1587 ("name", ht.NoDefault, ht.TMaybeString, None),
1591 class OpTagsDel(OpCode):
1592 """Remove a list of tags from a given object."""
1596 # Name is only meaningful for nodes and instances
1597 ("name", ht.NoDefault, ht.TMaybeString, None),
1602 class OpTestDelay(OpCode):
1603 """Sleeps for a configured amount of time.
1605 This is used just for debugging and testing.
1608 - duration: the time to sleep
1609 - on_master: if true, sleep on the master
1610 - on_nodes: list of nodes in which to sleep
1612 If the on_master parameter is true, it will execute a sleep on the
1613 master (before any node sleep).
1615 If the on_nodes list is not empty, it will sleep on those nodes
1616 (after the sleep on the master, if that is enabled).
1618 As an additional feature, the case of duration < 0 will be reported
1619 as an execution error, so this opcode can be used as a failure
1620 generator. The case of duration == 0 will not be treated specially.
1623 OP_DSC_FIELD = "duration"
1625 ("duration", ht.NoDefault, ht.TNumber, None),
1626 ("on_master", True, ht.TBool, None),
1627 ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1628 ("repeat", 0, ht.TPositiveInt, None),
1632 class OpTestAllocator(OpCode):
1633 """Allocator framework testing.
1635 This opcode has two modes:
1636 - gather and return allocator input for a given mode (allocate new
1637 or replace secondary) and a given instance definition (direction
1639 - run a selected allocator for a given operation (as above) and
1640 return the allocator output (direction 'out')
1643 OP_DSC_FIELD = "allocator"
1645 ("direction", ht.NoDefault,
1646 ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1647 ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1648 ("name", ht.NoDefault, ht.TNonEmptyString, None),
1649 ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1650 ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1651 ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1652 ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1653 ("hypervisor", None, ht.TMaybeString, None),
1654 ("allocator", None, ht.TMaybeString, None),
1655 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1656 ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1657 ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1658 ("os", None, ht.TMaybeString, None),
1659 ("disk_template", None, ht.TMaybeString, None),
1660 ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1663 ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1664 ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1669 class OpTestJqueue(OpCode):
1670 """Utility opcode to test some aspects of the job queue.
1674 ("notify_waitlock", False, ht.TBool, None),
1675 ("notify_exec", False, ht.TBool, None),
1676 ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1677 ("fail", False, ht.TBool, None),
1681 class OpTestDummy(OpCode):
1682 """Utility opcode used by unittests.
1686 ("result", ht.NoDefault, ht.NoType, None),
1687 ("messages", ht.NoDefault, ht.NoType, None),
1688 ("fail", ht.NoDefault, ht.NoType, None),
1689 ("submit_jobs", None, ht.NoType, None),
1695 """Returns list of all defined opcodes.
1697 Does not eliminate duplicates by C{OP_ID}.
1700 return [v for v in globals().values()
1701 if (isinstance(v, type) and issubclass(v, OpCode) and
1702 hasattr(v, "OP_ID") and v is not OpCode)]
1705 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())