4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 This module implements the data structures which define the cluster
25 operations - the so-called opcodes.
27 Every operation which modifies the cluster state is expressed via
32 # this are practically structures, so disable the message about too
34 # pylint: disable-msg=R0903
39 from ganeti import constants
40 from ganeti import errors
44 # Common opcode attributes
46 #: output fields for a query operation
47 _POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString))
49 #: the shutdown timeout
50 _PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
53 #: the force parameter
54 _PForce = ("force", False, ht.TBool)
56 #: a required instance name (for single-instance LUs)
57 _PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString)
59 #: Whether to ignore offline nodes
60 _PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool)
62 #: a required node name (for single-node LUs)
63 _PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString)
65 #: a required node group name (for single-group LUs)
66 _PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString)
68 #: Migration type (live/non-live)
69 _PMigrationMode = ("mode", None,
70 ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)))
72 #: Obsolete 'live' migration mode (boolean)
73 _PMigrationLive = ("live", None, ht.TMaybeBool)
76 _PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES))
78 #: List of tag strings
79 _PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString))
82 _PIgnoreConsistency = ("ignore_consistency", False, ht.TBool)
84 #: Do not remember instance state changes
85 _PNoRemember = ("no_remember", False, ht.TBool)
87 #: OP_ID conversion regular expression
88 _OPID_RE = re.compile("([a-z])([A-Z])")
92 """Convert an opcode class name to an OP_ID.
95 @param name: the class name, as OpXxxYyy
97 @return: the name in the OP_XXXX_YYYY format
100 if not name.startswith("Op"):
102 # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
103 # consume any input, and hence we would just have all the elements
104 # in the list, one by one; but it seems that split doesn't work on
105 # non-consuming input, hence we have to process the input string a
107 name = _OPID_RE.sub(r"\1,\2", name)
108 elems = name.split(",")
109 return "_".join(n.upper() for n in elems)
112 def RequireFileStorage():
113 """Checks that file storage is enabled.
115 While it doesn't really fit into this module, L{utils} was deemed too large
116 of a dependency to be imported for just one or two functions.
118 @raise errors.OpPrereqError: when file storage is disabled
121 if not constants.ENABLE_FILE_STORAGE:
122 raise errors.OpPrereqError("File storage disabled at configure time",
126 def _CheckDiskTemplate(template):
127 """Ensure a given disk template is valid.
130 if template not in constants.DISK_TEMPLATES:
131 # Using str.join directly to avoid importing utils for CommaJoin
132 msg = ("Invalid disk template name '%s', valid templates are: %s" %
133 (template, ", ".join(constants.DISK_TEMPLATES)))
134 raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
135 if template == constants.DT_FILE:
140 def _CheckStorageType(storage_type):
141 """Ensure a given storage type is valid.
144 if storage_type not in constants.VALID_STORAGE_TYPES:
145 raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
147 if storage_type == constants.ST_FILE:
152 #: Storage type parameter
153 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType)
156 class _AutoOpParamSlots(type):
157 """Meta class for opcode definitions.
160 def __new__(mcs, name, bases, attrs):
161 """Called when a class should be created.
163 @param mcs: The meta class
164 @param name: Name of created class
165 @param bases: Base classes
167 @param attrs: Class attributes
170 assert "__slots__" not in attrs, \
171 "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
172 assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
174 attrs["OP_ID"] = _NameToId(name)
176 # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
177 params = attrs.setdefault("OP_PARAMS", [])
179 # Use parameter names as slots
180 slots = [pname for (pname, _, _) in params]
182 assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
183 "Class '%s' uses unknown field in OP_DSC_FIELD" % name
185 attrs["__slots__"] = slots
187 return type.__new__(mcs, name, bases, attrs)
190 class BaseOpCode(object):
191 """A simple serializable object.
193 This object serves as a parent class for OpCode without any custom
197 # pylint: disable-msg=E1101
198 # as OP_ID is dynamically defined
199 __metaclass__ = _AutoOpParamSlots
201 def __init__(self, **kwargs):
202 """Constructor for BaseOpCode.
204 The constructor takes only keyword arguments and will set
205 attributes on this object based on the passed arguments. As such,
206 it means that you should not pass arguments which are not in the
207 __slots__ attribute for this class.
210 slots = self._all_slots()
213 raise TypeError("Object %s doesn't support the parameter '%s'" %
214 (self.__class__.__name__, key))
215 setattr(self, key, kwargs[key])
217 def __getstate__(self):
218 """Generic serializer.
220 This method just returns the contents of the instance as a
224 @return: the instance attributes and their values
228 for name in self._all_slots():
229 if hasattr(self, name):
230 state[name] = getattr(self, name)
233 def __setstate__(self, state):
234 """Generic unserializer.
236 This method just restores from the serialized state the attributes
237 of the current instance.
239 @param state: the serialized opcode data
243 if not isinstance(state, dict):
244 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
247 for name in self._all_slots():
248 if name not in state and hasattr(self, name):
252 setattr(self, name, state[name])
256 """Compute the list of all declared slots for a class.
260 for parent in cls.__mro__:
261 slots.extend(getattr(parent, "__slots__", []))
265 def GetAllParams(cls):
266 """Compute list of all parameters for an opcode.
270 for parent in cls.__mro__:
271 slots.extend(getattr(parent, "OP_PARAMS", []))
274 def Validate(self, set_defaults):
275 """Validate opcode parameters, optionally setting default values.
277 @type set_defaults: bool
278 @param set_defaults: Whether to set default values
279 @raise errors.OpPrereqError: When a parameter value doesn't match
283 for (attr_name, default, test) in self.GetAllParams():
284 assert test == ht.NoType or callable(test)
286 if not hasattr(self, attr_name):
287 if default == ht.NoDefault:
288 raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
289 (self.OP_ID, attr_name),
292 if callable(default):
296 setattr(self, attr_name, dval)
298 if test == ht.NoType:
302 if set_defaults or hasattr(self, attr_name):
303 attr_val = getattr(self, attr_name)
304 if not test(attr_val):
305 logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
306 self.OP_ID, attr_name, type(attr_val), attr_val)
307 raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
308 (self.OP_ID, attr_name),
312 class OpCode(BaseOpCode):
315 This is the root of the actual OpCode hierarchy. All clases derived
316 from this class should override OP_ID.
318 @cvar OP_ID: The ID of this opcode. This should be unique amongst all
319 children of this class.
320 @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
321 string returned by Summary(); see the docstring of that
323 @cvar OP_PARAMS: List of opcode attributes, the default values they should
324 get if not already defined, and types they must match.
325 @cvar WITH_LU: Boolean that specifies whether this should be included in
326 mcpu's dispatch table
327 @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
329 @ivar priority: Opcode priority for queue
332 # pylint: disable-msg=E1101
333 # as OP_ID is dynamically defined
336 ("dry_run", None, ht.TMaybeBool),
337 ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
338 ("priority", constants.OP_PRIO_DEFAULT,
339 ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID)),
342 def __getstate__(self):
343 """Specialized getstate for opcodes.
345 This method adds to the state dictionary the OP_ID of the class,
346 so that on unload we can identify the correct class for
347 instantiating the opcode.
350 @return: the state as a dictionary
353 data = BaseOpCode.__getstate__(self)
354 data["OP_ID"] = self.OP_ID
358 def LoadOpCode(cls, data):
359 """Generic load opcode method.
361 The method identifies the correct opcode class from the dict-form
362 by looking for a OP_ID key, if this is not found, or its value is
363 not available in this module as a child of this class, we fail.
366 @param data: the serialized opcode
369 if not isinstance(data, dict):
370 raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
371 if "OP_ID" not in data:
372 raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
373 op_id = data["OP_ID"]
375 if op_id in OP_MAPPING:
376 op_class = OP_MAPPING[op_id]
378 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
381 new_data = data.copy()
382 del new_data["OP_ID"]
383 op.__setstate__(new_data)
387 """Generates a summary description of this opcode.
389 The summary is the value of the OP_ID attribute (without the "OP_"
390 prefix), plus the value of the OP_DSC_FIELD attribute, if one was
391 defined; this field should allow to easily identify the operation
392 (for an instance creation job, e.g., it would be the instance
396 assert self.OP_ID is not None and len(self.OP_ID) > 3
397 # all OP_ID start with OP_, we remove that
399 field_name = getattr(self, "OP_DSC_FIELD", None)
401 field_value = getattr(self, field_name, None)
402 if isinstance(field_value, (list, tuple)):
403 field_value = ",".join(str(i) for i in field_value)
404 txt = "%s(%s)" % (txt, field_value)
410 class OpClusterPostInit(OpCode):
411 """Post cluster initialization.
413 This opcode does not touch the cluster at all. Its purpose is to run hooks
414 after the cluster has been initialized.
419 class OpClusterDestroy(OpCode):
420 """Destroy the cluster.
422 This opcode has no other parameters. All the state is irreversibly
423 lost after the execution of this opcode.
428 class OpClusterQuery(OpCode):
429 """Query cluster information."""
432 class OpClusterVerify(OpCode):
433 """Verify the cluster state.
435 @type skip_checks: C{list}
436 @ivar skip_checks: steps to be skipped from the verify process; this
437 needs to be a subset of
438 L{constants.VERIFY_OPTIONAL_CHECKS}; currently
439 only L{constants.VERIFY_NPLUSONE_MEM} can be passed
443 ("skip_checks", ht.EmptyList,
444 ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
445 ("verbose", False, ht.TBool),
446 ("error_codes", False, ht.TBool),
447 ("debug_simulate_errors", False, ht.TBool),
451 class OpClusterVerifyDisks(OpCode):
452 """Verify the cluster disks.
456 Result: a tuple of four elements:
457 - list of node names with bad data returned (unreachable, etc.)
458 - dict of node names with broken volume groups (values: error msg)
459 - list of instances with degraded disks (that should be activated)
460 - dict of instances with missing logical volumes (values: (node, vol)
461 pairs with details about the missing volumes)
463 In normal operation, all lists should be empty. A non-empty instance
464 list (3rd element of the result) is still ok (errors were fixed) but
465 non-empty node list means some node is down, and probably there are
466 unfixable drbd errors.
468 Note that only instances that are drbd-based are taken into
469 consideration. This might need to be revisited in the future.
474 class OpClusterRepairDiskSizes(OpCode):
475 """Verify the disk sizes of the instances and fixes configuration
478 Parameters: optional instances list, in case we want to restrict the
479 checks to only a subset of the instances.
481 Result: a list of tuples, (instance, disk, new-size) for changed
484 In normal operation, the list should be empty.
486 @type instances: list
487 @ivar instances: the list of instances to check, or empty for all instances
491 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
495 class OpClusterConfigQuery(OpCode):
496 """Query cluster configuration values."""
502 class OpClusterRename(OpCode):
503 """Rename the cluster.
506 @ivar name: The new name of the cluster. The name and/or the master IP
507 address will be changed to match the new name and its IP
511 OP_DSC_FIELD = "name"
513 ("name", ht.NoDefault, ht.TNonEmptyString),
517 class OpClusterSetParams(OpCode):
518 """Change the parameters of the cluster.
520 @type vg_name: C{str} or C{None}
521 @ivar vg_name: The new volume group name or None to disable LVM usage.
525 ("vg_name", None, ht.TMaybeString),
526 ("enabled_hypervisors", None,
527 ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
529 ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
531 ("beparams", None, ht.TOr(ht.TDict, ht.TNone)),
532 ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
534 ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
536 ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
537 ("uid_pool", None, ht.NoType),
538 ("add_uids", None, ht.NoType),
539 ("remove_uids", None, ht.NoType),
540 ("maintain_node_health", None, ht.TMaybeBool),
541 ("prealloc_wipe_disks", None, ht.TMaybeBool),
542 ("nicparams", None, ht.TMaybeDict),
543 ("ndparams", None, ht.TMaybeDict),
544 ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
545 ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
546 ("master_netdev", None, ht.TOr(ht.TString, ht.TNone)),
547 ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
548 ("hidden_os", None, ht.TOr(ht.TListOf(
551 ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
553 ("blacklisted_os", None, ht.TOr(ht.TListOf(
556 ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
561 class OpClusterRedistConf(OpCode):
562 """Force a full push of the cluster configuration.
567 class OpQuery(OpCode):
568 """Query for resources/items.
570 @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
571 @ivar fields: List of fields to retrieve
572 @ivar filter: Query filter
576 ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY)),
577 ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
578 ("filter", None, ht.TOr(ht.TNone,
579 ht.TListOf(ht.TOr(ht.TNonEmptyString, ht.TList)))),
583 class OpQueryFields(OpCode):
584 """Query for available resource/item fields.
586 @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
587 @ivar fields: List of fields to retrieve
591 ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY)),
592 ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
596 class OpOobCommand(OpCode):
597 """Interact with OOB."""
599 ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
600 ("command", None, ht.TElemOf(constants.OOB_COMMANDS)),
601 ("timeout", constants.OOB_TIMEOUT, ht.TInt),
607 class OpNodeRemove(OpCode):
610 @type node_name: C{str}
611 @ivar node_name: The name of the node to remove. If the node still has
612 instances on it, the operation will fail.
615 OP_DSC_FIELD = "node_name"
621 class OpNodeAdd(OpCode):
622 """Add a node to the cluster.
624 @type node_name: C{str}
625 @ivar node_name: The name of the node to add. This can be a short name,
626 but it will be expanded to the FQDN.
627 @type primary_ip: IP address
628 @ivar primary_ip: The primary IP of the node. This will be ignored when the
629 opcode is submitted, but will be filled during the node
630 add (so it will be visible in the job query).
631 @type secondary_ip: IP address
632 @ivar secondary_ip: The secondary IP of the node. This needs to be passed
633 if the cluster has been initialized in 'dual-network'
634 mode, otherwise it must not be given.
636 @ivar readd: Whether to re-add an existing node to the cluster. If
637 this is not passed, then the operation will abort if the node
638 name is already in the cluster; use this parameter to 'repair'
639 a node that had its configuration broken, or was reinstalled
640 without removal from the cluster.
642 @ivar group: The node group to which this node will belong.
643 @type vm_capable: C{bool}
644 @ivar vm_capable: The vm_capable node attribute
645 @type master_capable: C{bool}
646 @ivar master_capable: The master_capable node attribute
649 OP_DSC_FIELD = "node_name"
652 ("primary_ip", None, ht.NoType),
653 ("secondary_ip", None, ht.TMaybeString),
654 ("readd", False, ht.TBool),
655 ("group", None, ht.TMaybeString),
656 ("master_capable", None, ht.TMaybeBool),
657 ("vm_capable", None, ht.TMaybeBool),
658 ("ndparams", None, ht.TMaybeDict),
662 class OpNodeQuery(OpCode):
663 """Compute the list of nodes."""
666 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
667 ("use_locking", False, ht.TBool),
671 class OpNodeQueryvols(OpCode):
672 """Get list of volumes on node."""
675 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
679 class OpNodeQueryStorage(OpCode):
680 """Get information on storage for node(s)."""
684 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
685 ("name", None, ht.TMaybeString),
689 class OpNodeModifyStorage(OpCode):
690 """Modifies the properies of a storage unit"""
694 ("name", ht.NoDefault, ht.TNonEmptyString),
695 ("changes", ht.NoDefault, ht.TDict),
699 class OpRepairNodeStorage(OpCode):
700 """Repairs the volume group on a node."""
701 OP_DSC_FIELD = "node_name"
706 ("name", ht.NoDefault, ht.TNonEmptyString),
710 class OpNodeSetParams(OpCode):
711 """Change the parameters of a node."""
712 OP_DSC_FIELD = "node_name"
716 ("master_candidate", None, ht.TMaybeBool),
717 ("offline", None, ht.TMaybeBool),
718 ("drained", None, ht.TMaybeBool),
719 ("auto_promote", False, ht.TBool),
720 ("master_capable", None, ht.TMaybeBool),
721 ("vm_capable", None, ht.TMaybeBool),
722 ("secondary_ip", None, ht.TMaybeString),
723 ("ndparams", None, ht.TMaybeDict),
724 ("powered", None, ht.TMaybeBool),
728 class OpNodePowercycle(OpCode):
729 """Tries to powercycle a node."""
730 OP_DSC_FIELD = "node_name"
737 class OpNodeMigrate(OpCode):
738 """Migrate all instances from a node."""
739 OP_DSC_FIELD = "node_name"
747 class OpNodeEvacStrategy(OpCode):
748 """Compute the evacuation strategy for a list of nodes."""
749 OP_DSC_FIELD = "nodes"
751 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
752 ("remote_node", None, ht.TMaybeString),
753 ("iallocator", None, ht.TMaybeString),
759 class OpInstanceCreate(OpCode):
760 """Create an instance.
762 @ivar instance_name: Instance name
763 @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
764 @ivar source_handshake: Signed handshake from source (remote import only)
765 @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
766 @ivar source_instance_name: Previous name of instance (remote import only)
767 @ivar source_shutdown_timeout: Shutdown timeout used for source instance
771 OP_DSC_FIELD = "instance_name"
774 ("beparams", ht.EmptyDict, ht.TDict),
775 ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
776 ("disk_template", ht.NoDefault, _CheckDiskTemplate),
777 ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
778 ("file_storage_dir", None, ht.TMaybeString),
779 ("force_variant", False, ht.TBool),
780 ("hvparams", ht.EmptyDict, ht.TDict),
781 ("hypervisor", None, ht.TMaybeString),
782 ("iallocator", None, ht.TMaybeString),
783 ("identify_defaults", False, ht.TBool),
784 ("ip_check", True, ht.TBool),
785 ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
786 ("name_check", True, ht.TBool),
787 ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
788 ("no_install", None, ht.TMaybeBool),
789 ("osparams", ht.EmptyDict, ht.TDict),
790 ("os_type", None, ht.TMaybeString),
791 ("pnode", None, ht.TMaybeString),
792 ("snode", None, ht.TMaybeString),
793 ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
794 ("source_instance_name", None, ht.TMaybeString),
795 ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
797 ("source_x509_ca", None, ht.TMaybeString),
798 ("src_node", None, ht.TMaybeString),
799 ("src_path", None, ht.TMaybeString),
800 ("start", True, ht.TBool),
801 ("wait_for_sync", True, ht.TBool),
805 class OpInstanceReinstall(OpCode):
806 """Reinstall an instance's OS."""
807 OP_DSC_FIELD = "instance_name"
810 ("os_type", None, ht.TMaybeString),
811 ("force_variant", False, ht.TBool),
812 ("osparams", None, ht.TMaybeDict),
816 class OpInstanceRemove(OpCode):
817 """Remove an instance."""
818 OP_DSC_FIELD = "instance_name"
822 ("ignore_failures", False, ht.TBool),
826 class OpInstanceRename(OpCode):
827 """Rename an instance."""
830 ("new_name", ht.NoDefault, ht.TNonEmptyString),
831 ("ip_check", False, ht.TBool),
832 ("name_check", True, ht.TBool),
836 class OpInstanceStartup(OpCode):
837 """Startup an instance."""
838 OP_DSC_FIELD = "instance_name"
842 _PIgnoreOfflineNodes,
844 ("hvparams", ht.EmptyDict, ht.TDict),
845 ("beparams", ht.EmptyDict, ht.TDict),
849 class OpInstanceShutdown(OpCode):
850 """Shutdown an instance."""
851 OP_DSC_FIELD = "instance_name"
854 _PIgnoreOfflineNodes,
856 ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
860 class OpInstanceReboot(OpCode):
861 """Reboot an instance."""
862 OP_DSC_FIELD = "instance_name"
866 ("ignore_secondaries", False, ht.TBool),
867 ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
871 class OpInstanceReplaceDisks(OpCode):
872 """Replace the disks of an instance."""
873 OP_DSC_FIELD = "instance_name"
876 ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
877 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
878 ("remote_node", None, ht.TMaybeString),
879 ("iallocator", None, ht.TMaybeString),
880 ("early_release", False, ht.TBool),
884 class OpInstanceFailover(OpCode):
885 """Failover an instance."""
886 OP_DSC_FIELD = "instance_name"
894 class OpInstanceMigrate(OpCode):
895 """Migrate an instance.
897 This migrates (without shutting down an instance) to its secondary
900 @ivar instance_name: the name of the instance
901 @ivar mode: the migration mode (live, non-live or None for auto)
904 OP_DSC_FIELD = "instance_name"
909 ("cleanup", False, ht.TBool),
913 class OpInstanceMove(OpCode):
916 This move (with shutting down an instance and data copying) to an
919 @ivar instance_name: the name of the instance
920 @ivar target_node: the destination node
923 OP_DSC_FIELD = "instance_name"
928 ("target_node", ht.NoDefault, ht.TNonEmptyString),
932 class OpInstanceConsole(OpCode):
933 """Connect to an instance's console."""
934 OP_DSC_FIELD = "instance_name"
940 class OpInstanceActivateDisks(OpCode):
941 """Activate an instance's disks."""
942 OP_DSC_FIELD = "instance_name"
945 ("ignore_size", False, ht.TBool),
949 class OpInstanceDeactivateDisks(OpCode):
950 """Deactivate an instance's disks."""
951 OP_DSC_FIELD = "instance_name"
958 class OpInstanceRecreateDisks(OpCode):
959 """Deactivate an instance's disks."""
960 OP_DSC_FIELD = "instance_name"
963 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
964 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
968 class OpInstanceQuery(OpCode):
969 """Compute the list of instances."""
972 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
973 ("use_locking", False, ht.TBool),
977 class OpInstanceQueryData(OpCode):
978 """Compute the run-time status of instances."""
980 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
981 ("static", False, ht.TBool),
982 ("use_locking", False, ht.TBool),
986 class OpInstanceSetParams(OpCode):
987 """Change the parameters of an instance."""
988 OP_DSC_FIELD = "instance_name"
992 ("nics", ht.EmptyList, ht.TList),
993 ("disks", ht.EmptyList, ht.TList),
994 ("beparams", ht.EmptyDict, ht.TDict),
995 ("hvparams", ht.EmptyDict, ht.TDict),
996 ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate)),
997 ("remote_node", None, ht.TMaybeString),
998 ("os_name", None, ht.TMaybeString),
999 ("force_variant", False, ht.TBool),
1000 ("osparams", None, ht.TMaybeDict),
1001 ("wait_for_sync", True, ht.TBool),
1005 class OpInstanceGrowDisk(OpCode):
1006 """Grow a disk of an instance."""
1007 OP_DSC_FIELD = "instance_name"
1010 ("disk", ht.NoDefault, ht.TInt),
1011 ("amount", ht.NoDefault, ht.TInt),
1012 ("wait_for_sync", True, ht.TBool),
1016 # Node group opcodes
1018 class OpGroupAdd(OpCode):
1019 """Add a node group to the cluster."""
1020 OP_DSC_FIELD = "group_name"
1023 ("ndparams", None, ht.TMaybeDict),
1024 ("alloc_policy", None,
1025 ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES))),
1029 class OpGroupAssignNodes(OpCode):
1030 """Assign nodes to a node group."""
1031 OP_DSC_FIELD = "group_name"
1035 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
1039 class OpGroupQuery(OpCode):
1040 """Compute the list of node groups."""
1043 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1047 class OpGroupSetParams(OpCode):
1048 """Change the parameters of a node group."""
1049 OP_DSC_FIELD = "group_name"
1052 ("ndparams", None, ht.TMaybeDict),
1053 ("alloc_policy", None, ht.TOr(ht.TNone,
1054 ht.TElemOf(constants.VALID_ALLOC_POLICIES))),
1058 class OpGroupRemove(OpCode):
1059 """Remove a node group from the cluster."""
1060 OP_DSC_FIELD = "group_name"
1066 class OpGroupRename(OpCode):
1067 """Rename a node group in the cluster."""
1068 OP_DSC_FIELD = "old_name"
1070 ("old_name", ht.NoDefault, ht.TNonEmptyString),
1071 ("new_name", ht.NoDefault, ht.TNonEmptyString),
1076 class OpOsDiagnose(OpCode):
1077 """Compute the list of guest operating systems."""
1080 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1085 class OpBackupQuery(OpCode):
1086 """Compute the list of exported images."""
1088 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1089 ("use_locking", False, ht.TBool),
1093 class OpBackupPrepare(OpCode):
1094 """Prepares an instance export.
1096 @ivar instance_name: Instance name
1097 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1100 OP_DSC_FIELD = "instance_name"
1103 ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
1107 class OpBackupExport(OpCode):
1108 """Export an instance.
1110 For local exports, the export destination is the node name. For remote
1111 exports, the export destination is a list of tuples, each consisting of
1112 hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1113 the cluster domain secret over the value "${index}:${hostname}:${port}". The
1114 destination X509 CA must be a signed certificate.
1116 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1117 @ivar target_node: Export destination
1118 @ivar x509_key_name: X509 key to use (remote export only)
1119 @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1123 OP_DSC_FIELD = "instance_name"
1127 # TODO: Rename target_node as it changes meaning for different export modes
1128 # (e.g. "destination")
1129 ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
1130 ("shutdown", True, ht.TBool),
1131 ("remove_instance", False, ht.TBool),
1132 ("ignore_remove_failures", False, ht.TBool),
1133 ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
1134 ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
1135 ("destination_x509_ca", None, ht.TMaybeString),
1139 class OpBackupRemove(OpCode):
1140 """Remove an instance's export."""
1141 OP_DSC_FIELD = "instance_name"
1148 class OpTagsGet(OpCode):
1149 """Returns the tags of the given object."""
1150 OP_DSC_FIELD = "name"
1153 # Name is only meaningful for nodes and instances
1154 ("name", ht.NoDefault, ht.TMaybeString),
1158 class OpTagsSearch(OpCode):
1159 """Searches the tags in the cluster for a given pattern."""
1160 OP_DSC_FIELD = "pattern"
1162 ("pattern", ht.NoDefault, ht.TNonEmptyString),
1166 class OpTagsSet(OpCode):
1167 """Add a list of tags on a given object."""
1171 # Name is only meaningful for nodes and instances
1172 ("name", ht.NoDefault, ht.TMaybeString),
1176 class OpTagsDel(OpCode):
1177 """Remove a list of tags from a given object."""
1181 # Name is only meaningful for nodes and instances
1182 ("name", ht.NoDefault, ht.TMaybeString),
1186 class OpTestDelay(OpCode):
1187 """Sleeps for a configured amount of time.
1189 This is used just for debugging and testing.
1192 - duration: the time to sleep
1193 - on_master: if true, sleep on the master
1194 - on_nodes: list of nodes in which to sleep
1196 If the on_master parameter is true, it will execute a sleep on the
1197 master (before any node sleep).
1199 If the on_nodes list is not empty, it will sleep on those nodes
1200 (after the sleep on the master, if that is enabled).
1202 As an additional feature, the case of duration < 0 will be reported
1203 as an execution error, so this opcode can be used as a failure
1204 generator. The case of duration == 0 will not be treated specially.
1207 OP_DSC_FIELD = "duration"
1209 ("duration", ht.NoDefault, ht.TFloat),
1210 ("on_master", True, ht.TBool),
1211 ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1212 ("repeat", 0, ht.TPositiveInt)
1216 class OpTestAllocator(OpCode):
1217 """Allocator framework testing.
1219 This opcode has two modes:
1220 - gather and return allocator input for a given mode (allocate new
1221 or replace secondary) and a given instance definition (direction
1223 - run a selected allocator for a given operation (as above) and
1224 return the allocator output (direction 'out')
1227 OP_DSC_FIELD = "allocator"
1229 ("direction", ht.NoDefault,
1230 ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
1231 ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
1232 ("name", ht.NoDefault, ht.TNonEmptyString),
1233 ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1234 ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
1235 ht.TOr(ht.TNone, ht.TNonEmptyString))))),
1236 ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
1237 ("hypervisor", None, ht.TMaybeString),
1238 ("allocator", None, ht.TMaybeString),
1239 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
1240 ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
1241 ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
1242 ("os", None, ht.TMaybeString),
1243 ("disk_template", None, ht.TMaybeString),
1244 ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
1248 class OpTestJqueue(OpCode):
1249 """Utility opcode to test some aspects of the job queue.
1253 ("notify_waitlock", False, ht.TBool),
1254 ("notify_exec", False, ht.TBool),
1255 ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
1256 ("fail", False, ht.TBool),
1260 class OpTestDummy(OpCode):
1261 """Utility opcode used by unittests.
1265 ("result", ht.NoDefault, ht.NoType),
1266 ("messages", ht.NoDefault, ht.NoType),
1267 ("fail", ht.NoDefault, ht.NoType),
1273 """Returns list of all defined opcodes.
1275 Does not eliminate duplicates by C{OP_ID}.
1278 return [v for v in globals().values()
1279 if (isinstance(v, type) and issubclass(v, OpCode) and
1280 hasattr(v, "OP_ID") and v is not OpCode)]
1283 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())