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
40 from ganeti import constants
41 from ganeti import errors
45 # Common opcode attributes
47 #: output fields for a query operation
48 _POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
49 "Selected output fields")
51 #: the shutdown timeout
53 ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
54 "How long to wait for instance to shut down")
56 #: the force parameter
57 _PForce = ("force", False, ht.TBool, "Whether to force the operation")
59 #: a required instance name (for single-instance LUs)
60 _PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString,
63 #: Whether to ignore offline nodes
64 _PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
65 "Whether to ignore offline nodes")
67 #: a required node name (for single-node LUs)
68 _PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
70 #: a required node group name (for single-group LUs)
71 _PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
73 #: Migration type (live/non-live)
74 _PMigrationMode = ("mode", None,
75 ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)),
78 #: Obsolete 'live' migration mode (boolean)
79 _PMigrationLive = ("live", None, ht.TMaybeBool,
80 "Legacy setting for live migration, do not use")
83 _PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
85 #: List of tag strings
86 _PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
88 _PForceVariant = ("force_variant", False, ht.TBool,
89 "Whether to force an unknown OS variant")
91 _PWaitForSync = ("wait_for_sync", True, ht.TBool,
92 "Whether to wait for the disk to synchronize")
94 _PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
95 "Whether to ignore disk consistency")
97 _PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
99 _PUseLocking = ("use_locking", False, ht.TBool,
100 "Whether to use synchronization")
102 _PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
104 _PNodeGroupAllocPolicy = \
105 ("alloc_policy", None,
106 ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
107 "Instance allocation policy")
109 _PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
110 "Default node parameters for group")
112 _PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
114 #: OP_ID conversion regular expression
115 _OPID_RE = re.compile("([a-z])([A-Z])")
117 #: Utility function for L{OpClusterSetParams}
118 _TestClusterOsList = ht.TOr(ht.TNone,
119 ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
120 ht.TMap(ht.WithDesc("GetFirstItem")(operator.itemgetter(0)),
121 ht.TElemOf(constants.DDMS_VALUES)))))
124 # TODO: Generate check from constants.INIC_PARAMS_TYPES
125 #: Utility function for testing NIC definitions
126 _TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
127 ht.TOr(ht.TNone, ht.TNonEmptyString))
131 """Convert an opcode class name to an OP_ID.
134 @param name: the class name, as OpXxxYyy
136 @return: the name in the OP_XXXX_YYYY format
139 if not name.startswith("Op"):
141 # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
142 # consume any input, and hence we would just have all the elements
143 # in the list, one by one; but it seems that split doesn't work on
144 # non-consuming input, hence we have to process the input string a
146 name = _OPID_RE.sub(r"\1,\2", name)
147 elems = name.split(",")
148 return "_".join(n.upper() for n in elems)
151 def RequireFileStorage():
152 """Checks that file storage is enabled.
154 While it doesn't really fit into this module, L{utils} was deemed too large
155 of a dependency to be imported for just one or two functions.
157 @raise errors.OpPrereqError: when file storage is disabled
160 if not constants.ENABLE_FILE_STORAGE:
161 raise errors.OpPrereqError("File storage disabled at configure time",
165 def RequireSharedFileStorage():
166 """Checks that shared file storage is enabled.
168 While it doesn't really fit into this module, L{utils} was deemed too large
169 of a dependency to be imported for just one or two functions.
171 @raise errors.OpPrereqError: when shared file storage is disabled
174 if not constants.ENABLE_SHARED_FILE_STORAGE:
175 raise errors.OpPrereqError("Shared file storage disabled at"
176 " configure time", errors.ECODE_INVAL)
179 @ht.WithDesc("CheckFileStorage")
180 def _CheckFileStorage(value):
181 """Ensures file storage is enabled if used.
184 if value == constants.DT_FILE:
186 elif value == constants.DT_SHARED_FILE:
187 RequireSharedFileStorage()
191 _CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
195 def _CheckStorageType(storage_type):
196 """Ensure a given storage type is valid.
199 if storage_type not in constants.VALID_STORAGE_TYPES:
200 raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
202 if storage_type == constants.ST_FILE:
207 #: Storage type parameter
208 _PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
212 class _AutoOpParamSlots(type):
213 """Meta class for opcode definitions.
216 def __new__(mcs, name, bases, attrs):
217 """Called when a class should be created.
219 @param mcs: The meta class
220 @param name: Name of created class
221 @param bases: Base classes
223 @param attrs: Class attributes
226 assert "__slots__" not in attrs, \
227 "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
228 assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
230 attrs["OP_ID"] = _NameToId(name)
232 # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
233 params = attrs.setdefault("OP_PARAMS", [])
235 # Use parameter names as slots
236 slots = [pname for (pname, _, _, _) in params]
238 assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
239 "Class '%s' uses unknown field in OP_DSC_FIELD" % name
241 attrs["__slots__"] = slots
243 return type.__new__(mcs, name, bases, attrs)
246 class BaseOpCode(object):
247 """A simple serializable object.
249 This object serves as a parent class for OpCode without any custom
253 # pylint: disable-msg=E1101
254 # as OP_ID is dynamically defined
255 __metaclass__ = _AutoOpParamSlots
257 def __init__(self, **kwargs):
258 """Constructor for BaseOpCode.
260 The constructor takes only keyword arguments and will set
261 attributes on this object based on the passed arguments. As such,
262 it means that you should not pass arguments which are not in the
263 __slots__ attribute for this class.
266 slots = self._all_slots()
269 raise TypeError("Object %s doesn't support the parameter '%s'" %
270 (self.__class__.__name__, key))
271 setattr(self, key, kwargs[key])
273 def __getstate__(self):
274 """Generic serializer.
276 This method just returns the contents of the instance as a
280 @return: the instance attributes and their values
284 for name in self._all_slots():
285 if hasattr(self, name):
286 state[name] = getattr(self, name)
289 def __setstate__(self, state):
290 """Generic unserializer.
292 This method just restores from the serialized state the attributes
293 of the current instance.
295 @param state: the serialized opcode data
299 if not isinstance(state, dict):
300 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
303 for name in self._all_slots():
304 if name not in state and hasattr(self, name):
308 setattr(self, name, state[name])
312 """Compute the list of all declared slots for a class.
316 for parent in cls.__mro__:
317 slots.extend(getattr(parent, "__slots__", []))
321 def GetAllParams(cls):
322 """Compute list of all parameters for an opcode.
326 for parent in cls.__mro__:
327 slots.extend(getattr(parent, "OP_PARAMS", []))
330 def Validate(self, set_defaults):
331 """Validate opcode parameters, optionally setting default values.
333 @type set_defaults: bool
334 @param set_defaults: Whether to set default values
335 @raise errors.OpPrereqError: When a parameter value doesn't match
339 for (attr_name, default, test, _) in self.GetAllParams():
340 assert test == ht.NoType or callable(test)
342 if not hasattr(self, attr_name):
343 if default == ht.NoDefault:
344 raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
345 (self.OP_ID, attr_name),
348 if callable(default):
352 setattr(self, attr_name, dval)
354 if test == ht.NoType:
358 if set_defaults or hasattr(self, attr_name):
359 attr_val = getattr(self, attr_name)
360 if not test(attr_val):
361 logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
362 self.OP_ID, attr_name, type(attr_val), attr_val)
363 raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
364 (self.OP_ID, attr_name),
368 class OpCode(BaseOpCode):
371 This is the root of the actual OpCode hierarchy. All clases derived
372 from this class should override OP_ID.
374 @cvar OP_ID: The ID of this opcode. This should be unique amongst all
375 children of this class.
376 @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
377 string returned by Summary(); see the docstring of that
379 @cvar OP_PARAMS: List of opcode attributes, the default values they should
380 get if not already defined, and types they must match.
381 @cvar WITH_LU: Boolean that specifies whether this should be included in
382 mcpu's dispatch table
383 @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
385 @ivar priority: Opcode priority for queue
388 # pylint: disable-msg=E1101
389 # as OP_ID is dynamically defined
392 ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
393 ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
394 ("priority", constants.OP_PRIO_DEFAULT,
395 ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
398 def __getstate__(self):
399 """Specialized getstate for opcodes.
401 This method adds to the state dictionary the OP_ID of the class,
402 so that on unload we can identify the correct class for
403 instantiating the opcode.
406 @return: the state as a dictionary
409 data = BaseOpCode.__getstate__(self)
410 data["OP_ID"] = self.OP_ID
414 def LoadOpCode(cls, data):
415 """Generic load opcode method.
417 The method identifies the correct opcode class from the dict-form
418 by looking for a OP_ID key, if this is not found, or its value is
419 not available in this module as a child of this class, we fail.
422 @param data: the serialized opcode
425 if not isinstance(data, dict):
426 raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
427 if "OP_ID" not in data:
428 raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
429 op_id = data["OP_ID"]
431 if op_id in OP_MAPPING:
432 op_class = OP_MAPPING[op_id]
434 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
437 new_data = data.copy()
438 del new_data["OP_ID"]
439 op.__setstate__(new_data)
443 """Generates a summary description of this opcode.
445 The summary is the value of the OP_ID attribute (without the "OP_"
446 prefix), plus the value of the OP_DSC_FIELD attribute, if one was
447 defined; this field should allow to easily identify the operation
448 (for an instance creation job, e.g., it would be the instance
452 assert self.OP_ID is not None and len(self.OP_ID) > 3
453 # all OP_ID start with OP_, we remove that
455 field_name = getattr(self, "OP_DSC_FIELD", None)
457 field_value = getattr(self, field_name, None)
458 if isinstance(field_value, (list, tuple)):
459 field_value = ",".join(str(i) for i in field_value)
460 txt = "%s(%s)" % (txt, field_value)
466 class OpClusterPostInit(OpCode):
467 """Post cluster initialization.
469 This opcode does not touch the cluster at all. Its purpose is to run hooks
470 after the cluster has been initialized.
475 class OpClusterDestroy(OpCode):
476 """Destroy the cluster.
478 This opcode has no other parameters. All the state is irreversibly
479 lost after the execution of this opcode.
484 class OpClusterQuery(OpCode):
485 """Query cluster information."""
488 class OpClusterVerify(OpCode):
489 """Verify the cluster state.
491 @type skip_checks: C{list}
492 @ivar skip_checks: steps to be skipped from the verify process; this
493 needs to be a subset of
494 L{constants.VERIFY_OPTIONAL_CHECKS}; currently
495 only L{constants.VERIFY_NPLUSONE_MEM} can be passed
499 ("skip_checks", ht.EmptyList,
500 ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
501 ("verbose", False, ht.TBool, None),
502 ("error_codes", False, ht.TBool, None),
503 ("debug_simulate_errors", False, ht.TBool, None),
507 class OpClusterVerifyDisks(OpCode):
508 """Verify the cluster disks.
512 Result: a tuple of four elements:
513 - list of node names with bad data returned (unreachable, etc.)
514 - dict of node names with broken volume groups (values: error msg)
515 - list of instances with degraded disks (that should be activated)
516 - dict of instances with missing logical volumes (values: (node, vol)
517 pairs with details about the missing volumes)
519 In normal operation, all lists should be empty. A non-empty instance
520 list (3rd element of the result) is still ok (errors were fixed) but
521 non-empty node list means some node is down, and probably there are
522 unfixable drbd errors.
524 Note that only instances that are drbd-based are taken into
525 consideration. This might need to be revisited in the future.
530 class OpClusterRepairDiskSizes(OpCode):
531 """Verify the disk sizes of the instances and fixes configuration
534 Parameters: optional instances list, in case we want to restrict the
535 checks to only a subset of the instances.
537 Result: a list of tuples, (instance, disk, new-size) for changed
540 In normal operation, the list should be empty.
542 @type instances: list
543 @ivar instances: the list of instances to check, or empty for all instances
547 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
551 class OpClusterConfigQuery(OpCode):
552 """Query cluster configuration values."""
558 class OpClusterRename(OpCode):
559 """Rename the cluster.
562 @ivar name: The new name of the cluster. The name and/or the master IP
563 address will be changed to match the new name and its IP
567 OP_DSC_FIELD = "name"
569 ("name", ht.NoDefault, ht.TNonEmptyString, None),
573 class OpClusterSetParams(OpCode):
574 """Change the parameters of the cluster.
576 @type vg_name: C{str} or C{None}
577 @ivar vg_name: The new volume group name or None to disable LVM usage.
581 ("vg_name", None, ht.TMaybeString, "Volume group name"),
582 ("enabled_hypervisors", None,
583 ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
585 "List of enabled hypervisors"),
586 ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
588 "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
589 ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
590 "Cluster-wide backend parameter defaults"),
591 ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
593 "Cluster-wide per-OS hypervisor parameter defaults"),
594 ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
596 "Cluster-wide OS parameter defaults"),
597 ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
598 "Master candidate pool size"),
599 ("uid_pool", None, ht.NoType,
600 "Set UID pool, must be list of lists describing UID ranges (two items,"
601 " start and end inclusive)"),
602 ("add_uids", None, ht.NoType,
603 "Extend UID pool, must be list of lists describing UID ranges (two"
604 " items, start and end inclusive) to be added"),
605 ("remove_uids", None, ht.NoType,
606 "Shrink UID pool, must be list of lists describing UID ranges (two"
607 " items, start and end inclusive) to be removed"),
608 ("maintain_node_health", None, ht.TMaybeBool,
609 "Whether to automatically maintain node health"),
610 ("prealloc_wipe_disks", None, ht.TMaybeBool,
611 "Whether to wipe disks before allocating them to instances"),
612 ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
613 ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
614 ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
615 ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
616 "Default iallocator for cluster"),
617 ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
618 "Master network device"),
619 ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
620 "List of reserved LVs"),
621 ("hidden_os", None, _TestClusterOsList,
622 "Modify list of hidden operating systems. Each modification must have"
623 " two items, the operation and the OS name. The operation can be"
624 " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
625 ("blacklisted_os", None, _TestClusterOsList,
626 "Modify list of blacklisted operating systems. Each modification must have"
627 " two items, the operation and the OS name. The operation can be"
628 " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
632 class OpClusterRedistConf(OpCode):
633 """Force a full push of the cluster configuration.
638 class OpQuery(OpCode):
639 """Query for resources/items.
641 @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
642 @ivar fields: List of fields to retrieve
643 @ivar filter: Query filter
647 ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY),
648 "Resource(s) to query for"),
649 ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
651 ("filter", None, ht.TOr(ht.TNone,
652 ht.TListOf(ht.TOr(ht.TNonEmptyString, ht.TList))),
657 class OpQueryFields(OpCode):
658 """Query for available resource/item fields.
660 @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
661 @ivar fields: List of fields to retrieve
665 ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY), None),
666 ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)), None),
670 class OpOobCommand(OpCode):
671 """Interact with OOB."""
673 ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
674 ("command", None, ht.TElemOf(constants.OOB_COMMANDS), None),
675 ("timeout", constants.OOB_TIMEOUT, ht.TInt, None),
676 ("ignore_status", False, ht.TBool, None),
682 class OpNodeRemove(OpCode):
685 @type node_name: C{str}
686 @ivar node_name: The name of the node to remove. If the node still has
687 instances on it, the operation will fail.
690 OP_DSC_FIELD = "node_name"
696 class OpNodeAdd(OpCode):
697 """Add a node to the cluster.
699 @type node_name: C{str}
700 @ivar node_name: The name of the node to add. This can be a short name,
701 but it will be expanded to the FQDN.
702 @type primary_ip: IP address
703 @ivar primary_ip: The primary IP of the node. This will be ignored when the
704 opcode is submitted, but will be filled during the node
705 add (so it will be visible in the job query).
706 @type secondary_ip: IP address
707 @ivar secondary_ip: The secondary IP of the node. This needs to be passed
708 if the cluster has been initialized in 'dual-network'
709 mode, otherwise it must not be given.
711 @ivar readd: Whether to re-add an existing node to the cluster. If
712 this is not passed, then the operation will abort if the node
713 name is already in the cluster; use this parameter to 'repair'
714 a node that had its configuration broken, or was reinstalled
715 without removal from the cluster.
717 @ivar group: The node group to which this node will belong.
718 @type vm_capable: C{bool}
719 @ivar vm_capable: The vm_capable node attribute
720 @type master_capable: C{bool}
721 @ivar master_capable: The master_capable node attribute
724 OP_DSC_FIELD = "node_name"
727 ("primary_ip", None, ht.NoType, "Primary IP address"),
728 ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
729 ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
730 ("group", None, ht.TMaybeString, "Initial node group"),
731 ("master_capable", None, ht.TMaybeBool,
732 "Whether node can become master or master candidate"),
733 ("vm_capable", None, ht.TMaybeBool,
734 "Whether node can host instances"),
735 ("ndparams", None, ht.TMaybeDict, "Node parameters"),
739 class OpNodeQuery(OpCode):
740 """Compute the list of nodes."""
744 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
745 "Empty list to query all nodes, node names otherwise"),
749 class OpNodeQueryvols(OpCode):
750 """Get list of volumes on node."""
753 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
754 "Empty list to query all nodes, node names otherwise"),
758 class OpNodeQueryStorage(OpCode):
759 """Get information on storage for node(s)."""
763 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
764 ("name", None, ht.TMaybeString, "Storage name"),
768 class OpNodeModifyStorage(OpCode):
769 """Modifies the properies of a storage unit"""
774 ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
778 class OpRepairNodeStorage(OpCode):
779 """Repairs the volume group on a node."""
780 OP_DSC_FIELD = "node_name"
789 class OpNodeSetParams(OpCode):
790 """Change the parameters of a node."""
791 OP_DSC_FIELD = "node_name"
795 ("master_candidate", None, ht.TMaybeBool,
796 "Whether the node should become a master candidate"),
797 ("offline", None, ht.TMaybeBool,
798 "Whether the node should be marked as offline"),
799 ("drained", None, ht.TMaybeBool,
800 "Whether the node should be marked as drained"),
801 ("auto_promote", False, ht.TBool,
802 "Whether node(s) should be promoted to master candidate if necessary"),
803 ("master_capable", None, ht.TMaybeBool,
804 "Denote whether node can become master or master candidate"),
805 ("vm_capable", None, ht.TMaybeBool,
806 "Denote whether node can host instances"),
807 ("secondary_ip", None, ht.TMaybeString,
808 "Change node's secondary IP address"),
809 ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
810 ("powered", None, ht.TMaybeBool,
811 "Whether the node should be marked as powered"),
815 class OpNodePowercycle(OpCode):
816 """Tries to powercycle a node."""
817 OP_DSC_FIELD = "node_name"
824 class OpNodeMigrate(OpCode):
825 """Migrate all instances from a node."""
826 OP_DSC_FIELD = "node_name"
834 class OpNodeEvacStrategy(OpCode):
835 """Compute the evacuation strategy for a list of nodes."""
836 OP_DSC_FIELD = "nodes"
838 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
839 ("remote_node", None, ht.TMaybeString, None),
840 ("iallocator", None, ht.TMaybeString, None),
846 class OpInstanceCreate(OpCode):
847 """Create an instance.
849 @ivar instance_name: Instance name
850 @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
851 @ivar source_handshake: Signed handshake from source (remote import only)
852 @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
853 @ivar source_instance_name: Previous name of instance (remote import only)
854 @ivar source_shutdown_timeout: Shutdown timeout used for source instance
858 OP_DSC_FIELD = "instance_name"
864 ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
865 ("disks", ht.NoDefault,
866 # TODO: Generate check from constants.IDISK_PARAMS_TYPES
867 ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
868 ht.TOr(ht.TNonEmptyString, ht.TInt))),
869 "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
870 " each disk definition must contain a ``%s`` value and"
871 " can contain an optional ``%s`` value denoting the disk access mode"
873 (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
874 constants.IDISK_MODE,
875 " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
876 ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
877 ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
878 "Driver for file-backed disks"),
879 ("file_storage_dir", None, ht.TMaybeString,
880 "Directory for storing file-backed disks"),
881 ("hvparams", ht.EmptyDict, ht.TDict,
882 "Hypervisor parameters for instance, hypervisor-dependent"),
883 ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
884 ("iallocator", None, ht.TMaybeString,
885 "Iallocator for deciding which node(s) to use"),
886 ("identify_defaults", False, ht.TBool,
887 "Reset instance parameters to default if equal"),
888 ("ip_check", True, ht.TBool, _PIpCheckDoc),
889 ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
890 "Instance creation mode"),
891 ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
892 "List of NIC (network interface) definitions, for example"
893 " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
894 " contain the optional values %s" %
896 ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
897 ("no_install", None, ht.TMaybeBool,
898 "Do not install the OS (will disable automatic start)"),
899 ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
900 ("os_type", None, ht.TMaybeString, "Operating system"),
901 ("pnode", None, ht.TMaybeString, "Primary node"),
902 ("snode", None, ht.TMaybeString, "Secondary node"),
903 ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
904 "Signed handshake from source (remote import only)"),
905 ("source_instance_name", None, ht.TMaybeString,
906 "Source instance name (remote import only)"),
907 ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
909 "How long source instance was given to shut down (remote import only)"),
910 ("source_x509_ca", None, ht.TMaybeString,
911 "Source X509 CA in PEM format (remote import only)"),
912 ("src_node", None, ht.TMaybeString, "Source node for import"),
913 ("src_path", None, ht.TMaybeString, "Source directory for import"),
914 ("start", True, ht.TBool, "Whether to start instance after creation"),
918 class OpInstanceReinstall(OpCode):
919 """Reinstall an instance's OS."""
920 OP_DSC_FIELD = "instance_name"
924 ("os_type", None, ht.TMaybeString, "Instance operating system"),
925 ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
929 class OpInstanceRemove(OpCode):
930 """Remove an instance."""
931 OP_DSC_FIELD = "instance_name"
935 ("ignore_failures", False, ht.TBool,
936 "Whether to ignore failures during removal"),
940 class OpInstanceRename(OpCode):
941 """Rename an instance."""
945 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
946 ("ip_check", False, ht.TBool, _PIpCheckDoc),
950 class OpInstanceStartup(OpCode):
951 """Startup an instance."""
952 OP_DSC_FIELD = "instance_name"
956 _PIgnoreOfflineNodes,
957 ("hvparams", ht.EmptyDict, ht.TDict,
958 "Temporary hypervisor parameters, hypervisor-dependent"),
959 ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
963 class OpInstanceShutdown(OpCode):
964 """Shutdown an instance."""
965 OP_DSC_FIELD = "instance_name"
968 _PIgnoreOfflineNodes,
969 ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
970 "How long to wait for instance to shut down"),
974 class OpInstanceReboot(OpCode):
975 """Reboot an instance."""
976 OP_DSC_FIELD = "instance_name"
980 ("ignore_secondaries", False, ht.TBool,
981 "Whether to start the instance even if secondary disks are failing"),
982 ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
983 "How to reboot instance"),
987 class OpInstanceReplaceDisks(OpCode):
988 """Replace the disks of an instance."""
989 OP_DSC_FIELD = "instance_name"
992 ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
994 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
996 ("remote_node", None, ht.TMaybeString, "New secondary node"),
997 ("iallocator", None, ht.TMaybeString,
998 "Iallocator for deciding new secondary node"),
999 ("early_release", False, ht.TBool,
1000 "Whether to release locks as soon as possible"),
1004 class OpInstanceFailover(OpCode):
1005 """Failover an instance."""
1006 OP_DSC_FIELD = "instance_name"
1010 _PIgnoreConsistency,
1014 class OpInstanceMigrate(OpCode):
1015 """Migrate an instance.
1017 This migrates (without shutting down an instance) to its secondary
1020 @ivar instance_name: the name of the instance
1021 @ivar mode: the migration mode (live, non-live or None for auto)
1024 OP_DSC_FIELD = "instance_name"
1029 ("cleanup", False, ht.TBool,
1030 "Whether a previously failed migration should be cleaned up"),
1034 class OpInstanceMove(OpCode):
1035 """Move an instance.
1037 This move (with shutting down an instance and data copying) to an
1040 @ivar instance_name: the name of the instance
1041 @ivar target_node: the destination node
1044 OP_DSC_FIELD = "instance_name"
1048 ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1052 class OpInstanceConsole(OpCode):
1053 """Connect to an instance's console."""
1054 OP_DSC_FIELD = "instance_name"
1060 class OpInstanceActivateDisks(OpCode):
1061 """Activate an instance's disks."""
1062 OP_DSC_FIELD = "instance_name"
1065 ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1069 class OpInstanceDeactivateDisks(OpCode):
1070 """Deactivate an instance's disks."""
1071 OP_DSC_FIELD = "instance_name"
1078 class OpInstanceRecreateDisks(OpCode):
1079 """Deactivate an instance's disks."""
1080 OP_DSC_FIELD = "instance_name"
1083 ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1084 "List of disk indexes"),
1088 class OpInstanceQuery(OpCode):
1089 """Compute the list of instances."""
1093 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1094 "Empty list to query all instances, instance names otherwise"),
1098 class OpInstanceQueryData(OpCode):
1099 """Compute the run-time status of instances."""
1101 ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1102 ("static", False, ht.TBool, None),
1106 class OpInstanceSetParams(OpCode):
1107 """Change the parameters of an instance."""
1108 OP_DSC_FIELD = "instance_name"
1113 # TODO: Use _TestNicDef
1114 ("nics", ht.EmptyList, ht.TList,
1115 "List of NIC changes. Each item is of the form ``(op, settings)``."
1116 " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1117 " ``%s`` to remove the last NIC or a number to modify the settings"
1118 " of the NIC with that index." %
1119 (constants.DDM_ADD, constants.DDM_REMOVE)),
1120 ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1121 ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1122 ("hvparams", ht.EmptyDict, ht.TDict,
1123 "Per-instance hypervisor parameters, hypervisor-dependent"),
1124 ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1125 "Disk template for instance"),
1126 ("remote_node", None, ht.TMaybeString,
1127 "Secondary node (used when changing disk template)"),
1128 ("os_name", None, ht.TMaybeString,
1129 "Change instance's OS name. Does not reinstall the instance."),
1130 ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1134 class OpInstanceGrowDisk(OpCode):
1135 """Grow a disk of an instance."""
1136 OP_DSC_FIELD = "instance_name"
1140 ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1141 ("amount", ht.NoDefault, ht.TInt,
1142 "Amount of disk space to add (megabytes)"),
1146 # Node group opcodes
1148 class OpGroupAdd(OpCode):
1149 """Add a node group to the cluster."""
1150 OP_DSC_FIELD = "group_name"
1153 _PNodeGroupAllocPolicy,
1158 class OpGroupAssignNodes(OpCode):
1159 """Assign nodes to a node group."""
1160 OP_DSC_FIELD = "group_name"
1164 ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1165 "List of nodes to assign"),
1169 class OpGroupQuery(OpCode):
1170 """Compute the list of node groups."""
1173 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1174 "Empty list to query all groups, group names otherwise"),
1178 class OpGroupSetParams(OpCode):
1179 """Change the parameters of a node group."""
1180 OP_DSC_FIELD = "group_name"
1183 _PNodeGroupAllocPolicy,
1188 class OpGroupRemove(OpCode):
1189 """Remove a node group from the cluster."""
1190 OP_DSC_FIELD = "group_name"
1196 class OpGroupRename(OpCode):
1197 """Rename a node group in the cluster."""
1200 ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1205 class OpOsDiagnose(OpCode):
1206 """Compute the list of guest operating systems."""
1209 ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1210 "Which operating systems to diagnose"),
1215 class OpBackupQuery(OpCode):
1216 """Compute the list of exported images."""
1219 ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1220 "Empty list to query all nodes, node names otherwise"),
1224 class OpBackupPrepare(OpCode):
1225 """Prepares an instance export.
1227 @ivar instance_name: Instance name
1228 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1231 OP_DSC_FIELD = "instance_name"
1234 ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1239 class OpBackupExport(OpCode):
1240 """Export an instance.
1242 For local exports, the export destination is the node name. For remote
1243 exports, the export destination is a list of tuples, each consisting of
1244 hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1245 the cluster domain secret over the value "${index}:${hostname}:${port}". The
1246 destination X509 CA must be a signed certificate.
1248 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1249 @ivar target_node: Export destination
1250 @ivar x509_key_name: X509 key to use (remote export only)
1251 @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1255 OP_DSC_FIELD = "instance_name"
1259 # TODO: Rename target_node as it changes meaning for different export modes
1260 # (e.g. "destination")
1261 ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1262 "Destination information, depends on export mode"),
1263 ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1264 ("remove_instance", False, ht.TBool,
1265 "Whether to remove instance after export"),
1266 ("ignore_remove_failures", False, ht.TBool,
1267 "Whether to ignore failures while removing instances"),
1268 ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1270 ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1271 "Name of X509 key (remote export only)"),
1272 ("destination_x509_ca", None, ht.TMaybeString,
1273 "Destination X509 CA (remote export only)"),
1277 class OpBackupRemove(OpCode):
1278 """Remove an instance's export."""
1279 OP_DSC_FIELD = "instance_name"
1286 class OpTagsGet(OpCode):
1287 """Returns the tags of the given object."""
1288 OP_DSC_FIELD = "name"
1291 # Name is only meaningful for nodes and instances
1292 ("name", ht.NoDefault, ht.TMaybeString, None),
1296 class OpTagsSearch(OpCode):
1297 """Searches the tags in the cluster for a given pattern."""
1298 OP_DSC_FIELD = "pattern"
1300 ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1304 class OpTagsSet(OpCode):
1305 """Add a list of tags on a given object."""
1309 # Name is only meaningful for nodes and instances
1310 ("name", ht.NoDefault, ht.TMaybeString, None),
1314 class OpTagsDel(OpCode):
1315 """Remove a list of tags from a given object."""
1319 # Name is only meaningful for nodes and instances
1320 ("name", ht.NoDefault, ht.TMaybeString, None),
1324 class OpTestDelay(OpCode):
1325 """Sleeps for a configured amount of time.
1327 This is used just for debugging and testing.
1330 - duration: the time to sleep
1331 - on_master: if true, sleep on the master
1332 - on_nodes: list of nodes in which to sleep
1334 If the on_master parameter is true, it will execute a sleep on the
1335 master (before any node sleep).
1337 If the on_nodes list is not empty, it will sleep on those nodes
1338 (after the sleep on the master, if that is enabled).
1340 As an additional feature, the case of duration < 0 will be reported
1341 as an execution error, so this opcode can be used as a failure
1342 generator. The case of duration == 0 will not be treated specially.
1345 OP_DSC_FIELD = "duration"
1347 ("duration", ht.NoDefault, ht.TFloat, None),
1348 ("on_master", True, ht.TBool, None),
1349 ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1350 ("repeat", 0, ht.TPositiveInt, None),
1354 class OpTestAllocator(OpCode):
1355 """Allocator framework testing.
1357 This opcode has two modes:
1358 - gather and return allocator input for a given mode (allocate new
1359 or replace secondary) and a given instance definition (direction
1361 - run a selected allocator for a given operation (as above) and
1362 return the allocator output (direction 'out')
1365 OP_DSC_FIELD = "allocator"
1367 ("direction", ht.NoDefault,
1368 ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1369 ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1370 ("name", ht.NoDefault, ht.TNonEmptyString, None),
1371 ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1372 ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
1373 ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1374 ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1375 ("hypervisor", None, ht.TMaybeString, None),
1376 ("allocator", None, ht.TMaybeString, None),
1377 ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1378 ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1379 ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1380 ("os", None, ht.TMaybeString, None),
1381 ("disk_template", None, ht.TMaybeString, None),
1382 ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1387 class OpTestJqueue(OpCode):
1388 """Utility opcode to test some aspects of the job queue.
1392 ("notify_waitlock", False, ht.TBool, None),
1393 ("notify_exec", False, ht.TBool, None),
1394 ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1395 ("fail", False, ht.TBool, None),
1399 class OpTestDummy(OpCode):
1400 """Utility opcode used by unittests.
1404 ("result", ht.NoDefault, ht.NoType, None),
1405 ("messages", ht.NoDefault, ht.NoType, None),
1406 ("fail", ht.NoDefault, ht.NoType, None),
1412 """Returns list of all defined opcodes.
1414 Does not eliminate duplicates by C{OP_ID}.
1417 return [v for v in globals().values()
1418 if (isinstance(v, type) and issubclass(v, OpCode) and
1419 hasattr(v, "OP_ID") and v is not OpCode)]
1422 OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())