4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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
40 from ganeti import constants
41 from ganeti import errors
43 from ganeti import objects
44 from ganeti import outils
47 # Common opcode attributes
49 #: output fields for a query operation
50 _POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
51 "Selected output fields")
53 #: the shutdown timeout
55 ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TNonNegativeInt,
56 "How long to wait for instance to shut down")
58 #: the force parameter
59 _PForce = ("force", False, ht.TBool, "Whether to force the operation")
61 #: a required instance name (for single-instance LUs)
62 _PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString,
65 #: Whether to ignore offline nodes
66 _PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
67 "Whether to ignore offline nodes")
69 #: a required node name (for single-node LUs)
70 _PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
72 #: a required node group name (for single-group LUs)
73 _PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
75 #: Migration type (live/non-live)
76 _PMigrationMode = ("mode", None,
77 ht.TMaybe(ht.TElemOf(constants.HT_MIGRATION_MODES)),
80 #: Obsolete 'live' migration mode (boolean)
81 _PMigrationLive = ("live", None, ht.TMaybeBool,
82 "Legacy setting for live migration, do not use")
85 _PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES),
88 #: List of tag strings
89 _PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
92 _PForceVariant = ("force_variant", False, ht.TBool,
93 "Whether to force an unknown OS variant")
95 _PWaitForSync = ("wait_for_sync", True, ht.TBool,
96 "Whether to wait for the disk to synchronize")
98 _PWaitForSyncFalse = ("wait_for_sync", False, ht.TBool,
99 "Whether to wait for the disk to synchronize"
100 " (defaults to false)")
102 _PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
103 "Whether to ignore disk consistency")
105 _PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
107 _PUseLocking = ("use_locking", False, ht.TBool,
108 "Whether to use synchronization")
110 _PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
112 _PNodeGroupAllocPolicy = \
113 ("alloc_policy", None,
114 ht.TMaybe(ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
115 "Instance allocation policy")
117 _PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
118 "Default node parameters for group")
120 _PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
121 "Resource(s) to query for")
123 _PEarlyRelease = ("early_release", False, ht.TBool,
124 "Whether to release locks as soon as possible")
126 _PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
128 #: Do not remember instance state changes
129 _PNoRemember = ("no_remember", False, ht.TBool,
130 "Do not remember the state change")
132 #: Target node for instance migration/failover
133 _PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
134 "Target node for shared-storage instances")
136 _PStartupPaused = ("startup_paused", False, ht.TBool,
137 "Pause instance at startup")
139 _PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
141 # Parameters for cluster verification
142 _PDebugSimulateErrors = ("debug_simulate_errors", False, ht.TBool,
143 "Whether to simulate errors (useful for debugging)")
144 _PErrorCodes = ("error_codes", False, ht.TBool, "Error codes")
145 _PSkipChecks = ("skip_checks", ht.EmptyList,
146 ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)),
147 "Which checks to skip")
148 _PIgnoreErrors = ("ignore_errors", ht.EmptyList,
149 ht.TListOf(ht.TElemOf(constants.CV_ALL_ECODES_STRINGS)),
150 "List of error codes that should be treated as warnings")
155 ht.TMaybe(ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict)),
156 "Disk templates' parameter defaults")
158 # Parameters for node resource model
159 _PHvState = ("hv_state", None, ht.TMaybeDict, "Set hypervisor states")
160 _PDiskState = ("disk_state", None, ht.TMaybeDict, "Set disk states")
162 #: Opportunistic locking
163 _POpportunisticLocking = \
164 ("opportunistic_locking", False, ht.TBool,
165 ("Whether to employ opportunistic locking for nodes, meaning nodes"
166 " already locked by another opcode won't be considered for instance"
167 " allocation (only when an iallocator is used)"))
169 _PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
170 "Whether to ignore ipolicy violations")
172 # Allow runtime changes while migrating
173 _PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
174 "Allow runtime changes (eg. memory ballooning)")
176 #: IAllocator field builder
177 _PIAllocFromDesc = lambda desc: ("iallocator", None, ht.TMaybeString, desc)
179 #: a required network name
180 _PNetworkName = ("network_name", ht.NoDefault, ht.TNonEmptyString,
184 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
185 "Destination group names or UUIDs (defaults to \"all but current group\")")
187 #: OP_ID conversion regular expression
188 _OPID_RE = re.compile("([a-z])([A-Z])")
190 #: Utility function for L{OpClusterSetParams}
191 _TestClusterOsListItem = \
192 ht.TAnd(ht.TIsLength(2), ht.TItems([
193 ht.TElemOf(constants.DDMS_VALUES),
197 _TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
199 # TODO: Generate check from constants.INIC_PARAMS_TYPES
200 #: Utility function for testing NIC definitions
202 ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
205 _TSetParamsResultItemItems = [
206 ht.Comment("name of changed parameter")(ht.TNonEmptyString),
207 ht.Comment("new value")(ht.TAny),
210 _TSetParamsResult = \
211 ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
212 ht.TItems(_TSetParamsResultItemItems)))
214 # In the disks option we can provide arbitrary parameters too, which
215 # we may not be able to validate at this level, so we just check the
216 # format of the dict here and the checks concerning IDISK_PARAMS will
217 # happen at the LU level
219 ht.Comment("Disk parameters")(ht.TDictOf(ht.TNonEmptyString,
220 ht.TOr(ht.TNonEmptyString, ht.TInt)))
223 ht.TListOf(ht.TAnd(ht.TIsLength(2),
224 ht.TItems([ht.TElemOf(constants.RS_ALL),
227 _TQueryResult = ht.TListOf(_TQueryRow)
229 _TOldQueryRow = ht.TListOf(ht.TAny)
231 _TOldQueryResult = ht.TListOf(_TOldQueryRow)
241 #: Attribute name for dependencies
242 DEPEND_ATTR = "depends"
244 #: Attribute name for comment
245 COMMENT_ATTR = "comment"
248 def _NameComponents(name):
249 """Split an opcode class name into its components
252 @param name: the class name, as OpXxxYyy
253 @rtype: array of strings
254 @return: the components of the name
257 assert name.startswith("Op")
258 # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
259 # consume any input, and hence we would just have all the elements
260 # in the list, one by one; but it seems that split doesn't work on
261 # non-consuming input, hence we have to process the input string a
263 name = _OPID_RE.sub(r"\1,\2", name)
264 elems = name.split(",")
269 """Convert an opcode class name to an OP_ID.
272 @param name: the class name, as OpXxxYyy
274 @return: the name in the OP_XXXX_YYYY format
277 if not name.startswith("Op"):
279 return "_".join(n.upper() for n in _NameComponents(name))
282 def NameToReasonSrc(name):
283 """Convert an opcode class name to a source string for the reason trail
286 @param name: the class name, as OpXxxYyy
288 @return: the name in the OP_XXXX_YYYY format
291 if not name.startswith("Op"):
293 return "%s:%s" % (constants.OPCODE_REASON_SRC_OPCODE,
294 "_".join(n.lower() for n in _NameComponents(name)))
297 def _GenerateObjectTypeCheck(obj, fields_types):
298 """Helper to generate type checks for objects.
300 @param obj: The object to generate type checks
301 @param fields_types: The fields and their types as a dict
302 @return: A ht type check function
305 assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
306 "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
307 return ht.TStrictDict(True, True, fields_types)
311 _GenerateObjectTypeCheck(objects.QueryFieldDefinition, {
312 "name": ht.TNonEmptyString,
313 "title": ht.TNonEmptyString,
314 "kind": ht.TElemOf(constants.QFT_ALL),
315 "doc": ht.TNonEmptyString,
319 def RequireFileStorage():
320 """Checks that file storage is enabled.
322 While it doesn't really fit into this module, L{utils} was deemed too large
323 of a dependency to be imported for just one or two functions.
325 @raise errors.OpPrereqError: when file storage is disabled
328 if not constants.ENABLE_FILE_STORAGE:
329 raise errors.OpPrereqError("File storage disabled at configure time",
333 def RequireSharedFileStorage():
334 """Checks that shared file storage is enabled.
336 While it doesn't really fit into this module, L{utils} was deemed too large
337 of a dependency to be imported for just one or two functions.
339 @raise errors.OpPrereqError: when shared file storage is disabled
342 if not constants.ENABLE_SHARED_FILE_STORAGE:
343 raise errors.OpPrereqError("Shared file storage disabled at"
344 " configure time", errors.ECODE_INVAL)
347 @ht.WithDesc("CheckFileStorage")
348 def _CheckFileStorage(value):
349 """Ensures file storage is enabled if used.
352 if value == constants.DT_FILE:
354 elif value == constants.DT_SHARED_FILE:
355 RequireSharedFileStorage()
359 def _BuildDiskTemplateCheck(accept_none):
360 """Builds check for disk template.
362 @type accept_none: bool
363 @param accept_none: whether to accept None as a correct value
367 template_check = ht.TElemOf(constants.DISK_TEMPLATES)
370 template_check = ht.TMaybe(template_check)
372 return ht.TAnd(template_check, _CheckFileStorage)
375 def _CheckStorageType(storage_type):
376 """Ensure a given storage type is valid.
379 if storage_type not in constants.VALID_STORAGE_TYPES:
380 raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
382 if storage_type == constants.ST_FILE:
383 # TODO: What about shared file storage?
388 #: Storage type parameter
389 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
393 @ht.WithDesc("IPv4 network")
394 def _CheckCIDRNetNotation(value):
395 """Ensure a given CIDR notation type is valid.
399 ipaddr.IPv4Network(value)
400 except ipaddr.AddressValueError:
405 @ht.WithDesc("IPv4 address")
406 def _CheckCIDRAddrNotation(value):
407 """Ensure a given CIDR notation type is valid.
411 ipaddr.IPv4Address(value)
412 except ipaddr.AddressValueError:
417 @ht.WithDesc("IPv6 address")
418 def _CheckCIDR6AddrNotation(value):
419 """Ensure a given CIDR notation type is valid.
423 ipaddr.IPv6Address(value)
424 except ipaddr.AddressValueError:
429 @ht.WithDesc("IPv6 network")
430 def _CheckCIDR6NetNotation(value):
431 """Ensure a given CIDR notation type is valid.
435 ipaddr.IPv6Network(value)
436 except ipaddr.AddressValueError:
441 _TIpAddress4 = ht.TAnd(ht.TString, _CheckCIDRAddrNotation)
442 _TIpAddress6 = ht.TAnd(ht.TString, _CheckCIDR6AddrNotation)
443 _TIpNetwork4 = ht.TAnd(ht.TString, _CheckCIDRNetNotation)
444 _TIpNetwork6 = ht.TAnd(ht.TString, _CheckCIDR6NetNotation)
445 _TMaybeAddr4List = ht.TMaybe(ht.TListOf(_TIpAddress4))
448 class _AutoOpParamSlots(outils.AutoSlots):
449 """Meta class for opcode definitions.
452 def __new__(mcs, name, bases, attrs):
453 """Called when a class should be created.
455 @param mcs: The meta class
456 @param name: Name of created class
457 @param bases: Base classes
459 @param attrs: Class attributes
462 assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
464 slots = mcs._GetSlots(attrs)
465 assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
466 "Class '%s' uses unknown field in OP_DSC_FIELD" % name
467 assert ("OP_DSC_FORMATTER" not in attrs or
468 callable(attrs["OP_DSC_FORMATTER"])), \
469 ("Class '%s' uses non-callable in OP_DSC_FORMATTER (%s)" %
470 (name, type(attrs["OP_DSC_FORMATTER"])))
472 attrs["OP_ID"] = _NameToId(name)
474 return outils.AutoSlots.__new__(mcs, name, bases, attrs)
477 def _GetSlots(mcs, attrs):
478 """Build the slots out of OP_PARAMS.
481 # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
482 params = attrs.setdefault("OP_PARAMS", [])
484 # Use parameter names as slots
485 return [pname for (pname, _, _, _) in params]
488 class BaseOpCode(outils.ValidatedSlots):
489 """A simple serializable object.
491 This object serves as a parent class for OpCode without any custom
495 # pylint: disable=E1101
496 # as OP_ID is dynamically defined
497 __metaclass__ = _AutoOpParamSlots
499 def __getstate__(self):
500 """Generic serializer.
502 This method just returns the contents of the instance as a
506 @return: the instance attributes and their values
510 for name in self.GetAllSlots():
511 if hasattr(self, name):
512 state[name] = getattr(self, name)
515 def __setstate__(self, state):
516 """Generic unserializer.
518 This method just restores from the serialized state the attributes
519 of the current instance.
521 @param state: the serialized opcode data
525 if not isinstance(state, dict):
526 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
529 for name in self.GetAllSlots():
530 if name not in state and hasattr(self, name):
534 setattr(self, name, state[name])
537 def GetAllParams(cls):
538 """Compute list of all parameters for an opcode.
542 for parent in cls.__mro__:
543 slots.extend(getattr(parent, "OP_PARAMS", []))
546 def Validate(self, set_defaults): # pylint: disable=W0221
547 """Validate opcode parameters, optionally setting default values.
549 @type set_defaults: bool
550 @param set_defaults: Whether to set default values
551 @raise errors.OpPrereqError: When a parameter value doesn't match
555 for (attr_name, default, test, _) in self.GetAllParams():
556 assert test == ht.NoType or callable(test)
558 if not hasattr(self, attr_name):
559 if default == ht.NoDefault:
560 raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
561 (self.OP_ID, attr_name),
564 if callable(default):
568 setattr(self, attr_name, dval)
570 if test == ht.NoType:
574 if set_defaults or hasattr(self, attr_name):
575 attr_val = getattr(self, attr_name)
576 if not test(attr_val):
577 logging.error("OpCode %s, parameter %s, has invalid type %s/value"
578 " '%s' expecting type %s",
579 self.OP_ID, attr_name, type(attr_val), attr_val, test)
580 raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
581 (self.OP_ID, attr_name),
585 def _BuildJobDepCheck(relative):
586 """Builds check for job dependencies (L{DEPEND_ATTR}).
589 @param relative: Whether to accept relative job IDs (negative)
594 job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
599 ht.TAnd(ht.TOr(ht.TList, ht.TTuple),
602 ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
604 return ht.TMaybeListOf(job_dep)
607 TNoRelativeJobDependencies = _BuildJobDepCheck(False)
609 #: List of submission status and job ID as returned by C{SubmitManyJobs}
611 ht.TAnd(ht.TIsLength(2),
612 ht.TItems([ht.Comment("success")(ht.TBool),
613 ht.Comment("Job ID if successful, error message"
614 " otherwise")(ht.TOr(ht.TString,
616 TJobIdList = ht.TListOf(_TJobIdListItem)
618 #: Result containing only list of submitted jobs
619 TJobIdListOnly = ht.TStrictDict(True, True, {
620 constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
624 class OpCode(BaseOpCode):
627 This is the root of the actual OpCode hierarchy. All clases derived
628 from this class should override OP_ID.
630 @cvar OP_ID: The ID of this opcode. This should be unique amongst all
631 children of this class.
632 @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
633 string returned by Summary(); see the docstring of that
635 @cvar OP_DSC_FORMATTER: A callable that should format the OP_DSC_FIELD; if
636 not present, then the field will be simply converted
638 @cvar OP_PARAMS: List of opcode attributes, the default values they should
639 get if not already defined, and types they must match.
640 @cvar OP_RESULT: Callable to verify opcode result
641 @cvar WITH_LU: Boolean that specifies whether this should be included in
642 mcpu's dispatch table
643 @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
645 @ivar priority: Opcode priority for queue
648 # pylint: disable=E1101
649 # as OP_ID is dynamically defined
652 ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
653 ("debug_level", None, ht.TMaybe(ht.TNonNegativeInt), "Debug level"),
654 ("priority", constants.OP_PRIO_DEFAULT,
655 ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
656 (DEPEND_ATTR, None, _BuildJobDepCheck(True),
657 "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
658 " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
660 (COMMENT_ATTR, None, ht.TMaybeString,
661 "Comment describing the purpose of the opcode"),
662 (constants.OPCODE_REASON, None, ht.TMaybeList,
663 "The reason trail, describing why the OpCode is executed"),
667 def __getstate__(self):
668 """Specialized getstate for opcodes.
670 This method adds to the state dictionary the OP_ID of the class,
671 so that on unload we can identify the correct class for
672 instantiating the opcode.
675 @return: the state as a dictionary
678 data = BaseOpCode.__getstate__(self)
679 data["OP_ID"] = self.OP_ID
683 def LoadOpCode(cls, data):
684 """Generic load opcode method.
686 The method identifies the correct opcode class from the dict-form
687 by looking for a OP_ID key, if this is not found, or its value is
688 not available in this module as a child of this class, we fail.
691 @param data: the serialized opcode
694 if not isinstance(data, dict):
695 raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
696 if "OP_ID" not in data:
697 raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
698 op_id = data["OP_ID"]
700 if op_id in OP_MAPPING:
701 op_class = OP_MAPPING[op_id]
703 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
706 new_data = data.copy()
707 del new_data["OP_ID"]
708 op.__setstate__(new_data)
712 """Generates a summary description of this opcode.
714 The summary is the value of the OP_ID attribute (without the "OP_"
715 prefix), plus the value of the OP_DSC_FIELD attribute, if one was
716 defined; this field should allow to easily identify the operation
717 (for an instance creation job, e.g., it would be the instance
721 assert self.OP_ID is not None and len(self.OP_ID) > 3
722 # all OP_ID start with OP_, we remove that
724 field_name = getattr(self, "OP_DSC_FIELD", None)
726 field_value = getattr(self, field_name, None)
727 field_formatter = getattr(self, "OP_DSC_FORMATTER", None)
728 if callable(field_formatter):
729 field_value = field_formatter(field_value)
730 elif isinstance(field_value, (list, tuple)):
731 field_value = ",".join(str(i) for i in field_value)
732 txt = "%s(%s)" % (txt, field_value)
735 def TinySummary(self):
736 """Generates a compact summary description of the opcode.
739 assert self.OP_ID.startswith("OP_")
741 text = self.OP_ID[3:]
743 for (prefix, supplement) in _SUMMARY_PREFIX.items():
744 if text.startswith(prefix):
745 return supplement + text[len(prefix):]
752 class OpClusterPostInit(OpCode):
753 """Post cluster initialization.
755 This opcode does not touch the cluster at all. Its purpose is to run hooks
756 after the cluster has been initialized.
762 class OpClusterDestroy(OpCode):
763 """Destroy the cluster.
765 This opcode has no other parameters. All the state is irreversibly
766 lost after the execution of this opcode.
769 OP_RESULT = ht.TNonEmptyString
772 class OpClusterQuery(OpCode):
773 """Query cluster information."""
774 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
777 class OpClusterVerify(OpCode):
778 """Submits all jobs necessary to verify the cluster.
782 _PDebugSimulateErrors,
787 ("group_name", None, ht.TMaybeString, "Group to verify"),
789 OP_RESULT = TJobIdListOnly
792 class OpClusterVerifyConfig(OpCode):
793 """Verify the cluster config.
797 _PDebugSimulateErrors,
805 class OpClusterVerifyGroup(OpCode):
806 """Run verify on a node group from the cluster.
808 @type skip_checks: C{list}
809 @ivar skip_checks: steps to be skipped from the verify process; this
810 needs to be a subset of
811 L{constants.VERIFY_OPTIONAL_CHECKS}; currently
812 only L{constants.VERIFY_NPLUSONE_MEM} can be passed
815 OP_DSC_FIELD = "group_name"
818 _PDebugSimulateErrors,
827 class OpClusterVerifyDisks(OpCode):
828 """Verify the cluster disks.
831 OP_RESULT = TJobIdListOnly
834 class OpGroupVerifyDisks(OpCode):
835 """Verifies the status of all disks in a node group.
837 Result: a tuple of three elements:
838 - dict of node names with issues (values: error msg)
839 - list of instances with degraded disks (that should be activated)
840 - dict of instances with missing logical volumes (values: (node, vol)
841 pairs with details about the missing volumes)
843 In normal operation, all lists should be empty. A non-empty instance
844 list (3rd element of the result) is still ok (errors were fixed) but
845 non-empty node list means some node is down, and probably there are
846 unfixable drbd errors.
848 Note that only instances that are drbd-based are taken into
849 consideration. This might need to be revisited in the future.
852 OP_DSC_FIELD = "group_name"
857 ht.TAnd(ht.TIsLength(3),
858 ht.TItems([ht.TDictOf(ht.TString, ht.TString),
859 ht.TListOf(ht.TString),
860 ht.TDictOf(ht.TString,
861 ht.TListOf(ht.TListOf(ht.TString)))]))
864 class OpClusterRepairDiskSizes(OpCode):
865 """Verify the disk sizes of the instances and fixes configuration
868 Parameters: optional instances list, in case we want to restrict the
869 checks to only a subset of the instances.
871 Result: a list of tuples, (instance, disk, new-size) for changed
874 In normal operation, the list should be empty.
876 @type instances: list
877 @ivar instances: the list of instances to check, or empty for all instances
881 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
883 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
884 ht.TItems([ht.TNonEmptyString,
886 ht.TNonNegativeInt])))
889 class OpClusterConfigQuery(OpCode):
890 """Query cluster configuration values."""
894 OP_RESULT = ht.TListOf(ht.TAny)
897 class OpClusterRename(OpCode):
898 """Rename the cluster.
901 @ivar name: The new name of the cluster. The name and/or the master IP
902 address will be changed to match the new name and its IP
906 OP_DSC_FIELD = "name"
908 ("name", ht.NoDefault, ht.TNonEmptyString, None),
910 OP_RESULT = ht.TNonEmptyString
913 class OpClusterSetParams(OpCode):
914 """Change the parameters of the cluster.
916 @type vg_name: C{str} or C{None}
917 @ivar vg_name: The new volume group name or None to disable LVM usage.
923 ("vg_name", None, ht.TMaybe(ht.TString), "Volume group name"),
924 ("enabled_hypervisors", None,
925 ht.TMaybe(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)),
927 "List of enabled hypervisors"),
929 ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
930 "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
931 ("beparams", None, ht.TMaybeDict,
932 "Cluster-wide backend parameter defaults"),
933 ("os_hvp", None, ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
934 "Cluster-wide per-OS hypervisor parameter defaults"),
936 ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
937 "Cluster-wide OS parameter defaults"),
939 ("candidate_pool_size", None, ht.TMaybe(ht.TPositiveInt),
940 "Master candidate pool size"),
941 ("uid_pool", None, ht.NoType,
942 "Set UID pool, must be list of lists describing UID ranges (two items,"
943 " start and end inclusive)"),
944 ("add_uids", None, ht.NoType,
945 "Extend UID pool, must be list of lists describing UID ranges (two"
946 " items, start and end inclusive) to be added"),
947 ("remove_uids", None, ht.NoType,
948 "Shrink UID pool, must be list of lists describing UID ranges (two"
949 " items, start and end inclusive) to be removed"),
950 ("maintain_node_health", None, ht.TMaybeBool,
951 "Whether to automatically maintain node health"),
952 ("prealloc_wipe_disks", None, ht.TMaybeBool,
953 "Whether to wipe disks before allocating them to instances"),
954 ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
955 ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
956 ("ipolicy", None, ht.TMaybeDict,
957 "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
958 ("drbd_helper", None, ht.TMaybe(ht.TString), "DRBD helper program"),
959 ("default_iallocator", None, ht.TMaybe(ht.TString),
960 "Default iallocator for cluster"),
961 ("master_netdev", None, ht.TMaybe(ht.TString),
962 "Master network device"),
963 ("master_netmask", None, ht.TMaybe(ht.TNonNegativeInt),
964 "Netmask of the master IP"),
965 ("reserved_lvs", None, ht.TMaybeListOf(ht.TNonEmptyString),
966 "List of reserved LVs"),
967 ("hidden_os", None, _TestClusterOsList,
968 "Modify list of hidden operating systems: each modification must have"
969 " two items, the operation and the OS name; the operation can be"
970 " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
971 ("blacklisted_os", None, _TestClusterOsList,
972 "Modify list of blacklisted operating systems: each modification must"
973 " have two items, the operation and the OS name; the operation can be"
974 " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
975 ("use_external_mip_script", None, ht.TMaybeBool,
976 "Whether to use an external master IP address setup script"),
977 ("enabled_disk_templates", None,
978 ht.TMaybe(ht.TAnd(ht.TListOf(ht.TElemOf(constants.DISK_TEMPLATES)),
980 "List of enabled disk templates"),
985 class OpClusterRedistConf(OpCode):
986 """Force a full push of the cluster configuration.
992 class OpClusterActivateMasterIp(OpCode):
993 """Activate the master IP on the master node.
999 class OpClusterDeactivateMasterIp(OpCode):
1000 """Deactivate the master IP on the master node.
1003 OP_RESULT = ht.TNone
1006 class OpQuery(OpCode):
1007 """Query for resources/items.
1009 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
1010 @ivar fields: List of fields to retrieve
1011 @ivar qfilter: Query filter
1014 OP_DSC_FIELD = "what"
1018 ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1019 "Requested fields"),
1020 ("qfilter", None, ht.TMaybe(ht.TList),
1024 _GenerateObjectTypeCheck(objects.QueryResponse, {
1025 "fields": ht.TListOf(_TQueryFieldDef),
1026 "data": _TQueryResult,
1030 class OpQueryFields(OpCode):
1031 """Query for available resource/item fields.
1033 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
1034 @ivar fields: List of fields to retrieve
1037 OP_DSC_FIELD = "what"
1040 ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
1041 "Requested fields; if not given, all are returned"),
1044 _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
1045 "fields": ht.TListOf(_TQueryFieldDef),
1049 class OpOobCommand(OpCode):
1050 """Interact with OOB."""
1052 ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1053 "List of nodes to run the OOB command against"),
1054 ("command", ht.NoDefault, ht.TElemOf(constants.OOB_COMMANDS),
1055 "OOB command to be run"),
1056 ("timeout", constants.OOB_TIMEOUT, ht.TInt,
1057 "Timeout before the OOB helper will be terminated"),
1058 ("ignore_status", False, ht.TBool,
1059 "Ignores the node offline status for power off"),
1060 ("power_delay", constants.OOB_POWER_DELAY, ht.TNonNegativeFloat,
1061 "Time in seconds to wait between powering on nodes"),
1063 # Fixme: Make it more specific with all the special cases in LUOobCommand
1064 OP_RESULT = _TQueryResult
1067 class OpRestrictedCommand(OpCode):
1068 """Runs a restricted command on node(s).
1073 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1074 "Nodes on which the command should be run (at least one)"),
1075 ("command", ht.NoDefault, ht.TNonEmptyString,
1076 "Command name (no parameters)"),
1080 ht.Comment("success")(ht.TBool),
1081 ht.Comment("output or error message")(ht.TString),
1085 ht.TListOf(ht.TAnd(ht.TIsLength(len(_RESULT_ITEMS)),
1086 ht.TItems(_RESULT_ITEMS)))
1091 class OpNodeRemove(OpCode):
1094 @type node_name: C{str}
1095 @ivar node_name: The name of the node to remove. If the node still has
1096 instances on it, the operation will fail.
1099 OP_DSC_FIELD = "node_name"
1103 OP_RESULT = ht.TNone
1106 class OpNodeAdd(OpCode):
1107 """Add a node to the cluster.
1109 @type node_name: C{str}
1110 @ivar node_name: The name of the node to add. This can be a short name,
1111 but it will be expanded to the FQDN.
1112 @type primary_ip: IP address
1113 @ivar primary_ip: The primary IP of the node. This will be ignored when the
1114 opcode is submitted, but will be filled during the node
1115 add (so it will be visible in the job query).
1116 @type secondary_ip: IP address
1117 @ivar secondary_ip: The secondary IP of the node. This needs to be passed
1118 if the cluster has been initialized in 'dual-network'
1119 mode, otherwise it must not be given.
1120 @type readd: C{bool}
1121 @ivar readd: Whether to re-add an existing node to the cluster. If
1122 this is not passed, then the operation will abort if the node
1123 name is already in the cluster; use this parameter to 'repair'
1124 a node that had its configuration broken, or was reinstalled
1125 without removal from the cluster.
1127 @ivar group: The node group to which this node will belong.
1128 @type vm_capable: C{bool}
1129 @ivar vm_capable: The vm_capable node attribute
1130 @type master_capable: C{bool}
1131 @ivar master_capable: The master_capable node attribute
1134 OP_DSC_FIELD = "node_name"
1139 ("primary_ip", None, ht.NoType, "Primary IP address"),
1140 ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
1141 ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
1142 ("group", None, ht.TMaybeString, "Initial node group"),
1143 ("master_capable", None, ht.TMaybeBool,
1144 "Whether node can become master or master candidate"),
1145 ("vm_capable", None, ht.TMaybeBool,
1146 "Whether node can host instances"),
1147 ("ndparams", None, ht.TMaybeDict, "Node parameters"),
1149 OP_RESULT = ht.TNone
1152 class OpNodeQuery(OpCode):
1153 """Compute the list of nodes."""
1157 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1158 "Empty list to query all nodes, node names otherwise"),
1160 OP_RESULT = _TOldQueryResult
1163 class OpNodeQueryvols(OpCode):
1164 """Get list of volumes on node."""
1167 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1168 "Empty list to query all nodes, node names otherwise"),
1170 OP_RESULT = ht.TListOf(ht.TAny)
1173 class OpNodeQueryStorage(OpCode):
1174 """Get information on storage for node(s)."""
1178 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1179 ("name", None, ht.TMaybeString, "Storage name"),
1181 OP_RESULT = _TOldQueryResult
1184 class OpNodeModifyStorage(OpCode):
1185 """Modifies the properies of a storage unit"""
1186 OP_DSC_FIELD = "node_name"
1191 ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1193 OP_RESULT = ht.TNone
1196 class OpRepairNodeStorage(OpCode):
1197 """Repairs the volume group on a node."""
1198 OP_DSC_FIELD = "node_name"
1203 _PIgnoreConsistency,
1205 OP_RESULT = ht.TNone
1208 class OpNodeSetParams(OpCode):
1209 """Change the parameters of a node."""
1210 OP_DSC_FIELD = "node_name"
1216 ("master_candidate", None, ht.TMaybeBool,
1217 "Whether the node should become a master candidate"),
1218 ("offline", None, ht.TMaybeBool,
1219 "Whether the node should be marked as offline"),
1220 ("drained", None, ht.TMaybeBool,
1221 "Whether the node should be marked as drained"),
1222 ("auto_promote", False, ht.TBool,
1223 "Whether node(s) should be promoted to master candidate if necessary"),
1224 ("master_capable", None, ht.TMaybeBool,
1225 "Denote whether node can become master or master candidate"),
1226 ("vm_capable", None, ht.TMaybeBool,
1227 "Denote whether node can host instances"),
1228 ("secondary_ip", None, ht.TMaybeString,
1229 "Change node's secondary IP address"),
1230 ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1231 ("powered", None, ht.TMaybeBool,
1232 "Whether the node should be marked as powered"),
1234 OP_RESULT = _TSetParamsResult
1237 class OpNodePowercycle(OpCode):
1238 """Tries to powercycle a node."""
1239 OP_DSC_FIELD = "node_name"
1244 OP_RESULT = ht.TMaybeString
1247 class OpNodeMigrate(OpCode):
1248 """Migrate all instances from a node."""
1249 OP_DSC_FIELD = "node_name"
1254 _PMigrationTargetNode,
1257 _PIAllocFromDesc("Iallocator for deciding the target node"
1258 " for shared-storage instances"),
1260 OP_RESULT = TJobIdListOnly
1263 class OpNodeEvacuate(OpCode):
1264 """Evacuate instances off a number of nodes."""
1265 OP_DSC_FIELD = "node_name"
1269 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1270 _PIAllocFromDesc("Iallocator for computing solution"),
1271 ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1272 "Node evacuation mode"),
1274 OP_RESULT = TJobIdListOnly
1279 class OpInstanceCreate(OpCode):
1280 """Create an instance.
1282 @ivar instance_name: Instance name
1283 @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1284 @ivar source_handshake: Signed handshake from source (remote import only)
1285 @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1286 @ivar source_instance_name: Previous name of instance (remote import only)
1287 @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1288 (remote import only)
1291 OP_DSC_FIELD = "instance_name"
1298 _POpportunisticLocking,
1299 ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1300 ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1301 "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1302 " each disk definition must contain a ``%s`` value and"
1303 " can contain an optional ``%s`` value denoting the disk access mode"
1305 (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1306 constants.IDISK_MODE,
1307 " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1308 ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1310 ("file_driver", None, ht.TMaybe(ht.TElemOf(constants.FILE_DRIVER)),
1311 "Driver for file-backed disks"),
1312 ("file_storage_dir", None, ht.TMaybeString,
1313 "Directory for storing file-backed disks"),
1314 ("hvparams", ht.EmptyDict, ht.TDict,
1315 "Hypervisor parameters for instance, hypervisor-dependent"),
1316 ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1317 _PIAllocFromDesc("Iallocator for deciding which node(s) to use"),
1318 ("identify_defaults", False, ht.TBool,
1319 "Reset instance parameters to default if equal"),
1320 ("ip_check", True, ht.TBool, _PIpCheckDoc),
1321 ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1322 ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1323 "Instance creation mode"),
1324 ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1325 "List of NIC (network interface) definitions, for example"
1326 " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1327 " contain the optional values %s" %
1329 ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1330 ("no_install", None, ht.TMaybeBool,
1331 "Do not install the OS (will disable automatic start)"),
1332 ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1333 ("os_type", None, ht.TMaybeString, "Operating system"),
1334 ("pnode", None, ht.TMaybeString, "Primary node"),
1335 ("snode", None, ht.TMaybeString, "Secondary node"),
1336 ("source_handshake", None, ht.TMaybe(ht.TList),
1337 "Signed handshake from source (remote import only)"),
1338 ("source_instance_name", None, ht.TMaybeString,
1339 "Source instance name (remote import only)"),
1340 ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1342 "How long source instance was given to shut down (remote import only)"),
1343 ("source_x509_ca", None, ht.TMaybeString,
1344 "Source X509 CA in PEM format (remote import only)"),
1345 ("src_node", None, ht.TMaybeString, "Source node for import"),
1346 ("src_path", None, ht.TMaybeString, "Source directory for import"),
1347 ("start", True, ht.TBool, "Whether to start instance after creation"),
1348 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1350 OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1353 class OpInstanceMultiAlloc(OpCode):
1354 """Allocates multiple instances.
1358 _POpportunisticLocking,
1359 _PIAllocFromDesc("Iallocator used to allocate all the instances"),
1360 ("instances", ht.EmptyList, ht.TListOf(ht.TInstanceOf(OpInstanceCreate)),
1361 "List of instance create opcodes describing the instances to allocate"),
1363 _JOB_LIST = ht.Comment("List of submitted jobs")(TJobIdList)
1364 ALLOCATABLE_KEY = "allocatable"
1365 FAILED_KEY = "allocatable"
1366 OP_RESULT = ht.TStrictDict(True, True, {
1367 constants.JOB_IDS_KEY: _JOB_LIST,
1368 ALLOCATABLE_KEY: ht.TListOf(ht.TNonEmptyString),
1369 FAILED_KEY: ht.TListOf(ht.TNonEmptyString),
1372 def __getstate__(self):
1373 """Generic serializer.
1376 state = OpCode.__getstate__(self)
1377 if hasattr(self, "instances"):
1378 # pylint: disable=E1101
1379 state["instances"] = [inst.__getstate__() for inst in self.instances]
1382 def __setstate__(self, state):
1383 """Generic unserializer.
1385 This method just restores from the serialized state the attributes
1386 of the current instance.
1388 @param state: the serialized opcode data
1389 @type state: C{dict}
1392 if not isinstance(state, dict):
1393 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
1396 if "instances" in state:
1397 state["instances"] = map(OpCode.LoadOpCode, state["instances"])
1399 return OpCode.__setstate__(self, state)
1401 def Validate(self, set_defaults):
1402 """Validates this opcode.
1404 We do this recursively.
1407 OpCode.Validate(self, set_defaults)
1409 for inst in self.instances: # pylint: disable=E1101
1410 inst.Validate(set_defaults)
1413 class OpInstanceReinstall(OpCode):
1414 """Reinstall an instance's OS."""
1415 OP_DSC_FIELD = "instance_name"
1419 ("os_type", None, ht.TMaybeString, "Instance operating system"),
1420 ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1422 OP_RESULT = ht.TNone
1425 class OpInstanceRemove(OpCode):
1426 """Remove an instance."""
1427 OP_DSC_FIELD = "instance_name"
1431 ("ignore_failures", False, ht.TBool,
1432 "Whether to ignore failures during removal"),
1434 OP_RESULT = ht.TNone
1437 class OpInstanceRename(OpCode):
1438 """Rename an instance."""
1442 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1443 ("ip_check", False, ht.TBool, _PIpCheckDoc),
1445 OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1448 class OpInstanceStartup(OpCode):
1449 """Startup an instance."""
1450 OP_DSC_FIELD = "instance_name"
1454 _PIgnoreOfflineNodes,
1455 ("hvparams", ht.EmptyDict, ht.TDict,
1456 "Temporary hypervisor parameters, hypervisor-dependent"),
1457 ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1461 OP_RESULT = ht.TNone
1464 class OpInstanceShutdown(OpCode):
1465 """Shutdown an instance."""
1466 OP_DSC_FIELD = "instance_name"
1470 _PIgnoreOfflineNodes,
1471 ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TNonNegativeInt,
1472 "How long to wait for instance to shut down"),
1475 OP_RESULT = ht.TNone
1478 class OpInstanceReboot(OpCode):
1479 """Reboot an instance."""
1480 OP_DSC_FIELD = "instance_name"
1484 ("ignore_secondaries", False, ht.TBool,
1485 "Whether to start the instance even if secondary disks are failing"),
1486 ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1487 "How to reboot instance"),
1489 OP_RESULT = ht.TNone
1492 class OpInstanceReplaceDisks(OpCode):
1493 """Replace the disks of an instance."""
1494 OP_DSC_FIELD = "instance_name"
1499 ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1500 "Replacement mode"),
1501 ("disks", ht.EmptyList, ht.TListOf(ht.TNonNegativeInt),
1503 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1504 _PIAllocFromDesc("Iallocator for deciding new secondary node"),
1506 OP_RESULT = ht.TNone
1509 class OpInstanceFailover(OpCode):
1510 """Failover an instance."""
1511 OP_DSC_FIELD = "instance_name"
1515 _PIgnoreConsistency,
1516 _PMigrationTargetNode,
1518 _PIAllocFromDesc("Iallocator for deciding the target node for"
1519 " shared-storage instances"),
1521 OP_RESULT = ht.TNone
1524 class OpInstanceMigrate(OpCode):
1525 """Migrate an instance.
1527 This migrates (without shutting down an instance) to its secondary
1530 @ivar instance_name: the name of the instance
1531 @ivar mode: the migration mode (live, non-live or None for auto)
1534 OP_DSC_FIELD = "instance_name"
1539 _PMigrationTargetNode,
1542 ("cleanup", False, ht.TBool,
1543 "Whether a previously failed migration should be cleaned up"),
1544 _PIAllocFromDesc("Iallocator for deciding the target node for"
1545 " shared-storage instances"),
1546 ("allow_failover", False, ht.TBool,
1547 "Whether we can fallback to failover if migration is not possible"),
1549 OP_RESULT = ht.TNone
1552 class OpInstanceMove(OpCode):
1553 """Move an instance.
1555 This move (with shutting down an instance and data copying) to an
1558 @ivar instance_name: the name of the instance
1559 @ivar target_node: the destination node
1562 OP_DSC_FIELD = "instance_name"
1567 ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1568 _PIgnoreConsistency,
1570 OP_RESULT = ht.TNone
1573 class OpInstanceConsole(OpCode):
1574 """Connect to an instance's console."""
1575 OP_DSC_FIELD = "instance_name"
1579 OP_RESULT = ht.TDict
1582 class OpInstanceActivateDisks(OpCode):
1583 """Activate an instance's disks."""
1584 OP_DSC_FIELD = "instance_name"
1587 ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1590 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1591 ht.TItems([ht.TNonEmptyString,
1593 ht.TNonEmptyString])))
1596 class OpInstanceDeactivateDisks(OpCode):
1597 """Deactivate an instance's disks."""
1598 OP_DSC_FIELD = "instance_name"
1603 OP_RESULT = ht.TNone
1606 class OpInstanceRecreateDisks(OpCode):
1607 """Recreate an instance's disks."""
1609 ht.TAnd(ht.TIsLength(2),
1610 ht.TItems([ht.Comment("Disk index")(ht.TNonNegativeInt),
1611 ht.Comment("Parameters")(_TDiskParams)]))
1613 OP_DSC_FIELD = "instance_name"
1616 ("disks", ht.EmptyList,
1617 ht.TOr(ht.TListOf(ht.TNonNegativeInt), ht.TListOf(_TDiskChanges)),
1618 "List of disk indexes (deprecated) or a list of tuples containing a disk"
1619 " index and a possibly empty dictionary with disk parameter changes"),
1620 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1621 "New instance nodes, if relocation is desired"),
1622 _PIAllocFromDesc("Iallocator for deciding new nodes"),
1624 OP_RESULT = ht.TNone
1627 class OpInstanceQuery(OpCode):
1628 """Compute the list of instances."""
1632 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1633 "Empty list to query all instances, instance names otherwise"),
1635 OP_RESULT = _TOldQueryResult
1638 class OpInstanceQueryData(OpCode):
1639 """Compute the run-time status of instances."""
1642 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1644 ("static", False, ht.TBool,
1645 "Whether to only return configuration data without querying"
1648 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1651 def _TestInstSetParamsModList(fn):
1652 """Generates a check for modification lists.
1656 # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1658 ht.TAnd(ht.TIsLength(2), ht.TItems([
1659 ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TNonNegativeInt),
1663 # New format, supporting adding/removing disks/NICs at arbitrary indices
1665 ht.TAnd(ht.TIsLength(3), ht.TItems([
1666 ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1667 ht.Comment("Device index, can be negative, e.g. -1 for last disk")
1668 (ht.TOr(ht.TInt, ht.TString)),
1672 return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1673 ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1676 class OpInstanceSetParams(OpCode):
1677 """Change the parameters of an instance.
1680 TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1681 TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1683 OP_DSC_FIELD = "instance_name"
1689 ("nics", ht.EmptyList, TestNicModifications,
1690 "List of NIC changes: each item is of the form"
1691 " ``(op, identifier, settings)``, ``op`` is one of ``%s``, ``%s`` or"
1692 " ``%s``, ``identifier`` can be a zero-based index number (or -1 to refer"
1693 " to the last position), the NIC's UUID of the NIC's name; a"
1694 " deprecated version of this parameter used the form ``(op, settings)``,"
1695 " where ``op`` can be ``%s`` to add a new NIC with the specified"
1696 " settings, ``%s`` to remove the last NIC or a number to modify the"
1697 " settings of the NIC with that index" %
1698 (constants.DDM_ADD, constants.DDM_MODIFY, constants.DDM_REMOVE,
1699 constants.DDM_ADD, constants.DDM_REMOVE)),
1700 ("disks", ht.EmptyList, TestDiskModifications,
1701 "List of disk changes; see ``nics``"),
1702 ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1703 ("runtime_mem", None, ht.TMaybePositiveInt, "New runtime memory"),
1704 ("hvparams", ht.EmptyDict, ht.TDict,
1705 "Per-instance hypervisor parameters, hypervisor-dependent"),
1706 ("disk_template", None, ht.TMaybe(_BuildDiskTemplateCheck(False)),
1707 "Disk template for instance"),
1708 ("pnode", None, ht.TMaybeString, "New primary node"),
1709 ("remote_node", None, ht.TMaybeString,
1710 "Secondary node (used when changing disk template)"),
1711 ("os_name", None, ht.TMaybeString,
1712 "Change the instance's OS without reinstalling the instance"),
1713 ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1714 ("wait_for_sync", True, ht.TBool,
1715 "Whether to wait for the disk to synchronize, when changing template"),
1716 ("offline", None, ht.TMaybeBool, "Whether to mark instance as offline"),
1717 ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1719 OP_RESULT = _TSetParamsResult
1722 class OpInstanceGrowDisk(OpCode):
1723 """Grow a disk of an instance."""
1724 OP_DSC_FIELD = "instance_name"
1728 ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1729 ("amount", ht.NoDefault, ht.TNonNegativeInt,
1730 "Amount of disk space to add (megabytes)"),
1731 ("absolute", False, ht.TBool,
1732 "Whether the amount parameter is an absolute target or a relative one"),
1734 OP_RESULT = ht.TNone
1737 class OpInstanceChangeGroup(OpCode):
1738 """Moves an instance to another node group."""
1739 OP_DSC_FIELD = "instance_name"
1743 _PIAllocFromDesc("Iallocator for computing solution"),
1746 OP_RESULT = TJobIdListOnly
1749 # Node group opcodes
1751 class OpGroupAdd(OpCode):
1752 """Add a node group to the cluster."""
1753 OP_DSC_FIELD = "group_name"
1756 _PNodeGroupAllocPolicy,
1761 ("ipolicy", None, ht.TMaybeDict,
1762 "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1764 OP_RESULT = ht.TNone
1767 class OpGroupAssignNodes(OpCode):
1768 """Assign nodes to a node group."""
1769 OP_DSC_FIELD = "group_name"
1773 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1774 "List of nodes to assign"),
1776 OP_RESULT = ht.TNone
1779 class OpGroupQuery(OpCode):
1780 """Compute the list of node groups."""
1783 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1784 "Empty list to query all groups, group names otherwise"),
1786 OP_RESULT = _TOldQueryResult
1789 class OpGroupSetParams(OpCode):
1790 """Change the parameters of a node group."""
1791 OP_DSC_FIELD = "group_name"
1794 _PNodeGroupAllocPolicy,
1799 ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1801 OP_RESULT = _TSetParamsResult
1804 class OpGroupRemove(OpCode):
1805 """Remove a node group from the cluster."""
1806 OP_DSC_FIELD = "group_name"
1810 OP_RESULT = ht.TNone
1813 class OpGroupRename(OpCode):
1814 """Rename a node group in the cluster."""
1817 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1819 OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1822 class OpGroupEvacuate(OpCode):
1823 """Evacuate a node group in the cluster."""
1824 OP_DSC_FIELD = "group_name"
1828 _PIAllocFromDesc("Iallocator for computing solution"),
1831 OP_RESULT = TJobIdListOnly
1835 class OpOsDiagnose(OpCode):
1836 """Compute the list of guest operating systems."""
1839 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1840 "Which operating systems to diagnose"),
1842 OP_RESULT = _TOldQueryResult
1845 # ExtStorage opcodes
1846 class OpExtStorageDiagnose(OpCode):
1847 """Compute the list of external storage providers."""
1850 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1851 "Which ExtStorage Provider to diagnose"),
1853 OP_RESULT = _TOldQueryResult
1857 class OpBackupQuery(OpCode):
1858 """Compute the list of exported images."""
1861 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1862 "Empty list to query all nodes, node names otherwise"),
1864 OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1865 ht.TOr(ht.Comment("False on error")(ht.TBool),
1866 ht.TListOf(ht.TNonEmptyString)))
1869 class OpBackupPrepare(OpCode):
1870 """Prepares an instance export.
1872 @ivar instance_name: Instance name
1873 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1876 OP_DSC_FIELD = "instance_name"
1879 ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1882 OP_RESULT = ht.TMaybeDict
1885 class OpBackupExport(OpCode):
1886 """Export an instance.
1888 For local exports, the export destination is the node name. For
1889 remote exports, the export destination is a list of tuples, each
1890 consisting of hostname/IP address, port, magic, HMAC and HMAC
1891 salt. The HMAC is calculated using the cluster domain secret over
1892 the value "${index}:${hostname}:${port}". The destination X509 CA
1893 must be a signed certificate.
1895 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1896 @ivar target_node: Export destination
1897 @ivar x509_key_name: X509 key to use (remote export only)
1898 @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1902 OP_DSC_FIELD = "instance_name"
1906 # TODO: Rename target_node as it changes meaning for different export modes
1907 # (e.g. "destination")
1908 ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1909 "Destination information, depends on export mode"),
1910 ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1911 ("remove_instance", False, ht.TBool,
1912 "Whether to remove instance after export"),
1913 ("ignore_remove_failures", False, ht.TBool,
1914 "Whether to ignore failures while removing instances"),
1915 ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1917 ("x509_key_name", None, ht.TMaybe(ht.TList),
1918 "Name of X509 key (remote export only)"),
1919 ("destination_x509_ca", None, ht.TMaybeString,
1920 "Destination X509 CA (remote export only)"),
1923 ht.TAnd(ht.TIsLength(2), ht.TItems([
1924 ht.Comment("Finalizing status")(ht.TBool),
1925 ht.Comment("Status for every exported disk")(ht.TListOf(ht.TBool)),
1929 class OpBackupRemove(OpCode):
1930 """Remove an instance's export."""
1931 OP_DSC_FIELD = "instance_name"
1935 OP_RESULT = ht.TNone
1939 class OpTagsGet(OpCode):
1940 """Returns the tags of the given object."""
1941 OP_DSC_FIELD = "name"
1944 # Not using _PUseLocking as the default is different for historical reasons
1945 ("use_locking", True, ht.TBool, "Whether to use synchronization"),
1946 # Name is only meaningful for nodes and instances
1947 ("name", ht.NoDefault, ht.TMaybeString,
1948 "Name of object to retrieve tags from"),
1950 OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1953 class OpTagsSearch(OpCode):
1954 """Searches the tags in the cluster for a given pattern."""
1955 OP_DSC_FIELD = "pattern"
1957 ("pattern", ht.NoDefault, ht.TNonEmptyString,
1958 "Search pattern (regular expression)"),
1960 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1966 class OpTagsSet(OpCode):
1967 """Add a list of tags on a given object."""
1971 # Name is only meaningful for groups, nodes and instances
1972 ("name", ht.NoDefault, ht.TMaybeString,
1973 "Name of object where tag(s) should be added"),
1975 OP_RESULT = ht.TNone
1978 class OpTagsDel(OpCode):
1979 """Remove a list of tags from a given object."""
1983 # Name is only meaningful for groups, nodes and instances
1984 ("name", ht.NoDefault, ht.TMaybeString,
1985 "Name of object where tag(s) should be deleted"),
1987 OP_RESULT = ht.TNone
1991 class OpTestDelay(OpCode):
1992 """Sleeps for a configured amount of time.
1994 This is used just for debugging and testing.
1997 - duration: the time to sleep, in seconds
1998 - on_master: if true, sleep on the master
1999 - on_nodes: list of nodes in which to sleep
2001 If the on_master parameter is true, it will execute a sleep on the
2002 master (before any node sleep).
2004 If the on_nodes list is not empty, it will sleep on those nodes
2005 (after the sleep on the master, if that is enabled).
2007 As an additional feature, the case of duration < 0 will be reported
2008 as an execution error, so this opcode can be used as a failure
2009 generator. The case of duration == 0 will not be treated specially.
2012 OP_DSC_FIELD = "duration"
2014 ("duration", ht.NoDefault, ht.TNumber, None),
2015 ("on_master", True, ht.TBool, None),
2016 ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
2017 ("repeat", 0, ht.TNonNegativeInt, None),
2020 def OP_DSC_FORMATTER(self, value): # pylint: disable=C0103,R0201
2021 """Custom formatter for duration.
2031 class OpTestAllocator(OpCode):
2032 """Allocator framework testing.
2034 This opcode has two modes:
2035 - gather and return allocator input for a given mode (allocate new
2036 or replace secondary) and a given instance definition (direction
2038 - run a selected allocator for a given operation (as above) and
2039 return the allocator output (direction 'out')
2042 OP_DSC_FIELD = "iallocator"
2044 ("direction", ht.NoDefault,
2045 ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
2046 ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
2047 ("name", ht.NoDefault, ht.TNonEmptyString, None),
2048 ("nics", ht.NoDefault,
2049 ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
2054 ("disks", ht.NoDefault, ht.TMaybe(ht.TList), None),
2055 ("hypervisor", None, ht.TMaybeString, None),
2056 _PIAllocFromDesc(None),
2057 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
2058 ("memory", None, ht.TMaybe(ht.TNonNegativeInt), None),
2059 ("vcpus", None, ht.TMaybe(ht.TNonNegativeInt), None),
2060 ("os", None, ht.TMaybeString, None),
2061 ("disk_template", None, ht.TMaybeString, None),
2062 ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
2064 ht.TMaybe(ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
2065 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
2066 ("spindle_use", 1, ht.TNonNegativeInt, None),
2067 ("count", 1, ht.TNonNegativeInt, None),
2071 class OpTestJqueue(OpCode):
2072 """Utility opcode to test some aspects of the job queue.
2076 ("notify_waitlock", False, ht.TBool, None),
2077 ("notify_exec", False, ht.TBool, None),
2078 ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
2079 ("fail", False, ht.TBool, None),
2083 class OpTestDummy(OpCode):
2084 """Utility opcode used by unittests.
2088 ("result", ht.NoDefault, ht.NoType, None),
2089 ("messages", ht.NoDefault, ht.NoType, None),
2090 ("fail", ht.NoDefault, ht.NoType, None),
2091 ("submit_jobs", None, ht.NoType, None),
2097 # Add a new network in the cluster
2098 class OpNetworkAdd(OpCode):
2099 """Add an IP network to the cluster."""
2100 OP_DSC_FIELD = "network_name"
2103 ("network", ht.NoDefault, _TIpNetwork4, "IPv4 subnet"),
2104 ("gateway", None, ht.TMaybe(_TIpAddress4), "IPv4 gateway"),
2105 ("network6", None, ht.TMaybe(_TIpNetwork6), "IPv6 subnet"),
2106 ("gateway6", None, ht.TMaybe(_TIpAddress6), "IPv6 gateway"),
2107 ("mac_prefix", None, ht.TMaybeString,
2108 "MAC address prefix that overrides cluster one"),
2109 ("add_reserved_ips", None, _TMaybeAddr4List,
2110 "Which IP addresses to reserve"),
2111 ("conflicts_check", True, ht.TBool,
2112 "Whether to check for conflicting IP addresses"),
2113 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Network tags"),
2115 OP_RESULT = ht.TNone
2118 class OpNetworkRemove(OpCode):
2119 """Remove an existing network from the cluster.
2120 Must not be connected to any nodegroup.
2123 OP_DSC_FIELD = "network_name"
2128 OP_RESULT = ht.TNone
2131 class OpNetworkSetParams(OpCode):
2132 """Modify Network's parameters except for IPv4 subnet"""
2133 OP_DSC_FIELD = "network_name"
2136 ("gateway", None, ht.TMaybeValueNone(_TIpAddress4), "IPv4 gateway"),
2137 ("network6", None, ht.TMaybeValueNone(_TIpNetwork6), "IPv6 subnet"),
2138 ("gateway6", None, ht.TMaybeValueNone(_TIpAddress6), "IPv6 gateway"),
2139 ("mac_prefix", None, ht.TMaybeValueNone(ht.TString),
2140 "MAC address prefix that overrides cluster one"),
2141 ("add_reserved_ips", None, _TMaybeAddr4List,
2142 "Which external IP addresses to reserve"),
2143 ("remove_reserved_ips", None, _TMaybeAddr4List,
2144 "Which external IP addresses to release"),
2146 OP_RESULT = ht.TNone
2149 class OpNetworkConnect(OpCode):
2150 """Connect a Network to a specific Nodegroup with the defined netparams
2151 (mode, link). Nics in this Network will inherit those params.
2152 Produce errors if a NIC (that its not already assigned to a network)
2153 has an IP that is contained in the Network this will produce error unless
2154 --no-conflicts-check is passed.
2157 OP_DSC_FIELD = "network_name"
2161 ("network_mode", ht.NoDefault, ht.TElemOf(constants.NIC_VALID_MODES),
2162 "Connectivity mode"),
2163 ("network_link", ht.NoDefault, ht.TString, "Connectivity link"),
2164 ("conflicts_check", True, ht.TBool, "Whether to check for conflicting IPs"),
2166 OP_RESULT = ht.TNone
2169 class OpNetworkDisconnect(OpCode):
2170 """Disconnect a Network from a Nodegroup. Produce errors if NICs are
2171 present in the Network unless --no-conficts-check option is passed.
2174 OP_DSC_FIELD = "network_name"
2179 OP_RESULT = ht.TNone
2182 class OpNetworkQuery(OpCode):
2183 """Compute the list of networks."""
2187 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
2188 "Empty list to query all groups, group names otherwise"),
2190 OP_RESULT = _TOldQueryResult
2194 """Returns list of all defined opcodes.
2196 Does not eliminate duplicates by C{OP_ID}.
2199 return [v for v in globals().values()
2200 if (isinstance(v, type) and issubclass(v, OpCode) and
2201 hasattr(v, "OP_ID") and v is not OpCode)]
2204 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())