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
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")
156 _PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
157 "Whether to ignore ipolicy violations")
159 # Allow runtime changes while migrating
160 _PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
161 "Allow runtime changes (eg. memory ballooning)")
164 #: OP_ID conversion regular expression
165 _OPID_RE = re.compile("([a-z])([A-Z])")
167 #: Utility function for L{OpClusterSetParams}
168 _TestClusterOsListItem = \
169 ht.TAnd(ht.TIsLength(2), ht.TItems([
170 ht.TElemOf(constants.DDMS_VALUES),
174 _TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
176 # TODO: Generate check from constants.INIC_PARAMS_TYPES
177 #: Utility function for testing NIC definitions
179 ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
180 ht.TOr(ht.TNone, ht.TNonEmptyString)))
182 _TSetParamsResultItemItems = [
183 ht.Comment("name of changed parameter")(ht.TNonEmptyString),
184 ht.Comment("new value")(ht.TAny),
187 _TSetParamsResult = \
188 ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
189 ht.TItems(_TSetParamsResultItemItems)))
191 # TODO: Generate check from constants.IDISK_PARAMS_TYPES (however, not all users
192 # of this check support all parameters)
194 ht.Comment("Disk parameters")(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
195 ht.TOr(ht.TNonEmptyString, ht.TInt)))
198 ht.TListOf(ht.TAnd(ht.TIsLength(2),
199 ht.TItems([ht.TElemOf(constants.RS_ALL),
202 _TQueryResult = ht.TListOf(_TQueryRow)
204 _TOldQueryRow = ht.TListOf(ht.TAny)
206 _TOldQueryResult = ht.TListOf(_TOldQueryRow)
216 #: Attribute name for dependencies
217 DEPEND_ATTR = "depends"
219 #: Attribute name for comment
220 COMMENT_ATTR = "comment"
224 """Convert an opcode class name to an OP_ID.
227 @param name: the class name, as OpXxxYyy
229 @return: the name in the OP_XXXX_YYYY format
232 if not name.startswith("Op"):
234 # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
235 # consume any input, and hence we would just have all the elements
236 # in the list, one by one; but it seems that split doesn't work on
237 # non-consuming input, hence we have to process the input string a
239 name = _OPID_RE.sub(r"\1,\2", name)
240 elems = name.split(",")
241 return "_".join(n.upper() for n in elems)
244 def _GenerateObjectTypeCheck(obj, fields_types):
245 """Helper to generate type checks for objects.
247 @param obj: The object to generate type checks
248 @param fields_types: The fields and their types as a dict
249 @return: A ht type check function
252 assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
253 "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
254 return ht.TStrictDict(True, True, fields_types)
258 _GenerateObjectTypeCheck(objects.QueryFieldDefinition, {
259 "name": ht.TNonEmptyString,
260 "title": ht.TNonEmptyString,
261 "kind": ht.TElemOf(constants.QFT_ALL),
262 "doc": ht.TNonEmptyString,
266 def RequireFileStorage():
267 """Checks that file storage is enabled.
269 While it doesn't really fit into this module, L{utils} was deemed too large
270 of a dependency to be imported for just one or two functions.
272 @raise errors.OpPrereqError: when file storage is disabled
275 if not constants.ENABLE_FILE_STORAGE:
276 raise errors.OpPrereqError("File storage disabled at configure time",
280 def RequireSharedFileStorage():
281 """Checks that shared file storage is enabled.
283 While it doesn't really fit into this module, L{utils} was deemed too large
284 of a dependency to be imported for just one or two functions.
286 @raise errors.OpPrereqError: when shared file storage is disabled
289 if not constants.ENABLE_SHARED_FILE_STORAGE:
290 raise errors.OpPrereqError("Shared file storage disabled at"
291 " configure time", errors.ECODE_INVAL)
294 @ht.WithDesc("CheckFileStorage")
295 def _CheckFileStorage(value):
296 """Ensures file storage is enabled if used.
299 if value == constants.DT_FILE:
301 elif value == constants.DT_SHARED_FILE:
302 RequireSharedFileStorage()
306 def _BuildDiskTemplateCheck(accept_none):
307 """Builds check for disk template.
309 @type accept_none: bool
310 @param accept_none: whether to accept None as a correct value
314 template_check = ht.TElemOf(constants.DISK_TEMPLATES)
317 template_check = ht.TOr(template_check, ht.TNone)
319 return ht.TAnd(template_check, _CheckFileStorage)
322 def _CheckStorageType(storage_type):
323 """Ensure a given storage type is valid.
326 if storage_type not in constants.VALID_STORAGE_TYPES:
327 raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
329 if storage_type == constants.ST_FILE:
334 #: Storage type parameter
335 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
339 class _AutoOpParamSlots(type):
340 """Meta class for opcode definitions.
343 def __new__(mcs, name, bases, attrs):
344 """Called when a class should be created.
346 @param mcs: The meta class
347 @param name: Name of created class
348 @param bases: Base classes
350 @param attrs: Class attributes
353 assert "__slots__" not in attrs, \
354 "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
355 assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
357 attrs["OP_ID"] = _NameToId(name)
359 # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
360 params = attrs.setdefault("OP_PARAMS", [])
362 # Use parameter names as slots
363 slots = [pname for (pname, _, _, _) in params]
365 assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
366 "Class '%s' uses unknown field in OP_DSC_FIELD" % name
368 attrs["__slots__"] = slots
370 return type.__new__(mcs, name, bases, attrs)
373 class BaseOpCode(object):
374 """A simple serializable object.
376 This object serves as a parent class for OpCode without any custom
380 # pylint: disable=E1101
381 # as OP_ID is dynamically defined
382 __metaclass__ = _AutoOpParamSlots
384 def __init__(self, **kwargs):
385 """Constructor for BaseOpCode.
387 The constructor takes only keyword arguments and will set
388 attributes on this object based on the passed arguments. As such,
389 it means that you should not pass arguments which are not in the
390 __slots__ attribute for this class.
393 slots = self._all_slots()
396 raise TypeError("Object %s doesn't support the parameter '%s'" %
397 (self.__class__.__name__, key))
398 setattr(self, key, kwargs[key])
400 def __getstate__(self):
401 """Generic serializer.
403 This method just returns the contents of the instance as a
407 @return: the instance attributes and their values
411 for name in self._all_slots():
412 if hasattr(self, name):
413 state[name] = getattr(self, name)
416 def __setstate__(self, state):
417 """Generic unserializer.
419 This method just restores from the serialized state the attributes
420 of the current instance.
422 @param state: the serialized opcode data
426 if not isinstance(state, dict):
427 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
430 for name in self._all_slots():
431 if name not in state and hasattr(self, name):
435 setattr(self, name, state[name])
439 """Compute the list of all declared slots for a class.
443 for parent in cls.__mro__:
444 slots.extend(getattr(parent, "__slots__", []))
448 def GetAllParams(cls):
449 """Compute list of all parameters for an opcode.
453 for parent in cls.__mro__:
454 slots.extend(getattr(parent, "OP_PARAMS", []))
457 def Validate(self, set_defaults):
458 """Validate opcode parameters, optionally setting default values.
460 @type set_defaults: bool
461 @param set_defaults: Whether to set default values
462 @raise errors.OpPrereqError: When a parameter value doesn't match
466 for (attr_name, default, test, _) in self.GetAllParams():
467 assert test == ht.NoType or callable(test)
469 if not hasattr(self, attr_name):
470 if default == ht.NoDefault:
471 raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
472 (self.OP_ID, attr_name),
475 if callable(default):
479 setattr(self, attr_name, dval)
481 if test == ht.NoType:
485 if set_defaults or hasattr(self, attr_name):
486 attr_val = getattr(self, attr_name)
487 if not test(attr_val):
488 logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
489 self.OP_ID, attr_name, type(attr_val), attr_val)
490 raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
491 (self.OP_ID, attr_name),
495 def _BuildJobDepCheck(relative):
496 """Builds check for job dependencies (L{DEPEND_ATTR}).
499 @param relative: Whether to accept relative job IDs (negative)
504 job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
509 ht.TAnd(ht.TIsLength(2),
511 ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
513 return ht.TMaybeListOf(job_dep)
516 TNoRelativeJobDependencies = _BuildJobDepCheck(False)
518 #: List of submission status and job ID as returned by C{SubmitManyJobs}
520 ht.TAnd(ht.TIsLength(2),
521 ht.TItems([ht.Comment("success")(ht.TBool),
522 ht.Comment("Job ID if successful, error message"
523 " otherwise")(ht.TOr(ht.TString,
525 TJobIdList = ht.TListOf(_TJobIdListItem)
527 #: Result containing only list of submitted jobs
528 TJobIdListOnly = ht.TStrictDict(True, True, {
529 constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
533 class OpCode(BaseOpCode):
536 This is the root of the actual OpCode hierarchy. All clases derived
537 from this class should override OP_ID.
539 @cvar OP_ID: The ID of this opcode. This should be unique amongst all
540 children of this class.
541 @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
542 string returned by Summary(); see the docstring of that
544 @cvar OP_PARAMS: List of opcode attributes, the default values they should
545 get if not already defined, and types they must match.
546 @cvar OP_RESULT: Callable to verify opcode result
547 @cvar WITH_LU: Boolean that specifies whether this should be included in
548 mcpu's dispatch table
549 @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
551 @ivar priority: Opcode priority for queue
554 # pylint: disable=E1101
555 # as OP_ID is dynamically defined
558 ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
559 ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
560 ("priority", constants.OP_PRIO_DEFAULT,
561 ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
562 (DEPEND_ATTR, None, _BuildJobDepCheck(True),
563 "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
564 " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
566 (COMMENT_ATTR, None, ht.TMaybeString,
567 "Comment describing the purpose of the opcode"),
571 def __getstate__(self):
572 """Specialized getstate for opcodes.
574 This method adds to the state dictionary the OP_ID of the class,
575 so that on unload we can identify the correct class for
576 instantiating the opcode.
579 @return: the state as a dictionary
582 data = BaseOpCode.__getstate__(self)
583 data["OP_ID"] = self.OP_ID
587 def LoadOpCode(cls, data):
588 """Generic load opcode method.
590 The method identifies the correct opcode class from the dict-form
591 by looking for a OP_ID key, if this is not found, or its value is
592 not available in this module as a child of this class, we fail.
595 @param data: the serialized opcode
598 if not isinstance(data, dict):
599 raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
600 if "OP_ID" not in data:
601 raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
602 op_id = data["OP_ID"]
604 if op_id in OP_MAPPING:
605 op_class = OP_MAPPING[op_id]
607 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
610 new_data = data.copy()
611 del new_data["OP_ID"]
612 op.__setstate__(new_data)
616 """Generates a summary description of this opcode.
618 The summary is the value of the OP_ID attribute (without the "OP_"
619 prefix), plus the value of the OP_DSC_FIELD attribute, if one was
620 defined; this field should allow to easily identify the operation
621 (for an instance creation job, e.g., it would be the instance
625 assert self.OP_ID is not None and len(self.OP_ID) > 3
626 # all OP_ID start with OP_, we remove that
628 field_name = getattr(self, "OP_DSC_FIELD", None)
630 field_value = getattr(self, field_name, None)
631 if isinstance(field_value, (list, tuple)):
632 field_value = ",".join(str(i) for i in field_value)
633 txt = "%s(%s)" % (txt, field_value)
636 def TinySummary(self):
637 """Generates a compact summary description of the opcode.
640 assert self.OP_ID.startswith("OP_")
642 text = self.OP_ID[3:]
644 for (prefix, supplement) in _SUMMARY_PREFIX.items():
645 if text.startswith(prefix):
646 return supplement + text[len(prefix):]
653 class OpClusterPostInit(OpCode):
654 """Post cluster initialization.
656 This opcode does not touch the cluster at all. Its purpose is to run hooks
657 after the cluster has been initialized.
663 class OpClusterDestroy(OpCode):
664 """Destroy the cluster.
666 This opcode has no other parameters. All the state is irreversibly
667 lost after the execution of this opcode.
670 OP_RESULT = ht.TNonEmptyString
673 class OpClusterQuery(OpCode):
674 """Query cluster information."""
675 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
678 class OpClusterVerify(OpCode):
679 """Submits all jobs necessary to verify the cluster.
683 _PDebugSimulateErrors,
688 ("group_name", None, ht.TMaybeString, "Group to verify")
690 OP_RESULT = TJobIdListOnly
693 class OpClusterVerifyConfig(OpCode):
694 """Verify the cluster config.
698 _PDebugSimulateErrors,
706 class OpClusterVerifyGroup(OpCode):
707 """Run verify on a node group from the cluster.
709 @type skip_checks: C{list}
710 @ivar skip_checks: steps to be skipped from the verify process; this
711 needs to be a subset of
712 L{constants.VERIFY_OPTIONAL_CHECKS}; currently
713 only L{constants.VERIFY_NPLUSONE_MEM} can be passed
716 OP_DSC_FIELD = "group_name"
719 _PDebugSimulateErrors,
728 class OpClusterVerifyDisks(OpCode):
729 """Verify the cluster disks.
732 OP_RESULT = TJobIdListOnly
735 class OpGroupVerifyDisks(OpCode):
736 """Verifies the status of all disks in a node group.
738 Result: a tuple of three elements:
739 - dict of node names with issues (values: error msg)
740 - list of instances with degraded disks (that should be activated)
741 - dict of instances with missing logical volumes (values: (node, vol)
742 pairs with details about the missing volumes)
744 In normal operation, all lists should be empty. A non-empty instance
745 list (3rd element of the result) is still ok (errors were fixed) but
746 non-empty node list means some node is down, and probably there are
747 unfixable drbd errors.
749 Note that only instances that are drbd-based are taken into
750 consideration. This might need to be revisited in the future.
753 OP_DSC_FIELD = "group_name"
758 ht.TAnd(ht.TIsLength(3),
759 ht.TItems([ht.TDictOf(ht.TString, ht.TString),
760 ht.TListOf(ht.TString),
761 ht.TDictOf(ht.TString,
762 ht.TListOf(ht.TListOf(ht.TString)))]))
765 class OpClusterRepairDiskSizes(OpCode):
766 """Verify the disk sizes of the instances and fixes configuration
769 Parameters: optional instances list, in case we want to restrict the
770 checks to only a subset of the instances.
772 Result: a list of tuples, (instance, disk, new-size) for changed
775 In normal operation, the list should be empty.
777 @type instances: list
778 @ivar instances: the list of instances to check, or empty for all instances
782 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
784 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
785 ht.TItems([ht.TNonEmptyString,
790 class OpClusterConfigQuery(OpCode):
791 """Query cluster configuration values."""
795 OP_RESULT = ht.TListOf(ht.TAny)
798 class OpClusterRename(OpCode):
799 """Rename the cluster.
802 @ivar name: The new name of the cluster. The name and/or the master IP
803 address will be changed to match the new name and its IP
807 OP_DSC_FIELD = "name"
809 ("name", ht.NoDefault, ht.TNonEmptyString, None),
811 OP_RESULT = ht.TNonEmptyString
814 class OpClusterSetParams(OpCode):
815 """Change the parameters of the cluster.
817 @type vg_name: C{str} or C{None}
818 @ivar vg_name: The new volume group name or None to disable LVM usage.
824 ("vg_name", None, ht.TMaybeString, "Volume group name"),
825 ("enabled_hypervisors", None,
826 ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
828 "List of enabled hypervisors"),
829 ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
831 "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
832 ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
833 "Cluster-wide backend parameter defaults"),
834 ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
836 "Cluster-wide per-OS hypervisor parameter defaults"),
837 ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
839 "Cluster-wide OS parameter defaults"),
841 ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
842 "Master candidate pool size"),
843 ("uid_pool", None, ht.NoType,
844 "Set UID pool, must be list of lists describing UID ranges (two items,"
845 " start and end inclusive)"),
846 ("add_uids", None, ht.NoType,
847 "Extend UID pool, must be list of lists describing UID ranges (two"
848 " items, start and end inclusive) to be added"),
849 ("remove_uids", None, ht.NoType,
850 "Shrink UID pool, must be list of lists describing UID ranges (two"
851 " items, start and end inclusive) to be removed"),
852 ("maintain_node_health", None, ht.TMaybeBool,
853 "Whether to automatically maintain node health"),
854 ("prealloc_wipe_disks", None, ht.TMaybeBool,
855 "Whether to wipe disks before allocating them to instances"),
856 ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
857 ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
858 ("ipolicy", None, ht.TMaybeDict,
859 "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
860 ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
861 ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
862 "Default iallocator for cluster"),
863 ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
864 "Master network device"),
865 ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
866 "Netmask of the master IP"),
867 ("reserved_lvs", None, ht.TMaybeListOf(ht.TNonEmptyString),
868 "List of reserved LVs"),
869 ("hidden_os", None, _TestClusterOsList,
870 "Modify list of hidden operating systems. Each modification must have"
871 " two items, the operation and the OS name. The operation can be"
872 " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
873 ("blacklisted_os", None, _TestClusterOsList,
874 "Modify list of blacklisted operating systems. Each modification must have"
875 " two items, the operation and the OS name. The operation can be"
876 " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
877 ("use_external_mip_script", None, ht.TMaybeBool,
878 "Whether to use an external master IP address setup script"),
883 class OpClusterRedistConf(OpCode):
884 """Force a full push of the cluster configuration.
890 class OpClusterActivateMasterIp(OpCode):
891 """Activate the master IP on the master node.
897 class OpClusterDeactivateMasterIp(OpCode):
898 """Deactivate the master IP on the master node.
904 class OpQuery(OpCode):
905 """Query for resources/items.
907 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
908 @ivar fields: List of fields to retrieve
909 @ivar qfilter: Query filter
912 OP_DSC_FIELD = "what"
916 ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
918 ("qfilter", None, ht.TOr(ht.TNone, ht.TListOf),
922 _GenerateObjectTypeCheck(objects.QueryResponse, {
923 "fields": ht.TListOf(_TQueryFieldDef),
924 "data": _TQueryResult,
928 class OpQueryFields(OpCode):
929 """Query for available resource/item fields.
931 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
932 @ivar fields: List of fields to retrieve
935 OP_DSC_FIELD = "what"
938 ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
939 "Requested fields; if not given, all are returned"),
942 _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
943 "fields": ht.TListOf(_TQueryFieldDef),
947 class OpOobCommand(OpCode):
948 """Interact with OOB."""
950 ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
951 "List of nodes to run the OOB command against"),
952 ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
953 "OOB command to be run"),
954 ("timeout", constants.OOB_TIMEOUT, ht.TInt,
955 "Timeout before the OOB helper will be terminated"),
956 ("ignore_status", False, ht.TBool,
957 "Ignores the node offline status for power off"),
958 ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
959 "Time in seconds to wait between powering on nodes"),
961 # Fixme: Make it more specific with all the special cases in LUOobCommand
962 OP_RESULT = _TQueryResult
967 class OpNodeRemove(OpCode):
970 @type node_name: C{str}
971 @ivar node_name: The name of the node to remove. If the node still has
972 instances on it, the operation will fail.
975 OP_DSC_FIELD = "node_name"
982 class OpNodeAdd(OpCode):
983 """Add a node to the cluster.
985 @type node_name: C{str}
986 @ivar node_name: The name of the node to add. This can be a short name,
987 but it will be expanded to the FQDN.
988 @type primary_ip: IP address
989 @ivar primary_ip: The primary IP of the node. This will be ignored when the
990 opcode is submitted, but will be filled during the node
991 add (so it will be visible in the job query).
992 @type secondary_ip: IP address
993 @ivar secondary_ip: The secondary IP of the node. This needs to be passed
994 if the cluster has been initialized in 'dual-network'
995 mode, otherwise it must not be given.
997 @ivar readd: Whether to re-add an existing node to the cluster. If
998 this is not passed, then the operation will abort if the node
999 name is already in the cluster; use this parameter to 'repair'
1000 a node that had its configuration broken, or was reinstalled
1001 without removal from the cluster.
1003 @ivar group: The node group to which this node will belong.
1004 @type vm_capable: C{bool}
1005 @ivar vm_capable: The vm_capable node attribute
1006 @type master_capable: C{bool}
1007 @ivar master_capable: The master_capable node attribute
1010 OP_DSC_FIELD = "node_name"
1015 ("primary_ip", None, ht.NoType, "Primary IP address"),
1016 ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
1017 ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
1018 ("group", None, ht.TMaybeString, "Initial node group"),
1019 ("master_capable", None, ht.TMaybeBool,
1020 "Whether node can become master or master candidate"),
1021 ("vm_capable", None, ht.TMaybeBool,
1022 "Whether node can host instances"),
1023 ("ndparams", None, ht.TMaybeDict, "Node parameters"),
1025 OP_RESULT = ht.TNone
1028 class OpNodeQuery(OpCode):
1029 """Compute the list of nodes."""
1033 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1034 "Empty list to query all nodes, node names otherwise"),
1036 OP_RESULT = _TOldQueryResult
1039 class OpNodeQueryvols(OpCode):
1040 """Get list of volumes on node."""
1043 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1044 "Empty list to query all nodes, node names otherwise"),
1046 OP_RESULT = ht.TListOf(ht.TAny)
1049 class OpNodeQueryStorage(OpCode):
1050 """Get information on storage for node(s)."""
1054 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1055 ("name", None, ht.TMaybeString, "Storage name"),
1057 OP_RESULT = _TOldQueryResult
1060 class OpNodeModifyStorage(OpCode):
1061 """Modifies the properies of a storage unit"""
1066 ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1068 OP_RESULT = ht.TNone
1071 class OpRepairNodeStorage(OpCode):
1072 """Repairs the volume group on a node."""
1073 OP_DSC_FIELD = "node_name"
1078 _PIgnoreConsistency,
1080 OP_RESULT = ht.TNone
1083 class OpNodeSetParams(OpCode):
1084 """Change the parameters of a node."""
1085 OP_DSC_FIELD = "node_name"
1091 ("master_candidate", None, ht.TMaybeBool,
1092 "Whether the node should become a master candidate"),
1093 ("offline", None, ht.TMaybeBool,
1094 "Whether the node should be marked as offline"),
1095 ("drained", None, ht.TMaybeBool,
1096 "Whether the node should be marked as drained"),
1097 ("auto_promote", False, ht.TBool,
1098 "Whether node(s) should be promoted to master candidate if necessary"),
1099 ("master_capable", None, ht.TMaybeBool,
1100 "Denote whether node can become master or master candidate"),
1101 ("vm_capable", None, ht.TMaybeBool,
1102 "Denote whether node can host instances"),
1103 ("secondary_ip", None, ht.TMaybeString,
1104 "Change node's secondary IP address"),
1105 ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1106 ("powered", None, ht.TMaybeBool,
1107 "Whether the node should be marked as powered"),
1109 OP_RESULT = _TSetParamsResult
1112 class OpNodePowercycle(OpCode):
1113 """Tries to powercycle a node."""
1114 OP_DSC_FIELD = "node_name"
1119 OP_RESULT = ht.TMaybeString
1122 class OpNodeMigrate(OpCode):
1123 """Migrate all instances from a node."""
1124 OP_DSC_FIELD = "node_name"
1129 _PMigrationTargetNode,
1132 ("iallocator", None, ht.TMaybeString,
1133 "Iallocator for deciding the target node for shared-storage instances"),
1135 OP_RESULT = TJobIdListOnly
1138 class OpNodeEvacuate(OpCode):
1139 """Evacuate instances off a number of nodes."""
1140 OP_DSC_FIELD = "node_name"
1144 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1145 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1146 ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1147 "Node evacuation mode"),
1149 OP_RESULT = TJobIdListOnly
1154 class OpInstanceCreate(OpCode):
1155 """Create an instance.
1157 @ivar instance_name: Instance name
1158 @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1159 @ivar source_handshake: Signed handshake from source (remote import only)
1160 @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1161 @ivar source_instance_name: Previous name of instance (remote import only)
1162 @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1163 (remote import only)
1166 OP_DSC_FIELD = "instance_name"
1173 ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1174 ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1175 "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1176 " each disk definition must contain a ``%s`` value and"
1177 " can contain an optional ``%s`` value denoting the disk access mode"
1179 (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1180 constants.IDISK_MODE,
1181 " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1182 ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1184 ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1185 "Driver for file-backed disks"),
1186 ("file_storage_dir", None, ht.TMaybeString,
1187 "Directory for storing file-backed disks"),
1188 ("hvparams", ht.EmptyDict, ht.TDict,
1189 "Hypervisor parameters for instance, hypervisor-dependent"),
1190 ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1191 ("iallocator", None, ht.TMaybeString,
1192 "Iallocator for deciding which node(s) to use"),
1193 ("identify_defaults", False, ht.TBool,
1194 "Reset instance parameters to default if equal"),
1195 ("ip_check", True, ht.TBool, _PIpCheckDoc),
1196 ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1197 "Instance creation mode"),
1198 ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1199 "List of NIC (network interface) definitions, for example"
1200 " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1201 " contain the optional values %s" %
1203 ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1204 ("no_install", None, ht.TMaybeBool,
1205 "Do not install the OS (will disable automatic start)"),
1206 ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1207 ("os_type", None, ht.TMaybeString, "Operating system"),
1208 ("pnode", None, ht.TMaybeString, "Primary node"),
1209 ("snode", None, ht.TMaybeString, "Secondary node"),
1210 ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1211 "Signed handshake from source (remote import only)"),
1212 ("source_instance_name", None, ht.TMaybeString,
1213 "Source instance name (remote import only)"),
1214 ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1216 "How long source instance was given to shut down (remote import only)"),
1217 ("source_x509_ca", None, ht.TMaybeString,
1218 "Source X509 CA in PEM format (remote import only)"),
1219 ("src_node", None, ht.TMaybeString, "Source node for import"),
1220 ("src_path", None, ht.TMaybeString, "Source directory for import"),
1221 ("start", True, ht.TBool, "Whether to start instance after creation"),
1222 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1224 OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1227 class OpInstanceReinstall(OpCode):
1228 """Reinstall an instance's OS."""
1229 OP_DSC_FIELD = "instance_name"
1233 ("os_type", None, ht.TMaybeString, "Instance operating system"),
1234 ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1236 OP_RESULT = ht.TNone
1239 class OpInstanceRemove(OpCode):
1240 """Remove an instance."""
1241 OP_DSC_FIELD = "instance_name"
1245 ("ignore_failures", False, ht.TBool,
1246 "Whether to ignore failures during removal"),
1248 OP_RESULT = ht.TNone
1251 class OpInstanceRename(OpCode):
1252 """Rename an instance."""
1256 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1257 ("ip_check", False, ht.TBool, _PIpCheckDoc),
1259 OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1262 class OpInstanceStartup(OpCode):
1263 """Startup an instance."""
1264 OP_DSC_FIELD = "instance_name"
1268 _PIgnoreOfflineNodes,
1269 ("hvparams", ht.EmptyDict, ht.TDict,
1270 "Temporary hypervisor parameters, hypervisor-dependent"),
1271 ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1275 OP_RESULT = ht.TNone
1278 class OpInstanceShutdown(OpCode):
1279 """Shutdown an instance."""
1280 OP_DSC_FIELD = "instance_name"
1283 _PIgnoreOfflineNodes,
1284 ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1285 "How long to wait for instance to shut down"),
1288 OP_RESULT = ht.TNone
1291 class OpInstanceReboot(OpCode):
1292 """Reboot an instance."""
1293 OP_DSC_FIELD = "instance_name"
1297 ("ignore_secondaries", False, ht.TBool,
1298 "Whether to start the instance even if secondary disks are failing"),
1299 ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1300 "How to reboot instance"),
1302 OP_RESULT = ht.TNone
1305 class OpInstanceReplaceDisks(OpCode):
1306 """Replace the disks of an instance."""
1307 OP_DSC_FIELD = "instance_name"
1312 ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1313 "Replacement mode"),
1314 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1316 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1317 ("iallocator", None, ht.TMaybeString,
1318 "Iallocator for deciding new secondary node"),
1320 OP_RESULT = ht.TNone
1323 class OpInstanceFailover(OpCode):
1324 """Failover an instance."""
1325 OP_DSC_FIELD = "instance_name"
1329 _PIgnoreConsistency,
1330 _PMigrationTargetNode,
1332 ("iallocator", None, ht.TMaybeString,
1333 "Iallocator for deciding the target node for shared-storage instances"),
1335 OP_RESULT = ht.TNone
1338 class OpInstanceMigrate(OpCode):
1339 """Migrate an instance.
1341 This migrates (without shutting down an instance) to its secondary
1344 @ivar instance_name: the name of the instance
1345 @ivar mode: the migration mode (live, non-live or None for auto)
1348 OP_DSC_FIELD = "instance_name"
1353 _PMigrationTargetNode,
1356 ("cleanup", False, ht.TBool,
1357 "Whether a previously failed migration should be cleaned up"),
1358 ("iallocator", None, ht.TMaybeString,
1359 "Iallocator for deciding the target node for shared-storage instances"),
1360 ("allow_failover", False, ht.TBool,
1361 "Whether we can fallback to failover if migration is not possible"),
1363 OP_RESULT = ht.TNone
1366 class OpInstanceMove(OpCode):
1367 """Move an instance.
1369 This move (with shutting down an instance and data copying) to an
1372 @ivar instance_name: the name of the instance
1373 @ivar target_node: the destination node
1376 OP_DSC_FIELD = "instance_name"
1381 ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1382 _PIgnoreConsistency,
1384 OP_RESULT = ht.TNone
1387 class OpInstanceConsole(OpCode):
1388 """Connect to an instance's console."""
1389 OP_DSC_FIELD = "instance_name"
1393 OP_RESULT = ht.TDict
1396 class OpInstanceActivateDisks(OpCode):
1397 """Activate an instance's disks."""
1398 OP_DSC_FIELD = "instance_name"
1401 ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1403 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1404 ht.TItems([ht.TNonEmptyString,
1406 ht.TNonEmptyString])))
1409 class OpInstanceDeactivateDisks(OpCode):
1410 """Deactivate an instance's disks."""
1411 OP_DSC_FIELD = "instance_name"
1416 OP_RESULT = ht.TNone
1419 class OpInstanceRecreateDisks(OpCode):
1420 """Recreate an instance's disks."""
1422 ht.TAnd(ht.TIsLength(2),
1423 ht.TItems([ht.Comment("Disk index")(ht.TPositiveInt),
1424 ht.Comment("Parameters")(_TDiskParams)]))
1426 OP_DSC_FIELD = "instance_name"
1429 ("disks", ht.EmptyList,
1430 ht.TOr(ht.TListOf(ht.TPositiveInt), ht.TListOf(_TDiskChanges)),
1431 "List of disk indexes (deprecated) or a list of tuples containing a disk"
1432 " index and a possibly empty dictionary with disk parameter changes"),
1433 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1434 "New instance nodes, if relocation is desired"),
1436 OP_RESULT = ht.TNone
1439 class OpInstanceQuery(OpCode):
1440 """Compute the list of instances."""
1444 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1445 "Empty list to query all instances, instance names otherwise"),
1447 OP_RESULT = _TOldQueryResult
1450 class OpInstanceQueryData(OpCode):
1451 """Compute the run-time status of instances."""
1454 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1456 ("static", False, ht.TBool,
1457 "Whether to only return configuration data without querying"
1460 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1463 def _TestInstSetParamsModList(fn):
1464 """Generates a check for modification lists.
1468 # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1470 ht.TAnd(ht.TIsLength(2), ht.TItems([
1471 ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TPositiveInt),
1475 # New format, supporting adding/removing disks/NICs at arbitrary indices
1477 ht.TAnd(ht.TIsLength(3), ht.TItems([
1478 ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1479 ht.Comment("Disk index, can be negative, e.g. -1 for last disk")(ht.TInt),
1483 return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1484 ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1487 class OpInstanceSetParams(OpCode):
1488 """Change the parameters of an instance.
1491 TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1492 TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1494 OP_DSC_FIELD = "instance_name"
1500 ("nics", ht.EmptyList, TestNicModifications,
1501 "List of NIC changes. Each item is of the form ``(op, index, settings)``."
1502 " ``op`` is one of ``%s``, ``%s`` or ``%s``. ``index`` can be either -1 to"
1503 " refer to the last position, or a zero-based index number. A deprecated"
1504 " version of this parameter used the form ``(op, settings)``, where "
1505 " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1506 " ``%s`` to remove the last NIC or a number to modify the settings"
1507 " of the NIC with that index." %
1508 (constants.DDM_ADD, constants.DDM_MODIFY, constants.DDM_REMOVE,
1509 constants.DDM_ADD, constants.DDM_REMOVE)),
1510 ("disks", ht.EmptyList, TestDiskModifications,
1511 "List of disk changes. See ``nics``."),
1512 ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1513 ("runtime_mem", None, ht.TMaybeStrictPositiveInt, "New runtime memory"),
1514 ("hvparams", ht.EmptyDict, ht.TDict,
1515 "Per-instance hypervisor parameters, hypervisor-dependent"),
1516 ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1517 "Disk template for instance"),
1518 ("remote_node", None, ht.TMaybeString,
1519 "Secondary node (used when changing disk template)"),
1520 ("os_name", None, ht.TMaybeString,
1521 "Change instance's OS name. Does not reinstall the instance."),
1522 ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1523 ("wait_for_sync", True, ht.TBool,
1524 "Whether to wait for the disk to synchronize, when changing template"),
1525 ("offline", None, ht.TMaybeBool, "Whether to mark instance as offline"),
1527 OP_RESULT = _TSetParamsResult
1530 class OpInstanceGrowDisk(OpCode):
1531 """Grow a disk of an instance."""
1532 OP_DSC_FIELD = "instance_name"
1536 ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1537 ("amount", ht.NoDefault, ht.TInt,
1538 "Amount of disk space to add (megabytes)"),
1540 OP_RESULT = ht.TNone
1543 class OpInstanceChangeGroup(OpCode):
1544 """Moves an instance to another node group."""
1545 OP_DSC_FIELD = "instance_name"
1549 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1550 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1551 "Destination group names or UUIDs (defaults to \"all but current group\""),
1553 OP_RESULT = TJobIdListOnly
1556 # Node group opcodes
1558 class OpGroupAdd(OpCode):
1559 """Add a node group to the cluster."""
1560 OP_DSC_FIELD = "group_name"
1563 _PNodeGroupAllocPolicy,
1568 ("ipolicy", None, ht.TMaybeDict,
1569 "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1571 OP_RESULT = ht.TNone
1574 class OpGroupAssignNodes(OpCode):
1575 """Assign nodes to a node group."""
1576 OP_DSC_FIELD = "group_name"
1580 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1581 "List of nodes to assign"),
1583 OP_RESULT = ht.TNone
1586 class OpGroupQuery(OpCode):
1587 """Compute the list of node groups."""
1590 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1591 "Empty list to query all groups, group names otherwise"),
1593 OP_RESULT = _TOldQueryResult
1596 class OpGroupSetParams(OpCode):
1597 """Change the parameters of a node group."""
1598 OP_DSC_FIELD = "group_name"
1601 _PNodeGroupAllocPolicy,
1606 ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1608 OP_RESULT = _TSetParamsResult
1611 class OpGroupRemove(OpCode):
1612 """Remove a node group from the cluster."""
1613 OP_DSC_FIELD = "group_name"
1617 OP_RESULT = ht.TNone
1620 class OpGroupRename(OpCode):
1621 """Rename a node group in the cluster."""
1624 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1626 OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1629 class OpGroupEvacuate(OpCode):
1630 """Evacuate a node group in the cluster."""
1631 OP_DSC_FIELD = "group_name"
1635 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1636 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1637 "Destination group names or UUIDs"),
1639 OP_RESULT = TJobIdListOnly
1643 class OpOsDiagnose(OpCode):
1644 """Compute the list of guest operating systems."""
1647 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1648 "Which operating systems to diagnose"),
1650 OP_RESULT = _TOldQueryResult
1654 class OpBackupQuery(OpCode):
1655 """Compute the list of exported images."""
1658 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1659 "Empty list to query all nodes, node names otherwise"),
1661 OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1662 ht.TOr(ht.Comment("False on error")(ht.TBool),
1663 ht.TListOf(ht.TNonEmptyString)))
1666 class OpBackupPrepare(OpCode):
1667 """Prepares an instance export.
1669 @ivar instance_name: Instance name
1670 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1673 OP_DSC_FIELD = "instance_name"
1676 ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1679 OP_RESULT = ht.TOr(ht.TNone, ht.TDict)
1682 class OpBackupExport(OpCode):
1683 """Export an instance.
1685 For local exports, the export destination is the node name. For remote
1686 exports, the export destination is a list of tuples, each consisting of
1687 hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1688 the cluster domain secret over the value "${index}:${hostname}:${port}". The
1689 destination X509 CA must be a signed certificate.
1691 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1692 @ivar target_node: Export destination
1693 @ivar x509_key_name: X509 key to use (remote export only)
1694 @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1698 OP_DSC_FIELD = "instance_name"
1702 # TODO: Rename target_node as it changes meaning for different export modes
1703 # (e.g. "destination")
1704 ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1705 "Destination information, depends on export mode"),
1706 ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1707 ("remove_instance", False, ht.TBool,
1708 "Whether to remove instance after export"),
1709 ("ignore_remove_failures", False, ht.TBool,
1710 "Whether to ignore failures while removing instances"),
1711 ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1713 ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1714 "Name of X509 key (remote export only)"),
1715 ("destination_x509_ca", None, ht.TMaybeString,
1716 "Destination X509 CA (remote export only)"),
1719 ht.TAnd(ht.TIsLength(2), ht.TItems([
1720 ht.Comment("Finalizing status")(ht.TBool),
1721 ht.Comment("Status for every exported disk")(ht.TListOf(ht.TBool)),
1725 class OpBackupRemove(OpCode):
1726 """Remove an instance's export."""
1727 OP_DSC_FIELD = "instance_name"
1731 OP_RESULT = ht.TNone
1735 class OpTagsGet(OpCode):
1736 """Returns the tags of the given object."""
1737 OP_DSC_FIELD = "name"
1740 # Name is only meaningful for nodes and instances
1741 ("name", ht.NoDefault, ht.TMaybeString, None),
1743 OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1746 class OpTagsSearch(OpCode):
1747 """Searches the tags in the cluster for a given pattern."""
1748 OP_DSC_FIELD = "pattern"
1750 ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1752 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1758 class OpTagsSet(OpCode):
1759 """Add a list of tags on a given object."""
1763 # Name is only meaningful for nodes and instances
1764 ("name", ht.NoDefault, ht.TMaybeString, None),
1766 OP_RESULT = ht.TNone
1769 class OpTagsDel(OpCode):
1770 """Remove a list of tags from a given object."""
1774 # Name is only meaningful for nodes and instances
1775 ("name", ht.NoDefault, ht.TMaybeString, None),
1777 OP_RESULT = ht.TNone
1781 class OpTestDelay(OpCode):
1782 """Sleeps for a configured amount of time.
1784 This is used just for debugging and testing.
1787 - duration: the time to sleep
1788 - on_master: if true, sleep on the master
1789 - on_nodes: list of nodes in which to sleep
1791 If the on_master parameter is true, it will execute a sleep on the
1792 master (before any node sleep).
1794 If the on_nodes list is not empty, it will sleep on those nodes
1795 (after the sleep on the master, if that is enabled).
1797 As an additional feature, the case of duration < 0 will be reported
1798 as an execution error, so this opcode can be used as a failure
1799 generator. The case of duration == 0 will not be treated specially.
1802 OP_DSC_FIELD = "duration"
1804 ("duration", ht.NoDefault, ht.TNumber, None),
1805 ("on_master", True, ht.TBool, None),
1806 ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1807 ("repeat", 0, ht.TPositiveInt, None),
1811 class OpTestAllocator(OpCode):
1812 """Allocator framework testing.
1814 This opcode has two modes:
1815 - gather and return allocator input for a given mode (allocate new
1816 or replace secondary) and a given instance definition (direction
1818 - run a selected allocator for a given operation (as above) and
1819 return the allocator output (direction 'out')
1822 OP_DSC_FIELD = "allocator"
1824 ("direction", ht.NoDefault,
1825 ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1826 ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1827 ("name", ht.NoDefault, ht.TNonEmptyString, None),
1828 ("nics", ht.NoDefault,
1829 ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
1832 ht.TOr(ht.TNone, ht.TNonEmptyString))),
1834 ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1835 ("hypervisor", None, ht.TMaybeString, None),
1836 ("allocator", None, ht.TMaybeString, None),
1837 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1838 ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1839 ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1840 ("os", None, ht.TMaybeString, None),
1841 ("disk_template", None, ht.TMaybeString, None),
1842 ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1844 ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1845 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1849 class OpTestJqueue(OpCode):
1850 """Utility opcode to test some aspects of the job queue.
1854 ("notify_waitlock", False, ht.TBool, None),
1855 ("notify_exec", False, ht.TBool, None),
1856 ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1857 ("fail", False, ht.TBool, None),
1861 class OpTestDummy(OpCode):
1862 """Utility opcode used by unittests.
1866 ("result", ht.NoDefault, ht.NoType, None),
1867 ("messages", ht.NoDefault, ht.NoType, None),
1868 ("fail", ht.NoDefault, ht.NoType, None),
1869 ("submit_jobs", None, ht.NoType, None),
1875 """Returns list of all defined opcodes.
1877 Does not eliminate duplicates by C{OP_ID}.
1880 return [v for v in globals().values()
1881 if (isinstance(v, type) and issubclass(v, OpCode) and
1882 hasattr(v, "OP_ID") and v is not OpCode)]
1885 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())