4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 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 objectutils
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.TOr(ht.TNone, 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.TOr(ht.TNone, 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")
153 _PDiskParams = ("diskparams", None,
155 ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict),
157 "Disk templates' parameter defaults")
159 # Parameters for node resource model
160 _PHvState = ("hv_state", None, ht.TMaybeDict, "Set hypervisor states")
161 _PDiskState = ("disk_state", None, ht.TMaybeDict, "Set disk states")
164 _PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
165 "Whether to ignore ipolicy violations")
167 # Allow runtime changes while migrating
168 _PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
169 "Allow runtime changes (eg. memory ballooning)")
171 #: a required network name
172 _PNetworkName = ("network_name", ht.NoDefault, ht.TNonEmptyString,
175 #: OP_ID conversion regular expression
176 _OPID_RE = re.compile("([a-z])([A-Z])")
178 #: Utility function for L{OpClusterSetParams}
179 _TestClusterOsListItem = \
180 ht.TAnd(ht.TIsLength(2), ht.TItems([
181 ht.TElemOf(constants.DDMS_VALUES),
185 _TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
187 # TODO: Generate check from constants.INIC_PARAMS_TYPES
188 #: Utility function for testing NIC definitions
190 ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
191 ht.TOr(ht.TNone, ht.TNonEmptyString)))
193 _TSetParamsResultItemItems = [
194 ht.Comment("name of changed parameter")(ht.TNonEmptyString),
195 ht.Comment("new value")(ht.TAny),
198 _TSetParamsResult = \
199 ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
200 ht.TItems(_TSetParamsResultItemItems)))
202 # TODO: Generate check from constants.IDISK_PARAMS_TYPES (however, not all users
203 # of this check support all parameters)
205 ht.Comment("Disk parameters")(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
206 ht.TOr(ht.TNonEmptyString, ht.TInt)))
209 ht.TListOf(ht.TAnd(ht.TIsLength(2),
210 ht.TItems([ht.TElemOf(constants.RS_ALL),
213 _TQueryResult = ht.TListOf(_TQueryRow)
215 _TOldQueryRow = ht.TListOf(ht.TAny)
217 _TOldQueryResult = ht.TListOf(_TOldQueryRow)
227 #: Attribute name for dependencies
228 DEPEND_ATTR = "depends"
230 #: Attribute name for comment
231 COMMENT_ATTR = "comment"
235 """Convert an opcode class name to an OP_ID.
238 @param name: the class name, as OpXxxYyy
240 @return: the name in the OP_XXXX_YYYY format
243 if not name.startswith("Op"):
245 # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
246 # consume any input, and hence we would just have all the elements
247 # in the list, one by one; but it seems that split doesn't work on
248 # non-consuming input, hence we have to process the input string a
250 name = _OPID_RE.sub(r"\1,\2", name)
251 elems = name.split(",")
252 return "_".join(n.upper() for n in elems)
255 def _GenerateObjectTypeCheck(obj, fields_types):
256 """Helper to generate type checks for objects.
258 @param obj: The object to generate type checks
259 @param fields_types: The fields and their types as a dict
260 @return: A ht type check function
263 assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
264 "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
265 return ht.TStrictDict(True, True, fields_types)
269 _GenerateObjectTypeCheck(objects.QueryFieldDefinition, {
270 "name": ht.TNonEmptyString,
271 "title": ht.TNonEmptyString,
272 "kind": ht.TElemOf(constants.QFT_ALL),
273 "doc": ht.TNonEmptyString,
277 def RequireFileStorage():
278 """Checks that file storage is enabled.
280 While it doesn't really fit into this module, L{utils} was deemed too large
281 of a dependency to be imported for just one or two functions.
283 @raise errors.OpPrereqError: when file storage is disabled
286 if not constants.ENABLE_FILE_STORAGE:
287 raise errors.OpPrereqError("File storage disabled at configure time",
291 def RequireSharedFileStorage():
292 """Checks that shared file storage is enabled.
294 While it doesn't really fit into this module, L{utils} was deemed too large
295 of a dependency to be imported for just one or two functions.
297 @raise errors.OpPrereqError: when shared file storage is disabled
300 if not constants.ENABLE_SHARED_FILE_STORAGE:
301 raise errors.OpPrereqError("Shared file storage disabled at"
302 " configure time", errors.ECODE_INVAL)
305 @ht.WithDesc("CheckFileStorage")
306 def _CheckFileStorage(value):
307 """Ensures file storage is enabled if used.
310 if value == constants.DT_FILE:
312 elif value == constants.DT_SHARED_FILE:
313 RequireSharedFileStorage()
317 def _BuildDiskTemplateCheck(accept_none):
318 """Builds check for disk template.
320 @type accept_none: bool
321 @param accept_none: whether to accept None as a correct value
325 template_check = ht.TElemOf(constants.DISK_TEMPLATES)
328 template_check = ht.TOr(template_check, ht.TNone)
330 return ht.TAnd(template_check, _CheckFileStorage)
333 def _CheckStorageType(storage_type):
334 """Ensure a given storage type is valid.
337 if storage_type not in constants.VALID_STORAGE_TYPES:
338 raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
340 if storage_type == constants.ST_FILE:
341 # TODO: What about shared file storage?
346 #: Storage type parameter
347 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
350 _CheckNetworkType = ht.TElemOf(constants.NETWORK_VALID_TYPES)
352 #: Network type parameter
353 _PNetworkType = ("network_type", None, ht.TOr(ht.TNone, _CheckNetworkType),
357 def _CheckCIDRNetNotation(value):
358 """Ensure a given cidr notation type is valid.
362 ipaddr.IPv4Network(value)
363 except ipaddr.AddressValueError:
368 def _CheckCIDRAddrNotation(value):
369 """Ensure a given cidr notation type is valid.
373 ipaddr.IPv4Address(value)
374 except ipaddr.AddressValueError:
379 def _CheckCIDR6AddrNotation(value):
380 """Ensure a given cidr notation type is valid.
384 ipaddr.IPv6Address(value)
385 except ipaddr.AddressValueError:
390 def _CheckCIDR6NetNotation(value):
391 """Ensure a given cidr notation type is valid.
395 ipaddr.IPv6Network(value)
396 except ipaddr.AddressValueError:
401 class _AutoOpParamSlots(objectutils.AutoSlots):
402 """Meta class for opcode definitions.
405 def __new__(mcs, name, bases, attrs):
406 """Called when a class should be created.
408 @param mcs: The meta class
409 @param name: Name of created class
410 @param bases: Base classes
412 @param attrs: Class attributes
415 assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
417 slots = mcs._GetSlots(attrs)
418 assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
419 "Class '%s' uses unknown field in OP_DSC_FIELD" % name
421 attrs["OP_ID"] = _NameToId(name)
423 return objectutils.AutoSlots.__new__(mcs, name, bases, attrs)
426 def _GetSlots(mcs, attrs):
427 """Build the slots out of OP_PARAMS.
430 # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
431 params = attrs.setdefault("OP_PARAMS", [])
433 # Use parameter names as slots
434 return [pname for (pname, _, _, _) in params]
437 class BaseOpCode(objectutils.ValidatedSlots):
438 """A simple serializable object.
440 This object serves as a parent class for OpCode without any custom
444 # pylint: disable=E1101
445 # as OP_ID is dynamically defined
446 __metaclass__ = _AutoOpParamSlots
448 def __getstate__(self):
449 """Generic serializer.
451 This method just returns the contents of the instance as a
455 @return: the instance attributes and their values
459 for name in self.GetAllSlots():
460 if hasattr(self, name):
461 state[name] = getattr(self, name)
464 def __setstate__(self, state):
465 """Generic unserializer.
467 This method just restores from the serialized state the attributes
468 of the current instance.
470 @param state: the serialized opcode data
474 if not isinstance(state, dict):
475 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
478 for name in self.GetAllSlots():
479 if name not in state and hasattr(self, name):
483 setattr(self, name, state[name])
486 def GetAllParams(cls):
487 """Compute list of all parameters for an opcode.
491 for parent in cls.__mro__:
492 slots.extend(getattr(parent, "OP_PARAMS", []))
495 def Validate(self, set_defaults): # pylint: disable=W0221
496 """Validate opcode parameters, optionally setting default values.
498 @type set_defaults: bool
499 @param set_defaults: Whether to set default values
500 @raise errors.OpPrereqError: When a parameter value doesn't match
504 for (attr_name, default, test, _) in self.GetAllParams():
505 assert test == ht.NoType or callable(test)
507 if not hasattr(self, attr_name):
508 if default == ht.NoDefault:
509 raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
510 (self.OP_ID, attr_name),
513 if callable(default):
517 setattr(self, attr_name, dval)
519 if test == ht.NoType:
523 if set_defaults or hasattr(self, attr_name):
524 attr_val = getattr(self, attr_name)
525 if not test(attr_val):
526 logging.error("OpCode %s, parameter %s, has invalid type %s/value"
527 " '%s' expecting type %s",
528 self.OP_ID, attr_name, type(attr_val), attr_val, test)
529 raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
530 (self.OP_ID, attr_name),
534 def _BuildJobDepCheck(relative):
535 """Builds check for job dependencies (L{DEPEND_ATTR}).
538 @param relative: Whether to accept relative job IDs (negative)
543 job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
548 ht.TAnd(ht.TIsLength(2),
550 ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
552 return ht.TMaybeListOf(job_dep)
555 TNoRelativeJobDependencies = _BuildJobDepCheck(False)
557 #: List of submission status and job ID as returned by C{SubmitManyJobs}
559 ht.TAnd(ht.TIsLength(2),
560 ht.TItems([ht.Comment("success")(ht.TBool),
561 ht.Comment("Job ID if successful, error message"
562 " otherwise")(ht.TOr(ht.TString,
564 TJobIdList = ht.TListOf(_TJobIdListItem)
566 #: Result containing only list of submitted jobs
567 TJobIdListOnly = ht.TStrictDict(True, True, {
568 constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
572 class OpCode(BaseOpCode):
575 This is the root of the actual OpCode hierarchy. All clases derived
576 from this class should override OP_ID.
578 @cvar OP_ID: The ID of this opcode. This should be unique amongst all
579 children of this class.
580 @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
581 string returned by Summary(); see the docstring of that
583 @cvar OP_PARAMS: List of opcode attributes, the default values they should
584 get if not already defined, and types they must match.
585 @cvar OP_RESULT: Callable to verify opcode result
586 @cvar WITH_LU: Boolean that specifies whether this should be included in
587 mcpu's dispatch table
588 @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
590 @ivar priority: Opcode priority for queue
593 # pylint: disable=E1101
594 # as OP_ID is dynamically defined
597 ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
598 ("debug_level", None, ht.TOr(ht.TNone, ht.TNonNegativeInt), "Debug level"),
599 ("priority", constants.OP_PRIO_DEFAULT,
600 ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
601 (DEPEND_ATTR, None, _BuildJobDepCheck(True),
602 "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
603 " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
605 (COMMENT_ATTR, None, ht.TMaybeString,
606 "Comment describing the purpose of the opcode"),
610 def __getstate__(self):
611 """Specialized getstate for opcodes.
613 This method adds to the state dictionary the OP_ID of the class,
614 so that on unload we can identify the correct class for
615 instantiating the opcode.
618 @return: the state as a dictionary
621 data = BaseOpCode.__getstate__(self)
622 data["OP_ID"] = self.OP_ID
626 def LoadOpCode(cls, data):
627 """Generic load opcode method.
629 The method identifies the correct opcode class from the dict-form
630 by looking for a OP_ID key, if this is not found, or its value is
631 not available in this module as a child of this class, we fail.
634 @param data: the serialized opcode
637 if not isinstance(data, dict):
638 raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
639 if "OP_ID" not in data:
640 raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
641 op_id = data["OP_ID"]
643 if op_id in OP_MAPPING:
644 op_class = OP_MAPPING[op_id]
646 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
649 new_data = data.copy()
650 del new_data["OP_ID"]
651 op.__setstate__(new_data)
655 """Generates a summary description of this opcode.
657 The summary is the value of the OP_ID attribute (without the "OP_"
658 prefix), plus the value of the OP_DSC_FIELD attribute, if one was
659 defined; this field should allow to easily identify the operation
660 (for an instance creation job, e.g., it would be the instance
664 assert self.OP_ID is not None and len(self.OP_ID) > 3
665 # all OP_ID start with OP_, we remove that
667 field_name = getattr(self, "OP_DSC_FIELD", None)
669 field_value = getattr(self, field_name, None)
670 if isinstance(field_value, (list, tuple)):
671 field_value = ",".join(str(i) for i in field_value)
672 txt = "%s(%s)" % (txt, field_value)
675 def TinySummary(self):
676 """Generates a compact summary description of the opcode.
679 assert self.OP_ID.startswith("OP_")
681 text = self.OP_ID[3:]
683 for (prefix, supplement) in _SUMMARY_PREFIX.items():
684 if text.startswith(prefix):
685 return supplement + text[len(prefix):]
692 class OpClusterPostInit(OpCode):
693 """Post cluster initialization.
695 This opcode does not touch the cluster at all. Its purpose is to run hooks
696 after the cluster has been initialized.
702 class OpClusterDestroy(OpCode):
703 """Destroy the cluster.
705 This opcode has no other parameters. All the state is irreversibly
706 lost after the execution of this opcode.
709 OP_RESULT = ht.TNonEmptyString
712 class OpClusterQuery(OpCode):
713 """Query cluster information."""
714 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
717 class OpClusterVerify(OpCode):
718 """Submits all jobs necessary to verify the cluster.
722 _PDebugSimulateErrors,
727 ("group_name", None, ht.TMaybeString, "Group to verify"),
729 OP_RESULT = TJobIdListOnly
732 class OpClusterVerifyConfig(OpCode):
733 """Verify the cluster config.
737 _PDebugSimulateErrors,
745 class OpClusterVerifyGroup(OpCode):
746 """Run verify on a node group from the cluster.
748 @type skip_checks: C{list}
749 @ivar skip_checks: steps to be skipped from the verify process; this
750 needs to be a subset of
751 L{constants.VERIFY_OPTIONAL_CHECKS}; currently
752 only L{constants.VERIFY_NPLUSONE_MEM} can be passed
755 OP_DSC_FIELD = "group_name"
758 _PDebugSimulateErrors,
767 class OpClusterVerifyDisks(OpCode):
768 """Verify the cluster disks.
771 OP_RESULT = TJobIdListOnly
774 class OpGroupVerifyDisks(OpCode):
775 """Verifies the status of all disks in a node group.
777 Result: a tuple of three elements:
778 - dict of node names with issues (values: error msg)
779 - list of instances with degraded disks (that should be activated)
780 - dict of instances with missing logical volumes (values: (node, vol)
781 pairs with details about the missing volumes)
783 In normal operation, all lists should be empty. A non-empty instance
784 list (3rd element of the result) is still ok (errors were fixed) but
785 non-empty node list means some node is down, and probably there are
786 unfixable drbd errors.
788 Note that only instances that are drbd-based are taken into
789 consideration. This might need to be revisited in the future.
792 OP_DSC_FIELD = "group_name"
797 ht.TAnd(ht.TIsLength(3),
798 ht.TItems([ht.TDictOf(ht.TString, ht.TString),
799 ht.TListOf(ht.TString),
800 ht.TDictOf(ht.TString,
801 ht.TListOf(ht.TListOf(ht.TString)))]))
804 class OpClusterRepairDiskSizes(OpCode):
805 """Verify the disk sizes of the instances and fixes configuration
808 Parameters: optional instances list, in case we want to restrict the
809 checks to only a subset of the instances.
811 Result: a list of tuples, (instance, disk, new-size) for changed
814 In normal operation, the list should be empty.
816 @type instances: list
817 @ivar instances: the list of instances to check, or empty for all instances
821 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
823 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
824 ht.TItems([ht.TNonEmptyString,
826 ht.TNonNegativeInt])))
829 class OpClusterConfigQuery(OpCode):
830 """Query cluster configuration values."""
834 OP_RESULT = ht.TListOf(ht.TAny)
837 class OpClusterRename(OpCode):
838 """Rename the cluster.
841 @ivar name: The new name of the cluster. The name and/or the master IP
842 address will be changed to match the new name and its IP
846 OP_DSC_FIELD = "name"
848 ("name", ht.NoDefault, ht.TNonEmptyString, None),
850 OP_RESULT = ht.TNonEmptyString
853 class OpClusterSetParams(OpCode):
854 """Change the parameters of the cluster.
856 @type vg_name: C{str} or C{None}
857 @ivar vg_name: The new volume group name or None to disable LVM usage.
863 ("vg_name", None, ht.TOr(ht.TString, ht.TNone), "Volume group name"),
864 ("enabled_hypervisors", None,
865 ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
867 "List of enabled hypervisors"),
868 ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
870 "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
871 ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
872 "Cluster-wide backend parameter defaults"),
873 ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
875 "Cluster-wide per-OS hypervisor parameter defaults"),
876 ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
878 "Cluster-wide OS parameter defaults"),
880 ("candidate_pool_size", None, ht.TOr(ht.TPositiveInt, ht.TNone),
881 "Master candidate pool size"),
882 ("uid_pool", None, ht.NoType,
883 "Set UID pool, must be list of lists describing UID ranges (two items,"
884 " start and end inclusive)"),
885 ("add_uids", None, ht.NoType,
886 "Extend UID pool, must be list of lists describing UID ranges (two"
887 " items, start and end inclusive) to be added"),
888 ("remove_uids", None, ht.NoType,
889 "Shrink UID pool, must be list of lists describing UID ranges (two"
890 " items, start and end inclusive) to be removed"),
891 ("maintain_node_health", None, ht.TMaybeBool,
892 "Whether to automatically maintain node health"),
893 ("prealloc_wipe_disks", None, ht.TMaybeBool,
894 "Whether to wipe disks before allocating them to instances"),
895 ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
896 ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
897 ("ipolicy", None, ht.TMaybeDict,
898 "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
899 ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
900 ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
901 "Default iallocator for cluster"),
902 ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
903 "Master network device"),
904 ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
905 "Netmask of the master IP"),
906 ("reserved_lvs", None, ht.TMaybeListOf(ht.TNonEmptyString),
907 "List of reserved LVs"),
908 ("hidden_os", None, _TestClusterOsList,
909 "Modify list of hidden operating systems: each modification must have"
910 " two items, the operation and the OS name; the operation can be"
911 " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
912 ("blacklisted_os", None, _TestClusterOsList,
913 "Modify list of blacklisted operating systems: each modification must"
914 " have two items, the operation and the OS name; the operation can be"
915 " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
916 ("use_external_mip_script", None, ht.TMaybeBool,
917 "Whether to use an external master IP address setup script"),
922 class OpClusterRedistConf(OpCode):
923 """Force a full push of the cluster configuration.
929 class OpClusterActivateMasterIp(OpCode):
930 """Activate the master IP on the master node.
936 class OpClusterDeactivateMasterIp(OpCode):
937 """Deactivate the master IP on the master node.
943 class OpQuery(OpCode):
944 """Query for resources/items.
946 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
947 @ivar fields: List of fields to retrieve
948 @ivar qfilter: Query filter
951 OP_DSC_FIELD = "what"
955 ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
957 ("qfilter", None, ht.TOr(ht.TNone, ht.TList),
961 _GenerateObjectTypeCheck(objects.QueryResponse, {
962 "fields": ht.TListOf(_TQueryFieldDef),
963 "data": _TQueryResult,
967 class OpQueryFields(OpCode):
968 """Query for available resource/item fields.
970 @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
971 @ivar fields: List of fields to retrieve
974 OP_DSC_FIELD = "what"
977 ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
978 "Requested fields; if not given, all are returned"),
981 _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
982 "fields": ht.TListOf(_TQueryFieldDef),
986 class OpOobCommand(OpCode):
987 """Interact with OOB."""
989 ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
990 "List of nodes to run the OOB command against"),
991 ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
992 "OOB command to be run"),
993 ("timeout", constants.OOB_TIMEOUT, ht.TInt,
994 "Timeout before the OOB helper will be terminated"),
995 ("ignore_status", False, ht.TBool,
996 "Ignores the node offline status for power off"),
997 ("power_delay", constants.OOB_POWER_DELAY, ht.TNonNegativeFloat,
998 "Time in seconds to wait between powering on nodes"),
1000 # Fixme: Make it more specific with all the special cases in LUOobCommand
1001 OP_RESULT = _TQueryResult
1004 class OpRestrictedCommand(OpCode):
1005 """Runs a restricted command on node(s).
1010 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1011 "Nodes on which the command should be run (at least one)"),
1012 ("command", ht.NoDefault, ht.TNonEmptyString,
1013 "Command name (no parameters)"),
1017 ht.Comment("success")(ht.TBool),
1018 ht.Comment("output or error message")(ht.TString),
1022 ht.TListOf(ht.TAnd(ht.TIsLength(len(_RESULT_ITEMS)),
1023 ht.TItems(_RESULT_ITEMS)))
1028 class OpNodeRemove(OpCode):
1031 @type node_name: C{str}
1032 @ivar node_name: The name of the node to remove. If the node still has
1033 instances on it, the operation will fail.
1036 OP_DSC_FIELD = "node_name"
1040 OP_RESULT = ht.TNone
1043 class OpNodeAdd(OpCode):
1044 """Add a node to the cluster.
1046 @type node_name: C{str}
1047 @ivar node_name: The name of the node to add. This can be a short name,
1048 but it will be expanded to the FQDN.
1049 @type primary_ip: IP address
1050 @ivar primary_ip: The primary IP of the node. This will be ignored when the
1051 opcode is submitted, but will be filled during the node
1052 add (so it will be visible in the job query).
1053 @type secondary_ip: IP address
1054 @ivar secondary_ip: The secondary IP of the node. This needs to be passed
1055 if the cluster has been initialized in 'dual-network'
1056 mode, otherwise it must not be given.
1057 @type readd: C{bool}
1058 @ivar readd: Whether to re-add an existing node to the cluster. If
1059 this is not passed, then the operation will abort if the node
1060 name is already in the cluster; use this parameter to 'repair'
1061 a node that had its configuration broken, or was reinstalled
1062 without removal from the cluster.
1064 @ivar group: The node group to which this node will belong.
1065 @type vm_capable: C{bool}
1066 @ivar vm_capable: The vm_capable node attribute
1067 @type master_capable: C{bool}
1068 @ivar master_capable: The master_capable node attribute
1071 OP_DSC_FIELD = "node_name"
1076 ("primary_ip", None, ht.NoType, "Primary IP address"),
1077 ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
1078 ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
1079 ("group", None, ht.TMaybeString, "Initial node group"),
1080 ("master_capable", None, ht.TMaybeBool,
1081 "Whether node can become master or master candidate"),
1082 ("vm_capable", None, ht.TMaybeBool,
1083 "Whether node can host instances"),
1084 ("ndparams", None, ht.TMaybeDict, "Node parameters"),
1086 OP_RESULT = ht.TNone
1089 class OpNodeQuery(OpCode):
1090 """Compute the list of nodes."""
1094 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1095 "Empty list to query all nodes, node names otherwise"),
1097 OP_RESULT = _TOldQueryResult
1100 class OpNodeQueryvols(OpCode):
1101 """Get list of volumes on node."""
1104 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1105 "Empty list to query all nodes, node names otherwise"),
1107 OP_RESULT = ht.TListOf(ht.TAny)
1110 class OpNodeQueryStorage(OpCode):
1111 """Get information on storage for node(s)."""
1115 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1116 ("name", None, ht.TMaybeString, "Storage name"),
1118 OP_RESULT = _TOldQueryResult
1121 class OpNodeModifyStorage(OpCode):
1122 """Modifies the properies of a storage unit"""
1123 OP_DSC_FIELD = "node_name"
1128 ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1130 OP_RESULT = ht.TNone
1133 class OpRepairNodeStorage(OpCode):
1134 """Repairs the volume group on a node."""
1135 OP_DSC_FIELD = "node_name"
1140 _PIgnoreConsistency,
1142 OP_RESULT = ht.TNone
1145 class OpNodeSetParams(OpCode):
1146 """Change the parameters of a node."""
1147 OP_DSC_FIELD = "node_name"
1153 ("master_candidate", None, ht.TMaybeBool,
1154 "Whether the node should become a master candidate"),
1155 ("offline", None, ht.TMaybeBool,
1156 "Whether the node should be marked as offline"),
1157 ("drained", None, ht.TMaybeBool,
1158 "Whether the node should be marked as drained"),
1159 ("auto_promote", False, ht.TBool,
1160 "Whether node(s) should be promoted to master candidate if necessary"),
1161 ("master_capable", None, ht.TMaybeBool,
1162 "Denote whether node can become master or master candidate"),
1163 ("vm_capable", None, ht.TMaybeBool,
1164 "Denote whether node can host instances"),
1165 ("secondary_ip", None, ht.TMaybeString,
1166 "Change node's secondary IP address"),
1167 ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1168 ("powered", None, ht.TMaybeBool,
1169 "Whether the node should be marked as powered"),
1171 OP_RESULT = _TSetParamsResult
1174 class OpNodePowercycle(OpCode):
1175 """Tries to powercycle a node."""
1176 OP_DSC_FIELD = "node_name"
1181 OP_RESULT = ht.TMaybeString
1184 class OpNodeMigrate(OpCode):
1185 """Migrate all instances from a node."""
1186 OP_DSC_FIELD = "node_name"
1191 _PMigrationTargetNode,
1194 ("iallocator", None, ht.TMaybeString,
1195 "Iallocator for deciding the target node for shared-storage instances"),
1197 OP_RESULT = TJobIdListOnly
1200 class OpNodeEvacuate(OpCode):
1201 """Evacuate instances off a number of nodes."""
1202 OP_DSC_FIELD = "node_name"
1206 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1207 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1208 ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1209 "Node evacuation mode"),
1211 OP_RESULT = TJobIdListOnly
1216 class OpInstanceCreate(OpCode):
1217 """Create an instance.
1219 @ivar instance_name: Instance name
1220 @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1221 @ivar source_handshake: Signed handshake from source (remote import only)
1222 @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1223 @ivar source_instance_name: Previous name of instance (remote import only)
1224 @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1225 (remote import only)
1228 OP_DSC_FIELD = "instance_name"
1235 ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1236 ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1237 "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1238 " each disk definition must contain a ``%s`` value and"
1239 " can contain an optional ``%s`` value denoting the disk access mode"
1241 (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1242 constants.IDISK_MODE,
1243 " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1244 ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1246 ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1247 "Driver for file-backed disks"),
1248 ("file_storage_dir", None, ht.TMaybeString,
1249 "Directory for storing file-backed disks"),
1250 ("hvparams", ht.EmptyDict, ht.TDict,
1251 "Hypervisor parameters for instance, hypervisor-dependent"),
1252 ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1253 ("iallocator", None, ht.TMaybeString,
1254 "Iallocator for deciding which node(s) to use"),
1255 ("identify_defaults", False, ht.TBool,
1256 "Reset instance parameters to default if equal"),
1257 ("ip_check", True, ht.TBool, _PIpCheckDoc),
1258 ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1259 ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1260 "Instance creation mode"),
1261 ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1262 "List of NIC (network interface) definitions, for example"
1263 " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1264 " contain the optional values %s" %
1266 ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1267 ("no_install", None, ht.TMaybeBool,
1268 "Do not install the OS (will disable automatic start)"),
1269 ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1270 ("os_type", None, ht.TMaybeString, "Operating system"),
1271 ("pnode", None, ht.TMaybeString, "Primary node"),
1272 ("snode", None, ht.TMaybeString, "Secondary node"),
1273 ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1274 "Signed handshake from source (remote import only)"),
1275 ("source_instance_name", None, ht.TMaybeString,
1276 "Source instance name (remote import only)"),
1277 ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1279 "How long source instance was given to shut down (remote import only)"),
1280 ("source_x509_ca", None, ht.TMaybeString,
1281 "Source X509 CA in PEM format (remote import only)"),
1282 ("src_node", None, ht.TMaybeString, "Source node for import"),
1283 ("src_path", None, ht.TMaybeString, "Source directory for import"),
1284 ("start", True, ht.TBool, "Whether to start instance after creation"),
1285 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1287 OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1290 class OpInstanceMultiAlloc(OpCode):
1291 """Allocates multiple instances.
1295 ("iallocator", None, ht.TMaybeString,
1296 "Iallocator used to allocate all the instances"),
1297 ("instances", [], ht.TListOf(ht.TInstanceOf(OpInstanceCreate)),
1298 "List of instance create opcodes describing the instances to allocate"),
1300 _JOB_LIST = ht.Comment("List of submitted jobs")(TJobIdList)
1301 ALLOCATABLE_KEY = "allocatable"
1302 FAILED_KEY = "allocatable"
1303 OP_RESULT = ht.TStrictDict(True, True, {
1304 constants.JOB_IDS_KEY: _JOB_LIST,
1305 ALLOCATABLE_KEY: ht.TListOf(ht.TNonEmptyString),
1306 FAILED_KEY: ht.TListOf(ht.TNonEmptyString),
1309 def __getstate__(self):
1310 """Generic serializer.
1313 state = OpCode.__getstate__(self)
1314 if hasattr(self, "instances"):
1315 # pylint: disable=E1101
1316 state["instances"] = [inst.__getstate__() for inst in self.instances]
1319 def __setstate__(self, state):
1320 """Generic unserializer.
1322 This method just restores from the serialized state the attributes
1323 of the current instance.
1325 @param state: the serialized opcode data
1326 @type state: C{dict}
1329 if not isinstance(state, dict):
1330 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
1333 if "instances" in state:
1334 insts = [OpCode.LoadOpCode(inst) for inst in state["instances"]]
1335 state["instances"] = insts
1336 return OpCode.__setstate__(self, state)
1338 def Validate(self, set_defaults):
1339 """Validates this opcode.
1341 We do this recursively.
1344 OpCode.Validate(self, set_defaults)
1346 for inst in self.instances: # pylint: disable=E1101
1347 inst.Validate(set_defaults)
1350 class OpInstanceReinstall(OpCode):
1351 """Reinstall an instance's OS."""
1352 OP_DSC_FIELD = "instance_name"
1356 ("os_type", None, ht.TMaybeString, "Instance operating system"),
1357 ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1359 OP_RESULT = ht.TNone
1362 class OpInstanceRemove(OpCode):
1363 """Remove an instance."""
1364 OP_DSC_FIELD = "instance_name"
1368 ("ignore_failures", False, ht.TBool,
1369 "Whether to ignore failures during removal"),
1371 OP_RESULT = ht.TNone
1374 class OpInstanceRename(OpCode):
1375 """Rename an instance."""
1379 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1380 ("ip_check", False, ht.TBool, _PIpCheckDoc),
1382 OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1385 class OpInstanceStartup(OpCode):
1386 """Startup an instance."""
1387 OP_DSC_FIELD = "instance_name"
1391 _PIgnoreOfflineNodes,
1392 ("hvparams", ht.EmptyDict, ht.TDict,
1393 "Temporary hypervisor parameters, hypervisor-dependent"),
1394 ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1398 OP_RESULT = ht.TNone
1401 class OpInstanceShutdown(OpCode):
1402 """Shutdown an instance."""
1403 OP_DSC_FIELD = "instance_name"
1406 _PIgnoreOfflineNodes,
1407 ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TNonNegativeInt,
1408 "How long to wait for instance to shut down"),
1411 OP_RESULT = ht.TNone
1414 class OpInstanceReboot(OpCode):
1415 """Reboot an instance."""
1416 OP_DSC_FIELD = "instance_name"
1420 ("ignore_secondaries", False, ht.TBool,
1421 "Whether to start the instance even if secondary disks are failing"),
1422 ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1423 "How to reboot instance"),
1425 OP_RESULT = ht.TNone
1428 class OpInstanceReplaceDisks(OpCode):
1429 """Replace the disks of an instance."""
1430 OP_DSC_FIELD = "instance_name"
1435 ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1436 "Replacement mode"),
1437 ("disks", ht.EmptyList, ht.TListOf(ht.TNonNegativeInt),
1439 ("remote_node", None, ht.TMaybeString, "New secondary node"),
1440 ("iallocator", None, ht.TMaybeString,
1441 "Iallocator for deciding new secondary node"),
1443 OP_RESULT = ht.TNone
1446 class OpInstanceFailover(OpCode):
1447 """Failover an instance."""
1448 OP_DSC_FIELD = "instance_name"
1452 _PIgnoreConsistency,
1453 _PMigrationTargetNode,
1455 ("iallocator", None, ht.TMaybeString,
1456 "Iallocator for deciding the target node for shared-storage instances"),
1458 OP_RESULT = ht.TNone
1461 class OpInstanceMigrate(OpCode):
1462 """Migrate an instance.
1464 This migrates (without shutting down an instance) to its secondary
1467 @ivar instance_name: the name of the instance
1468 @ivar mode: the migration mode (live, non-live or None for auto)
1471 OP_DSC_FIELD = "instance_name"
1476 _PMigrationTargetNode,
1479 ("cleanup", False, ht.TBool,
1480 "Whether a previously failed migration should be cleaned up"),
1481 ("iallocator", None, ht.TMaybeString,
1482 "Iallocator for deciding the target node for shared-storage instances"),
1483 ("allow_failover", False, ht.TBool,
1484 "Whether we can fallback to failover if migration is not possible"),
1486 OP_RESULT = ht.TNone
1489 class OpInstanceMove(OpCode):
1490 """Move an instance.
1492 This move (with shutting down an instance and data copying) to an
1495 @ivar instance_name: the name of the instance
1496 @ivar target_node: the destination node
1499 OP_DSC_FIELD = "instance_name"
1504 ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1505 _PIgnoreConsistency,
1507 OP_RESULT = ht.TNone
1510 class OpInstanceConsole(OpCode):
1511 """Connect to an instance's console."""
1512 OP_DSC_FIELD = "instance_name"
1516 OP_RESULT = ht.TDict
1519 class OpInstanceActivateDisks(OpCode):
1520 """Activate an instance's disks."""
1521 OP_DSC_FIELD = "instance_name"
1524 ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1527 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1528 ht.TItems([ht.TNonEmptyString,
1530 ht.TNonEmptyString])))
1533 class OpInstanceDeactivateDisks(OpCode):
1534 """Deactivate an instance's disks."""
1535 OP_DSC_FIELD = "instance_name"
1540 OP_RESULT = ht.TNone
1543 class OpInstanceRecreateDisks(OpCode):
1544 """Recreate an instance's disks."""
1546 ht.TAnd(ht.TIsLength(2),
1547 ht.TItems([ht.Comment("Disk index")(ht.TNonNegativeInt),
1548 ht.Comment("Parameters")(_TDiskParams)]))
1550 OP_DSC_FIELD = "instance_name"
1553 ("disks", ht.EmptyList,
1554 ht.TOr(ht.TListOf(ht.TNonNegativeInt), ht.TListOf(_TDiskChanges)),
1555 "List of disk indexes (deprecated) or a list of tuples containing a disk"
1556 " index and a possibly empty dictionary with disk parameter changes"),
1557 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1558 "New instance nodes, if relocation is desired"),
1559 ("iallocator", None, ht.TMaybeString,
1560 "Iallocator for deciding new nodes"),
1562 OP_RESULT = ht.TNone
1565 class OpInstanceQuery(OpCode):
1566 """Compute the list of instances."""
1570 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1571 "Empty list to query all instances, instance names otherwise"),
1573 OP_RESULT = _TOldQueryResult
1576 class OpInstanceQueryData(OpCode):
1577 """Compute the run-time status of instances."""
1580 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1582 ("static", False, ht.TBool,
1583 "Whether to only return configuration data without querying"
1586 OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1589 def _TestInstSetParamsModList(fn):
1590 """Generates a check for modification lists.
1594 # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1596 ht.TAnd(ht.TIsLength(2), ht.TItems([
1597 ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TNonNegativeInt),
1601 # New format, supporting adding/removing disks/NICs at arbitrary indices
1603 ht.TAnd(ht.TIsLength(3), ht.TItems([
1604 ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1605 ht.Comment("Disk index, can be negative, e.g. -1 for last disk")(ht.TInt),
1609 return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1610 ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1613 class OpInstanceSetParams(OpCode):
1614 """Change the parameters of an instance.
1617 TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1618 TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1620 OP_DSC_FIELD = "instance_name"
1626 ("nics", ht.EmptyList, TestNicModifications,
1627 "List of NIC changes: each item is of the form ``(op, index, settings)``,"
1628 " ``op`` is one of ``%s``, ``%s`` or ``%s``, ``index`` can be either -1"
1629 " to refer to the last position, or a zero-based index number; a"
1630 " deprecated version of this parameter used the form ``(op, settings)``,"
1631 " where ``op`` can be ``%s`` to add a new NIC with the specified"
1632 " settings, ``%s`` to remove the last NIC or a number to modify the"
1633 " settings of the NIC with that index" %
1634 (constants.DDM_ADD, constants.DDM_MODIFY, constants.DDM_REMOVE,
1635 constants.DDM_ADD, constants.DDM_REMOVE)),
1636 ("disks", ht.EmptyList, TestDiskModifications,
1637 "List of disk changes; see ``nics``"),
1638 ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1639 ("runtime_mem", None, ht.TMaybePositiveInt, "New runtime memory"),
1640 ("hvparams", ht.EmptyDict, ht.TDict,
1641 "Per-instance hypervisor parameters, hypervisor-dependent"),
1642 ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1643 "Disk template for instance"),
1644 ("remote_node", None, ht.TMaybeString,
1645 "Secondary node (used when changing disk template)"),
1646 ("os_name", None, ht.TMaybeString,
1647 "Change the instance's OS without reinstalling the instance"),
1648 ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1649 ("wait_for_sync", True, ht.TBool,
1650 "Whether to wait for the disk to synchronize, when changing template"),
1651 ("offline", None, ht.TMaybeBool, "Whether to mark instance as offline"),
1652 ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1654 OP_RESULT = _TSetParamsResult
1657 class OpInstanceGrowDisk(OpCode):
1658 """Grow a disk of an instance."""
1659 OP_DSC_FIELD = "instance_name"
1663 ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1664 ("amount", ht.NoDefault, ht.TNonNegativeInt,
1665 "Amount of disk space to add (megabytes)"),
1666 ("absolute", False, ht.TBool,
1667 "Whether the amount parameter is an absolute target or a relative one"),
1669 OP_RESULT = ht.TNone
1672 class OpInstanceChangeGroup(OpCode):
1673 """Moves an instance to another node group."""
1674 OP_DSC_FIELD = "instance_name"
1678 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1679 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1680 "Destination group names or UUIDs (defaults to \"all but current group\""),
1682 OP_RESULT = TJobIdListOnly
1685 # Node group opcodes
1687 class OpGroupAdd(OpCode):
1688 """Add a node group to the cluster."""
1689 OP_DSC_FIELD = "group_name"
1692 _PNodeGroupAllocPolicy,
1697 ("ipolicy", None, ht.TMaybeDict,
1698 "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1700 OP_RESULT = ht.TNone
1703 class OpGroupAssignNodes(OpCode):
1704 """Assign nodes to a node group."""
1705 OP_DSC_FIELD = "group_name"
1709 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1710 "List of nodes to assign"),
1712 OP_RESULT = ht.TNone
1715 class OpGroupQuery(OpCode):
1716 """Compute the list of node groups."""
1719 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1720 "Empty list to query all groups, group names otherwise"),
1722 OP_RESULT = _TOldQueryResult
1725 class OpGroupSetParams(OpCode):
1726 """Change the parameters of a node group."""
1727 OP_DSC_FIELD = "group_name"
1730 _PNodeGroupAllocPolicy,
1735 ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1737 OP_RESULT = _TSetParamsResult
1740 class OpGroupRemove(OpCode):
1741 """Remove a node group from the cluster."""
1742 OP_DSC_FIELD = "group_name"
1746 OP_RESULT = ht.TNone
1749 class OpGroupRename(OpCode):
1750 """Rename a node group in the cluster."""
1753 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1755 OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1758 class OpGroupEvacuate(OpCode):
1759 """Evacuate a node group in the cluster."""
1760 OP_DSC_FIELD = "group_name"
1764 ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1765 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1766 "Destination group names or UUIDs"),
1768 OP_RESULT = TJobIdListOnly
1772 class OpOsDiagnose(OpCode):
1773 """Compute the list of guest operating systems."""
1776 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1777 "Which operating systems to diagnose"),
1779 OP_RESULT = _TOldQueryResult
1783 class OpBackupQuery(OpCode):
1784 """Compute the list of exported images."""
1787 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1788 "Empty list to query all nodes, node names otherwise"),
1790 OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1791 ht.TOr(ht.Comment("False on error")(ht.TBool),
1792 ht.TListOf(ht.TNonEmptyString)))
1795 class OpBackupPrepare(OpCode):
1796 """Prepares an instance export.
1798 @ivar instance_name: Instance name
1799 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1802 OP_DSC_FIELD = "instance_name"
1805 ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1808 OP_RESULT = ht.TOr(ht.TNone, ht.TDict)
1811 class OpBackupExport(OpCode):
1812 """Export an instance.
1814 For local exports, the export destination is the node name. For remote
1815 exports, the export destination is a list of tuples, each consisting of
1816 hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1817 the cluster domain secret over the value "${index}:${hostname}:${port}". The
1818 destination X509 CA must be a signed certificate.
1820 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1821 @ivar target_node: Export destination
1822 @ivar x509_key_name: X509 key to use (remote export only)
1823 @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1827 OP_DSC_FIELD = "instance_name"
1831 # TODO: Rename target_node as it changes meaning for different export modes
1832 # (e.g. "destination")
1833 ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1834 "Destination information, depends on export mode"),
1835 ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1836 ("remove_instance", False, ht.TBool,
1837 "Whether to remove instance after export"),
1838 ("ignore_remove_failures", False, ht.TBool,
1839 "Whether to ignore failures while removing instances"),
1840 ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1842 ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1843 "Name of X509 key (remote export only)"),
1844 ("destination_x509_ca", None, ht.TMaybeString,
1845 "Destination X509 CA (remote export only)"),
1848 ht.TAnd(ht.TIsLength(2), ht.TItems([
1849 ht.Comment("Finalizing status")(ht.TBool),
1850 ht.Comment("Status for every exported disk")(ht.TListOf(ht.TBool)),
1854 class OpBackupRemove(OpCode):
1855 """Remove an instance's export."""
1856 OP_DSC_FIELD = "instance_name"
1860 OP_RESULT = ht.TNone
1864 class OpTagsGet(OpCode):
1865 """Returns the tags of the given object."""
1866 OP_DSC_FIELD = "name"
1869 # Not using _PUseLocking as the default is different for historical reasons
1870 ("use_locking", True, ht.TBool, "Whether to use synchronization"),
1871 # Name is only meaningful for nodes and instances
1872 ("name", ht.NoDefault, ht.TMaybeString,
1873 "Name of object to retrieve tags from"),
1875 OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1878 class OpTagsSearch(OpCode):
1879 """Searches the tags in the cluster for a given pattern."""
1880 OP_DSC_FIELD = "pattern"
1882 ("pattern", ht.NoDefault, ht.TNonEmptyString,
1883 "Search pattern (regular expression)"),
1885 OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1891 class OpTagsSet(OpCode):
1892 """Add a list of tags on a given object."""
1896 # Name is only meaningful for groups, nodes and instances
1897 ("name", ht.NoDefault, ht.TMaybeString,
1898 "Name of object where tag(s) should be added"),
1900 OP_RESULT = ht.TNone
1903 class OpTagsDel(OpCode):
1904 """Remove a list of tags from a given object."""
1908 # Name is only meaningful for groups, nodes and instances
1909 ("name", ht.NoDefault, ht.TMaybeString,
1910 "Name of object where tag(s) should be deleted"),
1912 OP_RESULT = ht.TNone
1916 class OpTestDelay(OpCode):
1917 """Sleeps for a configured amount of time.
1919 This is used just for debugging and testing.
1922 - duration: the time to sleep
1923 - on_master: if true, sleep on the master
1924 - on_nodes: list of nodes in which to sleep
1926 If the on_master parameter is true, it will execute a sleep on the
1927 master (before any node sleep).
1929 If the on_nodes list is not empty, it will sleep on those nodes
1930 (after the sleep on the master, if that is enabled).
1932 As an additional feature, the case of duration < 0 will be reported
1933 as an execution error, so this opcode can be used as a failure
1934 generator. The case of duration == 0 will not be treated specially.
1937 OP_DSC_FIELD = "duration"
1939 ("duration", ht.NoDefault, ht.TNumber, None),
1940 ("on_master", True, ht.TBool, None),
1941 ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1942 ("repeat", 0, ht.TNonNegativeInt, None),
1946 class OpTestAllocator(OpCode):
1947 """Allocator framework testing.
1949 This opcode has two modes:
1950 - gather and return allocator input for a given mode (allocate new
1951 or replace secondary) and a given instance definition (direction
1953 - run a selected allocator for a given operation (as above) and
1954 return the allocator output (direction 'out')
1957 OP_DSC_FIELD = "allocator"
1959 ("direction", ht.NoDefault,
1960 ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1961 ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1962 ("name", ht.NoDefault, ht.TNonEmptyString, None),
1963 ("nics", ht.NoDefault,
1964 ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
1967 ht.TOr(ht.TNone, ht.TNonEmptyString))),
1969 ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1970 ("hypervisor", None, ht.TMaybeString, None),
1971 ("allocator", None, ht.TMaybeString, None),
1972 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1973 ("memory", None, ht.TOr(ht.TNone, ht.TNonNegativeInt), None),
1974 ("vcpus", None, ht.TOr(ht.TNone, ht.TNonNegativeInt), None),
1975 ("os", None, ht.TMaybeString, None),
1976 ("disk_template", None, ht.TMaybeString, None),
1977 ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1979 ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1980 ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1981 ("spindle_use", 1, ht.TNonNegativeInt, None),
1982 ("count", 1, ht.TNonNegativeInt, None),
1986 class OpTestJqueue(OpCode):
1987 """Utility opcode to test some aspects of the job queue.
1991 ("notify_waitlock", False, ht.TBool, None),
1992 ("notify_exec", False, ht.TBool, None),
1993 ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1994 ("fail", False, ht.TBool, None),
1998 class OpTestDummy(OpCode):
1999 """Utility opcode used by unittests.
2003 ("result", ht.NoDefault, ht.NoType, None),
2004 ("messages", ht.NoDefault, ht.NoType, None),
2005 ("fail", ht.NoDefault, ht.NoType, None),
2006 ("submit_jobs", None, ht.NoType, None),
2012 # Add a new network in the cluster
2013 class OpNetworkAdd(OpCode):
2014 """Add an IP network to the cluster."""
2015 OP_DSC_FIELD = "network_name"
2019 ("network", None, ht.TAnd(ht.TString, _CheckCIDRNetNotation),
2021 ("gateway", None, ht.TOr(ht.TNone, _CheckCIDRAddrNotation),
2023 ("network6", None, ht.TOr(ht.TNone, _CheckCIDR6NetNotation),
2025 ("gateway6", None, ht.TOr(ht.TNone, _CheckCIDR6AddrNotation),
2027 ("mac_prefix", None, ht.TMaybeString,
2028 "Mac prefix that overrides cluster one"),
2029 ("add_reserved_ips", None,
2030 ht.TOr(ht.TNone, ht.TListOf(_CheckCIDRAddrNotation)),
2031 "Which IPs to reserve"),
2032 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Network tags"),
2034 OP_RESULT = ht.TNone
2037 class OpNetworkRemove(OpCode):
2038 """Remove an existing network from the cluster.
2039 Must not be connected to any nodegroup.
2042 OP_DSC_FIELD = "network_name"
2047 OP_RESULT = ht.TNone
2050 class OpNetworkSetParams(OpCode):
2051 """Modify Network's parameters except for IPv4 subnet"""
2052 OP_DSC_FIELD = "network_name"
2056 ("gateway", None, ht.TOr(ht.TNone, _CheckCIDRAddrNotation),
2058 ("network6", None, ht.TOr(ht.TNone, _CheckCIDR6NetNotation),
2060 ("gateway6", None, ht.TOr(ht.TNone, _CheckCIDR6AddrNotation),
2062 ("mac_prefix", None, ht.TMaybeString,
2063 "Mac prefix that overrides cluster one"),
2064 ("add_reserved_ips", None,
2065 ht.TOr(ht.TNone, ht.TListOf(_CheckCIDRAddrNotation)),
2066 "Which external IPs to reserve"),
2067 ("remove_reserved_ips", None,
2068 ht.TOr(ht.TNone, ht.TListOf(_CheckCIDRAddrNotation)),
2069 "Which external IPs to release"),
2071 OP_RESULT = ht.TNone
2074 class OpNetworkConnect(OpCode):
2075 """Connect a Network to a specific Nodegroup with the defined netparams
2076 (mode, link). Nics in this Network will inherit those params.
2077 Produce errors if a NIC (that its not already assigned to a network)
2078 has an IP that is contained in the Network this will produce error unless
2079 --no-conflicts-check is passed.
2082 OP_DSC_FIELD = "network_name"
2086 ("network_mode", None, ht.TString, "Connectivity mode"),
2087 ("network_link", None, ht.TString, "Connectivity link"),
2088 ("conflicts_check", True, ht.TBool, "Whether to check for conflicting IPs"),
2090 OP_RESULT = ht.TNone
2093 class OpNetworkDisconnect(OpCode):
2094 """Disconnect a Network from a Nodegroup. Produce errors if NICs are
2095 present in the Network unless --no-conficts-check option is passed.
2098 OP_DSC_FIELD = "network_name"
2102 ("conflicts_check", True, ht.TBool, "Whether to check for conflicting IPs"),
2104 OP_RESULT = ht.TNone
2107 class OpNetworkQuery(OpCode):
2108 """Compute the list of networks."""
2111 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
2112 "Empty list to query all groups, group names otherwise"),
2114 OP_RESULT = ht.TNone
2118 """Returns list of all defined opcodes.
2120 Does not eliminate duplicates by C{OP_ID}.
2123 return [v for v in globals().values()
2124 if (isinstance(v, type) and issubclass(v, OpCode) and
2125 hasattr(v, "OP_ID") and v is not OpCode)]
2128 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())