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 constants
40 from ganeti import errors
42 from ganeti import objects
43 from ganeti import query
46 # Common opcode attributes
48 #: output fields for a query operation
49 _POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
50 "Selected output fields")
52 #: the shutdown timeout
54 ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
55 "How long to wait for instance to shut down")
57 #: the force parameter
58 _PForce = ("force", False, ht.TBool, "Whether to force the operation")
60 #: a required instance name (for single-instance LUs)
61 _PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString,
64 #: Whether to ignore offline nodes
65 _PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
66 "Whether to ignore offline nodes")
68 #: a required node name (for single-node LUs)
69 _PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
71 #: a required node group name (for single-group LUs)
72 _PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
74 #: Migration type (live/non-live)
75 _PMigrationMode = ("mode", None,
76 ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)),
79 #: Obsolete 'live' migration mode (boolean)
80 _PMigrationLive = ("live", None, ht.TMaybeBool,
81 "Legacy setting for live migration, do not use")
84 _PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
86 #: List of tag strings
87 _PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
89 _PForceVariant = ("force_variant", False, ht.TBool,
90 "Whether to force an unknown OS variant")
92 _PWaitForSync = ("wait_for_sync", True, ht.TBool,
93 "Whether to wait for the disk to synchronize")
95 _PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
96 "Whether to ignore disk consistency")
98 _PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
100 _PUseLocking = ("use_locking", False, ht.TBool,
101 "Whether to use synchronization")
103 _PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
105 _PNodeGroupAllocPolicy = \
106 ("alloc_policy", None,
107 ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
108 "Instance allocation policy")
110 _PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
111 "Default node parameters for group")
113 _PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
114 "Resource(s) to query for")
116 _PEarlyRelease = ("early_release", False, ht.TBool,
117 "Whether to release locks as soon as possible")
119 _PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
121 #: Do not remember instance state changes
122 _PNoRemember = ("no_remember", False, ht.TBool,
123 "Do not remember the state change")
125 #: Target node for instance migration/failover
126 _PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
127 "Target node for shared-storage instances")
129 _PStartupPaused = ("startup_paused", False, ht.TBool,
130 "Pause instance at startup")
132 _PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
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")
146 _PDiskParams = ("diskparams", None,
148 ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict),
150 "Disk templates' parameter defaults")
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")
157 _PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
158 "Whether to ignore ipolicy violations")
160 # Allow runtime changes while migrating
161 _PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
162 "Allow runtime changes (eg. memory ballooning)")
165 #: OP_ID conversion regular expression
166 _OPID_RE = re.compile("([a-z])([A-Z])")
168 #: Utility function for L{OpClusterSetParams}
169 _TestClusterOsListItem = \
170 ht.TAnd(ht.TIsLength(2), ht.TItems([
171 ht.TElemOf(constants.DDMS_VALUES),
175 _TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
177 # TODO: Generate check from constants.INIC_PARAMS_TYPES
178 #: Utility function for testing NIC definitions
180 ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
181 ht.TOr(ht.TNone, ht.TNonEmptyString)))
183 _TSetParamsResultItemItems = [
184 ht.Comment("name of changed parameter")(ht.TNonEmptyString),
185 ht.Comment("new value")(ht.TAny),
188 _TSetParamsResult = \
189 ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
190 ht.TItems(_TSetParamsResultItemItems)))
192 # TODO: Generate check from constants.IDISK_PARAMS_TYPES (however, not all users
193 # of this check support all parameters)
195 ht.Comment("Disk parameters")(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
196 ht.TOr(ht.TNonEmptyString, ht.TInt)))
199 ht.TListOf(ht.TAnd(ht.TIsLength(2),
200 ht.TItems([ht.TElemOf(constants.RS_ALL),
203 _TQueryResult = ht.TListOf(_TQueryRow)
205 _TOldQueryRow = ht.TListOf(ht.TAny)
207 _TOldQueryResult = ht.TListOf(_TOldQueryRow)
217 #: Attribute name for dependencies
218 DEPEND_ATTR = "depends"
220 #: Attribute name for comment
221 COMMENT_ATTR = "comment"
225 """Convert an opcode class name to an OP_ID.
228 @param name: the class name, as OpXxxYyy
230 @return: the name in the OP_XXXX_YYYY format
233 if not name.startswith("Op"):
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
240 name = _OPID_RE.sub(r"\1,\2", name)
241 elems = name.split(",")
242 return "_".join(n.upper() for n in elems)
245 def _GenerateObjectTypeCheck(obj, fields_types):
246 """Helper to generate type checks for objects.
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
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)
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),
267 def RequireFileStorage():
268 """Checks that file storage is enabled.
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.
273 @raise errors.OpPrereqError: when file storage is disabled
276 if not constants.ENABLE_FILE_STORAGE:
277 raise errors.OpPrereqError("File storage disabled at configure time",
281 def RequireSharedFileStorage():
282 """Checks that shared file storage is enabled.
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.
287 @raise errors.OpPrereqError: when shared file storage is disabled
290 if not constants.ENABLE_SHARED_FILE_STORAGE:
291 raise errors.OpPrereqError("Shared file storage disabled at"
292 " configure time", errors.ECODE_INVAL)
295 @ht.WithDesc("CheckFileStorage")
296 def _CheckFileStorage(value):
297 """Ensures file storage is enabled if used.
300 if value == constants.DT_FILE:
302 elif value == constants.DT_SHARED_FILE:
303 RequireSharedFileStorage()
307 def _BuildDiskTemplateCheck(accept_none):
308 """Builds check for disk template.
310 @type accept_none: bool
311 @param accept_none: whether to accept None as a correct value
315 template_check = ht.TElemOf(constants.DISK_TEMPLATES)
318 template_check = ht.TOr(template_check, ht.TNone)
320 return ht.TAnd(template_check, _CheckFileStorage)
323 def _CheckStorageType(storage_type):
324 """Ensure a given storage type is valid.
327 if storage_type not in constants.VALID_STORAGE_TYPES:
328 raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
330 if storage_type == constants.ST_FILE:
335 #: Storage type parameter
336 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
340 class _AutoOpParamSlots(type):
341 """Meta class for opcode definitions.
344 def __new__(mcs, name, bases, attrs):
345 """Called when a class should be created.
347 @param mcs: The meta class
348 @param name: Name of created class
349 @param bases: Base classes
351 @param attrs: Class attributes
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
358 attrs["OP_ID"] = _NameToId(name)
360 # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
361 params = attrs.setdefault("OP_PARAMS", [])
363 # Use parameter names as slots
364 slots = [pname for (pname, _, _, _) in params]
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
369 attrs["__slots__"] = slots
371 return type.__new__(mcs, name, bases, attrs)
374 class BaseOpCode(object):
375 """A simple serializable object.
377 This object serves as a parent class for OpCode without any custom
381 # pylint: disable=E1101
382 # as OP_ID is dynamically defined
383 __metaclass__ = _AutoOpParamSlots
385 def __init__(self, **kwargs):
386 """Constructor for BaseOpCode.
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.
394 slots = self._all_slots()
397 raise TypeError("Object %s doesn't support the parameter '%s'" %
398 (self.__class__.__name__, key))
399 setattr(self, key, kwargs[key])
401 def __getstate__(self):
402 """Generic serializer.
404 This method just returns the contents of the instance as a
408 @return: the instance attributes and their values
412 for name in self._all_slots():
413 if hasattr(self, name):
414 state[name] = getattr(self, name)
417 def __setstate__(self, state):
418 """Generic unserializer.
420 This method just restores from the serialized state the attributes
421 of the current instance.
423 @param state: the serialized opcode data
427 if not isinstance(state, dict):
428 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
431 for name in self._all_slots():
432 if name not in state and hasattr(self, name):
436 setattr(self, name, state[name])
440 """Compute the list of all declared slots for a class.
444 for parent in cls.__mro__:
445 slots.extend(getattr(parent, "__slots__", []))
449 def GetAllParams(cls):
450 """Compute list of all parameters for an opcode.
454 for parent in cls.__mro__:
455 slots.extend(getattr(parent, "OP_PARAMS", []))
458 def Validate(self, set_defaults):
459 """Validate opcode parameters, optionally setting default values.
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
467 for (attr_name, default, test, _) in self.GetAllParams():
468 assert test == ht.NoType or callable(test)
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),
476 if callable(default):
480 setattr(self, attr_name, dval)
482 if test == ht.NoType:
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),
496 def _BuildJobDepCheck(relative):
497 """Builds check for job dependencies (L{DEPEND_ATTR}).
500 @param relative: Whether to accept relative job IDs (negative)
505 job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
510 ht.TAnd(ht.TIsLength(2),
512 ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
514 return ht.TMaybeListOf(job_dep)
517 TNoRelativeJobDependencies = _BuildJobDepCheck(False)
519 #: List of submission status and job ID as returned by C{SubmitManyJobs}
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,
526 TJobIdList = ht.TListOf(_TJobIdListItem)
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),
534 class OpCode(BaseOpCode):
537 This is the root of the actual OpCode hierarchy. All clases derived
538 from this class should override OP_ID.
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
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
552 @ivar priority: Opcode priority for queue
555 # pylint: disable=E1101
556 # as OP_ID is dynamically defined
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>`"
567 (COMMENT_ATTR, None, ht.TMaybeString,
568 "Comment describing the purpose of the opcode"),
572 def __getstate__(self):
573 """Specialized getstate for opcodes.
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.
580 @return: the state as a dictionary
583 data = BaseOpCode.__getstate__(self)
584 data["OP_ID"] = self.OP_ID
588 def LoadOpCode(cls, data):
589 """Generic load opcode method.
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.
596 @param data: the serialized opcode
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"]
605 if op_id in OP_MAPPING:
606 op_class = OP_MAPPING[op_id]
608 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
611 new_data = data.copy()
612 del new_data["OP_ID"]
613 op.__setstate__(new_data)
617 """Generates a summary description of this opcode.
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
626 assert self.OP_ID is not None and len(self.OP_ID) > 3
627 # all OP_ID start with OP_, we remove that
629 field_name = getattr(self, "OP_DSC_FIELD", None)
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)
637 def TinySummary(self):
638 """Generates a compact summary description of the opcode.
641 assert self.OP_ID.startswith("OP_")
643 text = self.OP_ID[3:]
645 for (prefix, supplement) in _SUMMARY_PREFIX.items():
646 if text.startswith(prefix):
647 return supplement + text[len(prefix):]
654 class OpClusterPostInit(OpCode):
655 """Post cluster initialization.
657 This opcode does not touch the cluster at all. Its purpose is to run hooks
658 after the cluster has been initialized.
664 class OpClusterDestroy(OpCode):
665 """Destroy the cluster.
667 This opcode has no other parameters. All the state is irreversibly
668 lost after the execution of this opcode.
671 OP_RESULT = ht.TNonEmptyString
674 class OpClusterQuery(OpCode):
675 """Query cluster information."""
676 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
679 class OpClusterVerify(OpCode):
680 """Submits all jobs necessary to verify the cluster.
684 _PDebugSimulateErrors,
689 ("group_name", None, ht.TMaybeString, "Group to verify")
691 OP_RESULT = TJobIdListOnly
694 class OpClusterVerifyConfig(OpCode):
695 """Verify the cluster config.
699 _PDebugSimulateErrors,
707 class OpClusterVerifyGroup(OpCode):
708 """Run verify on a node group from the cluster.
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
717 OP_DSC_FIELD = "group_name"
720 _PDebugSimulateErrors,
729 class OpClusterVerifyDisks(OpCode):
730 """Verify the cluster disks.
733 OP_RESULT = TJobIdListOnly
736 class OpGroupVerifyDisks(OpCode):
737 """Verifies the status of all disks in a node group.
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)
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.
750 Note that only instances that are drbd-based are taken into
751 consideration. This might need to be revisited in the future.
754 OP_DSC_FIELD = "group_name"
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)))]))
766 class OpClusterRepairDiskSizes(OpCode):
767 """Verify the disk sizes of the instances and fixes configuration
770 Parameters: optional instances list, in case we want to restrict the
771 checks to only a subset of the instances.
773 Result: a list of tuples, (instance, disk, new-size) for changed
776 In normal operation, the list should be empty.
778 @type instances: list
779 @ivar instances: the list of instances to check, or empty for all instances
783 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
785 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
786 ht.TItems([ht.TNonEmptyString,
791 class OpClusterConfigQuery(OpCode):
792 """Query cluster configuration values."""
796 OP_RESULT = ht.TListOf(ht.TAny)
799 class OpClusterRename(OpCode):
800 """Rename the cluster.
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
808 OP_DSC_FIELD = "name"
810 ("name", ht.NoDefault, ht.TNonEmptyString, None),
812 OP_RESULT = ht.TNonEmptyString
815 class OpClusterSetParams(OpCode):
816 """Change the parameters of the cluster.
818 @type vg_name: C{str} or C{None}
819 @ivar vg_name: The new volume group name or None to disable LVM usage.
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),
829 "List of enabled hypervisors"),
830 ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
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),
837 "Cluster-wide per-OS hypervisor parameter defaults"),
838 ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
840 "Cluster-wide OS parameter defaults"),
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"),
884 class OpClusterRedistConf(OpCode):
885 """Force a full push of the cluster configuration.
891 class OpClusterActivateMasterIp(OpCode):
892 """Activate the master IP on the master node.
898 class OpClusterDeactivateMasterIp(OpCode):
899 """Deactivate the master IP on the master node.
905 class OpQuery(OpCode):
906 """Query for resources/items.
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
913 OP_DSC_FIELD = "what"
917 ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
919 ("qfilter", None, ht.TOr(ht.TNone, ht.TListOf),
923 _GenerateObjectTypeCheck(objects.QueryResponse, {
924 "fields": ht.TListOf(_TObjFdefs),
925 "data": _TQueryResult,
929 class OpQueryFields(OpCode):
930 """Query for available resource/item fields.
932 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
933 @ivar fields: List of fields to retrieve
936 OP_DSC_FIELD = "what"
939 ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
940 "Requested fields; if not given, all are returned"),
943 _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
944 "fields": ht.TListOf(_TObjFdefs),
948 class OpOobCommand(OpCode):
949 """Interact with OOB."""
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"),
962 # Fixme: Make it more specific with all the special cases in LUOobCommand
963 OP_RESULT = _TQueryResult
968 class OpNodeRemove(OpCode):
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.
976 OP_DSC_FIELD = "node_name"
983 class OpNodeAdd(OpCode):
984 """Add a node to the cluster.
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.
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.
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
1011 OP_DSC_FIELD = "node_name"
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"),
1026 OP_RESULT = ht.TNone
1029 class OpNodeQuery(OpCode):
1030 """Compute the list of nodes."""
1034 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1035 "Empty list to query all nodes, node names otherwise"),
1037 OP_RESULT = _TOldQueryResult
1040 class OpNodeQueryvols(OpCode):
1041 """Get list of volumes on node."""
1044 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1045 "Empty list to query all nodes, node names otherwise"),
1047 OP_RESULT = ht.TListOf(ht.TAny)
1050 class OpNodeQueryStorage(OpCode):
1051 """Get information on storage for node(s)."""
1055 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1056 ("name", None, ht.TMaybeString, "Storage name"),
1058 OP_RESULT = _TOldQueryResult
1061 class OpNodeModifyStorage(OpCode):
1062 """Modifies the properies of a storage unit"""
1067 ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1069 OP_RESULT = ht.TNone
1072 class OpRepairNodeStorage(OpCode):
1073 """Repairs the volume group on a node."""
1074 OP_DSC_FIELD = "node_name"
1079 _PIgnoreConsistency,
1081 OP_RESULT = ht.TNone
1084 class OpNodeSetParams(OpCode):
1085 """Change the parameters of a node."""
1086 OP_DSC_FIELD = "node_name"
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"),
1110 OP_RESULT = _TSetParamsResult
1113 class OpNodePowercycle(OpCode):
1114 """Tries to powercycle a node."""
1115 OP_DSC_FIELD = "node_name"
1120 OP_RESULT = ht.TMaybeString
1123 class OpNodeMigrate(OpCode):
1124 """Migrate all instances from a node."""
1125 OP_DSC_FIELD = "node_name"
1130 _PMigrationTargetNode,
1133 ("iallocator", None, ht.TMaybeString,
1134 "Iallocator for deciding the target node for shared-storage instances"),
1136 OP_RESULT = TJobIdListOnly
1139 class OpNodeEvacuate(OpCode):
1140 """Evacuate instances off a number of nodes."""
1141 OP_DSC_FIELD = "node_name"
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"),
1150 OP_RESULT = TJobIdListOnly
1155 class OpInstanceCreate(OpCode):
1156 """Create an instance.
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)
1167 OP_DSC_FIELD = "instance_name"
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"
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),
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" %
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,
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"),
1225 OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1228 class OpInstanceReinstall(OpCode):
1229 """Reinstall an instance's OS."""
1230 OP_DSC_FIELD = "instance_name"
1234 ("os_type", None, ht.TMaybeString, "Instance operating system"),
1235 ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1237 OP_RESULT = ht.TNone
1240 class OpInstanceRemove(OpCode):
1241 """Remove an instance."""
1242 OP_DSC_FIELD = "instance_name"
1246 ("ignore_failures", False, ht.TBool,
1247 "Whether to ignore failures during removal"),
1249 OP_RESULT = ht.TNone
1252 class OpInstanceRename(OpCode):
1253 """Rename an instance."""
1257 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1258 ("ip_check", False, ht.TBool, _PIpCheckDoc),
1260 OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1263 class OpInstanceStartup(OpCode):
1264 """Startup an instance."""
1265 OP_DSC_FIELD = "instance_name"
1269 _PIgnoreOfflineNodes,
1270 ("hvparams", ht.EmptyDict, ht.TDict,
1271 "Temporary hypervisor parameters, hypervisor-dependent"),
1272 ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1276 OP_RESULT = ht.TNone
1279 class OpInstanceShutdown(OpCode):
1280 """Shutdown an instance."""
1281 OP_DSC_FIELD = "instance_name"
1284 _PIgnoreOfflineNodes,
1285 ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1286 "How long to wait for instance to shut down"),
1289 OP_RESULT = ht.TNone
1292 class OpInstanceReboot(OpCode):
1293 """Reboot an instance."""
1294 OP_DSC_FIELD = "instance_name"
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"),
1303 OP_RESULT = ht.TNone
1306 class OpInstanceReplaceDisks(OpCode):
1307 """Replace the disks of an instance."""
1308 OP_DSC_FIELD = "instance_name"
1313 ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1314 "Replacement mode"),
1315 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1317 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1318 ("iallocator", None, ht.TMaybeString,
1319 "Iallocator for deciding new secondary node"),
1321 OP_RESULT = ht.TNone
1324 class OpInstanceFailover(OpCode):
1325 """Failover an instance."""
1326 OP_DSC_FIELD = "instance_name"
1330 _PIgnoreConsistency,
1331 _PMigrationTargetNode,
1333 ("iallocator", None, ht.TMaybeString,
1334 "Iallocator for deciding the target node for shared-storage instances"),
1336 OP_RESULT = ht.TNone
1339 class OpInstanceMigrate(OpCode):
1340 """Migrate an instance.
1342 This migrates (without shutting down an instance) to its secondary
1345 @ivar instance_name: the name of the instance
1346 @ivar mode: the migration mode (live, non-live or None for auto)
1349 OP_DSC_FIELD = "instance_name"
1354 _PMigrationTargetNode,
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"),
1364 OP_RESULT = ht.TNone
1367 class OpInstanceMove(OpCode):
1368 """Move an instance.
1370 This move (with shutting down an instance and data copying) to an
1373 @ivar instance_name: the name of the instance
1374 @ivar target_node: the destination node
1377 OP_DSC_FIELD = "instance_name"
1382 ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1383 _PIgnoreConsistency,
1385 OP_RESULT = ht.TNone
1388 class OpInstanceConsole(OpCode):
1389 """Connect to an instance's console."""
1390 OP_DSC_FIELD = "instance_name"
1394 OP_RESULT = ht.TDict
1397 class OpInstanceActivateDisks(OpCode):
1398 """Activate an instance's disks."""
1399 OP_DSC_FIELD = "instance_name"
1402 ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1404 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1405 ht.TItems([ht.TNonEmptyString,
1407 ht.TNonEmptyString])))
1410 class OpInstanceDeactivateDisks(OpCode):
1411 """Deactivate an instance's disks."""
1412 OP_DSC_FIELD = "instance_name"
1417 OP_RESULT = ht.TNone
1420 class OpInstanceRecreateDisks(OpCode):
1421 """Recreate an instance's disks."""
1423 ht.TAnd(ht.TIsLength(2),
1424 ht.TItems([ht.Comment("Disk index")(ht.TPositiveInt),
1425 ht.Comment("Parameters")(_TDiskParams)]))
1427 OP_DSC_FIELD = "instance_name"
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"),
1437 OP_RESULT = ht.TNone
1440 class OpInstanceQuery(OpCode):
1441 """Compute the list of instances."""
1445 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1446 "Empty list to query all instances, instance names otherwise"),
1448 OP_RESULT = _TOldQueryResult
1451 class OpInstanceQueryData(OpCode):
1452 """Compute the run-time status of instances."""
1455 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1457 ("static", False, ht.TBool,
1458 "Whether to only return configuration data without querying"
1461 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1464 def _TestInstSetParamsModList(fn):
1465 """Generates a check for modification lists.
1469 # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1471 ht.TAnd(ht.TIsLength(2), ht.TItems([
1472 ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TPositiveInt),
1476 # New format, supporting adding/removing disks/NICs at arbitrary indices
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),
1484 return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1485 ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1488 class OpInstanceSetParams(OpCode):
1489 """Change the parameters of an instance.
1492 TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1493 TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1495 OP_DSC_FIELD = "instance_name"
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"),
1528 OP_RESULT = _TSetParamsResult
1531 class OpInstanceGrowDisk(OpCode):
1532 """Grow a disk of an instance."""
1533 OP_DSC_FIELD = "instance_name"
1537 ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1538 ("amount", ht.NoDefault, ht.TInt,
1539 "Amount of disk space to add (megabytes)"),
1541 OP_RESULT = ht.TNone
1544 class OpInstanceChangeGroup(OpCode):
1545 """Moves an instance to another node group."""
1546 OP_DSC_FIELD = "instance_name"
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\""),
1554 OP_RESULT = TJobIdListOnly
1557 # Node group opcodes
1559 class OpGroupAdd(OpCode):
1560 """Add a node group to the cluster."""
1561 OP_DSC_FIELD = "group_name"
1564 _PNodeGroupAllocPolicy,
1569 ("ipolicy", None, ht.TMaybeDict,
1570 "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1572 OP_RESULT = ht.TNone
1575 class OpGroupAssignNodes(OpCode):
1576 """Assign nodes to a node group."""
1577 OP_DSC_FIELD = "group_name"
1581 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1582 "List of nodes to assign"),
1584 OP_RESULT = ht.TNone
1587 class OpGroupQuery(OpCode):
1588 """Compute the list of node groups."""
1591 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1592 "Empty list to query all groups, group names otherwise"),
1594 OP_RESULT = _TOldQueryResult
1597 class OpGroupSetParams(OpCode):
1598 """Change the parameters of a node group."""
1599 OP_DSC_FIELD = "group_name"
1602 _PNodeGroupAllocPolicy,
1607 ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1609 OP_RESULT = _TSetParamsResult
1612 class OpGroupRemove(OpCode):
1613 """Remove a node group from the cluster."""
1614 OP_DSC_FIELD = "group_name"
1618 OP_RESULT = ht.TNone
1621 class OpGroupRename(OpCode):
1622 """Rename a node group in the cluster."""
1625 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1627 OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1630 class OpGroupEvacuate(OpCode):
1631 """Evacuate a node group in the cluster."""
1632 OP_DSC_FIELD = "group_name"
1636 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1637 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1638 "Destination group names or UUIDs"),
1640 OP_RESULT = TJobIdListOnly
1644 class OpOsDiagnose(OpCode):
1645 """Compute the list of guest operating systems."""
1648 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1649 "Which operating systems to diagnose"),
1651 OP_RESULT = _TOldQueryResult
1655 class OpBackupQuery(OpCode):
1656 """Compute the list of exported images."""
1659 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1660 "Empty list to query all nodes, node names otherwise"),
1662 OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1663 ht.TOr(ht.Comment("False on error")(ht.TBool),
1664 ht.TListOf(ht.TNonEmptyString)))
1667 class OpBackupPrepare(OpCode):
1668 """Prepares an instance export.
1670 @ivar instance_name: Instance name
1671 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1674 OP_DSC_FIELD = "instance_name"
1677 ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1680 OP_RESULT = ht.TOr(ht.TNone, ht.TDict)
1683 class OpBackupExport(OpCode):
1684 """Export an instance.
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.
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
1699 OP_DSC_FIELD = "instance_name"
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),
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)"),
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)),
1726 class OpBackupRemove(OpCode):
1727 """Remove an instance's export."""
1728 OP_DSC_FIELD = "instance_name"
1732 OP_RESULT = ht.TNone
1736 class OpTagsGet(OpCode):
1737 """Returns the tags of the given object."""
1738 OP_DSC_FIELD = "name"
1741 # Name is only meaningful for nodes and instances
1742 ("name", ht.NoDefault, ht.TMaybeString, None),
1744 OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1747 class OpTagsSearch(OpCode):
1748 """Searches the tags in the cluster for a given pattern."""
1749 OP_DSC_FIELD = "pattern"
1751 ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1753 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1759 class OpTagsSet(OpCode):
1760 """Add a list of tags on a given object."""
1764 # Name is only meaningful for nodes and instances
1765 ("name", ht.NoDefault, ht.TMaybeString, None),
1767 OP_RESULT = ht.TNone
1770 class OpTagsDel(OpCode):
1771 """Remove a list of tags from a given object."""
1775 # Name is only meaningful for nodes and instances
1776 ("name", ht.NoDefault, ht.TMaybeString, None),
1778 OP_RESULT = ht.TNone
1782 class OpTestDelay(OpCode):
1783 """Sleeps for a configured amount of time.
1785 This is used just for debugging and testing.
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
1792 If the on_master parameter is true, it will execute a sleep on the
1793 master (before any node sleep).
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).
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.
1803 OP_DSC_FIELD = "duration"
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),
1812 class OpTestAllocator(OpCode):
1813 """Allocator framework testing.
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
1819 - run a selected allocator for a given operation (as above) and
1820 return the allocator output (direction 'out')
1823 OP_DSC_FIELD = "allocator"
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,
1833 ht.TOr(ht.TNone, ht.TNonEmptyString))),
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),
1845 ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1846 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1850 class OpTestJqueue(OpCode):
1851 """Utility opcode to test some aspects of the job queue.
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),
1862 class OpTestDummy(OpCode):
1863 """Utility opcode used by unittests.
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),
1876 """Returns list of all defined opcodes.
1878 Does not eliminate duplicates by C{OP_ID}.
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)]
1886 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())