4 # Copyright (C) 2006, 2007, 2008, 2009, 2010 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
37 class BaseOpCode(object):
38 """A simple serializable object.
40 This object serves as a parent class for OpCode without any custom
46 def __init__(self, **kwargs):
47 """Constructor for BaseOpCode.
49 The constructor takes only keyword arguments and will set
50 attributes on this object based on the passed arguments. As such,
51 it means that you should not pass arguments which are not in the
52 __slots__ attribute for this class.
55 slots = self._all_slots()
58 raise TypeError("Object %s doesn't support the parameter '%s'" %
59 (self.__class__.__name__, key))
60 setattr(self, key, kwargs[key])
62 def __getstate__(self):
63 """Generic serializer.
65 This method just returns the contents of the instance as a
69 @return: the instance attributes and their values
73 for name in self._all_slots():
74 if hasattr(self, name):
75 state[name] = getattr(self, name)
78 def __setstate__(self, state):
79 """Generic unserializer.
81 This method just restores from the serialized state the attributes
82 of the current instance.
84 @param state: the serialized opcode data
88 if not isinstance(state, dict):
89 raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
92 for name in self._all_slots():
93 if name not in state and hasattr(self, name):
97 setattr(self, name, state[name])
101 """Compute the list of all declared slots for a class.
105 for parent in cls.__mro__:
106 slots.extend(getattr(parent, "__slots__", []))
110 class OpCode(BaseOpCode):
113 This is the root of the actual OpCode hierarchy. All clases derived
114 from this class should override OP_ID.
116 @cvar OP_ID: The ID of this opcode. This should be unique amongst all
117 children of this class.
118 @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
120 @ivar priority: Opcode priority for queue
123 OP_ID = "OP_ABSTRACT"
124 __slots__ = ["dry_run", "debug_level", "priority"]
126 def __getstate__(self):
127 """Specialized getstate for opcodes.
129 This method adds to the state dictionary the OP_ID of the class,
130 so that on unload we can identify the correct class for
131 instantiating the opcode.
134 @return: the state as a dictionary
137 data = BaseOpCode.__getstate__(self)
138 data["OP_ID"] = self.OP_ID
142 def LoadOpCode(cls, data):
143 """Generic load opcode method.
145 The method identifies the correct opcode class from the dict-form
146 by looking for a OP_ID key, if this is not found, or its value is
147 not available in this module as a child of this class, we fail.
150 @param data: the serialized opcode
153 if not isinstance(data, dict):
154 raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
155 if "OP_ID" not in data:
156 raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
157 op_id = data["OP_ID"]
159 if op_id in OP_MAPPING:
160 op_class = OP_MAPPING[op_id]
162 raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
165 new_data = data.copy()
166 del new_data["OP_ID"]
167 op.__setstate__(new_data)
171 """Generates a summary description of this opcode.
174 # all OP_ID start with OP_, we remove that
176 field_name = getattr(self, "OP_DSC_FIELD", None)
178 field_value = getattr(self, field_name, None)
179 if isinstance(field_value, (list, tuple)):
180 field_value = ",".join(str(i) for i in field_value)
181 txt = "%s(%s)" % (txt, field_value)
187 class OpPostInitCluster(OpCode):
188 """Post cluster initialization.
190 This opcode does not touch the cluster at all. Its purpose is to run hooks
191 after the cluster has been initialized.
194 OP_ID = "OP_CLUSTER_POST_INIT"
198 class OpDestroyCluster(OpCode):
199 """Destroy the cluster.
201 This opcode has no other parameters. All the state is irreversibly
202 lost after the execution of this opcode.
205 OP_ID = "OP_CLUSTER_DESTROY"
209 class OpQueryClusterInfo(OpCode):
210 """Query cluster information."""
211 OP_ID = "OP_CLUSTER_QUERY"
215 class OpVerifyCluster(OpCode):
216 """Verify the cluster state.
218 @type skip_checks: C{list}
219 @ivar skip_checks: steps to be skipped from the verify process; this
220 needs to be a subset of
221 L{constants.VERIFY_OPTIONAL_CHECKS}; currently
222 only L{constants.VERIFY_NPLUSONE_MEM} can be passed
225 OP_ID = "OP_CLUSTER_VERIFY"
226 __slots__ = ["skip_checks", "verbose", "error_codes",
227 "debug_simulate_errors"]
230 class OpVerifyDisks(OpCode):
231 """Verify the cluster disks.
235 Result: a tuple of four elements:
236 - list of node names with bad data returned (unreachable, etc.)
237 - dict of node names with broken volume groups (values: error msg)
238 - list of instances with degraded disks (that should be activated)
239 - dict of instances with missing logical volumes (values: (node, vol)
240 pairs with details about the missing volumes)
242 In normal operation, all lists should be empty. A non-empty instance
243 list (3rd element of the result) is still ok (errors were fixed) but
244 non-empty node list means some node is down, and probably there are
245 unfixable drbd errors.
247 Note that only instances that are drbd-based are taken into
248 consideration. This might need to be revisited in the future.
251 OP_ID = "OP_CLUSTER_VERIFY_DISKS"
255 class OpRepairDiskSizes(OpCode):
256 """Verify the disk sizes of the instances and fixes configuration
259 Parameters: optional instances list, in case we want to restrict the
260 checks to only a subset of the instances.
262 Result: a list of tuples, (instance, disk, new-size) for changed
265 In normal operation, the list should be empty.
267 @type instances: list
268 @ivar instances: the list of instances to check, or empty for all instances
271 OP_ID = "OP_CLUSTER_REPAIR_DISK_SIZES"
272 __slots__ = ["instances"]
275 class OpQueryConfigValues(OpCode):
276 """Query cluster configuration values."""
277 OP_ID = "OP_CLUSTER_CONFIG_QUERY"
278 __slots__ = ["output_fields"]
281 class OpRenameCluster(OpCode):
282 """Rename the cluster.
285 @ivar name: The new name of the cluster. The name and/or the master IP
286 address will be changed to match the new name and its IP
290 OP_ID = "OP_CLUSTER_RENAME"
291 OP_DSC_FIELD = "name"
295 class OpSetClusterParams(OpCode):
296 """Change the parameters of the cluster.
298 @type vg_name: C{str} or C{None}
299 @ivar vg_name: The new volume group name or None to disable LVM usage.
302 OP_ID = "OP_CLUSTER_SET_PARAMS"
306 "enabled_hypervisors",
312 "candidate_pool_size",
313 "maintain_node_health",
317 "default_iallocator",
324 class OpRedistributeConfig(OpCode):
325 """Force a full push of the cluster configuration.
328 OP_ID = "OP_CLUSTER_REDIST_CONF"
333 class OpRemoveNode(OpCode):
336 @type node_name: C{str}
337 @ivar node_name: The name of the node to remove. If the node still has
338 instances on it, the operation will fail.
341 OP_ID = "OP_NODE_REMOVE"
342 OP_DSC_FIELD = "node_name"
343 __slots__ = ["node_name"]
346 class OpAddNode(OpCode):
347 """Add a node to the cluster.
349 @type node_name: C{str}
350 @ivar node_name: The name of the node to add. This can be a short name,
351 but it will be expanded to the FQDN.
352 @type primary_ip: IP address
353 @ivar primary_ip: The primary IP of the node. This will be ignored when the
354 opcode is submitted, but will be filled during the node
355 add (so it will be visible in the job query).
356 @type secondary_ip: IP address
357 @ivar secondary_ip: The secondary IP of the node. This needs to be passed
358 if the cluster has been initialized in 'dual-network'
359 mode, otherwise it must not be given.
361 @ivar readd: Whether to re-add an existing node to the cluster. If
362 this is not passed, then the operation will abort if the node
363 name is already in the cluster; use this parameter to 'repair'
364 a node that had its configuration broken, or was reinstalled
365 without removal from the cluster.
368 OP_ID = "OP_NODE_ADD"
369 OP_DSC_FIELD = "node_name"
370 __slots__ = ["node_name", "primary_ip", "secondary_ip", "readd", "nodegroup"]
373 class OpQueryNodes(OpCode):
374 """Compute the list of nodes."""
375 OP_ID = "OP_NODE_QUERY"
376 __slots__ = ["output_fields", "names", "use_locking"]
379 class OpQueryNodeVolumes(OpCode):
380 """Get list of volumes on node."""
381 OP_ID = "OP_NODE_QUERYVOLS"
382 __slots__ = ["nodes", "output_fields"]
385 class OpQueryNodeStorage(OpCode):
386 """Get information on storage for node(s)."""
387 OP_ID = "OP_NODE_QUERY_STORAGE"
396 class OpModifyNodeStorage(OpCode):
397 """Modifies the properies of a storage unit"""
398 OP_ID = "OP_NODE_MODIFY_STORAGE"
407 class OpRepairNodeStorage(OpCode):
408 """Repairs the volume group on a node."""
409 OP_ID = "OP_REPAIR_NODE_STORAGE"
410 OP_DSC_FIELD = "node_name"
415 "ignore_consistency",
419 class OpSetNodeParams(OpCode):
420 """Change the parameters of a node."""
421 OP_ID = "OP_NODE_SET_PARAMS"
422 OP_DSC_FIELD = "node_name"
433 class OpPowercycleNode(OpCode):
434 """Tries to powercycle a node."""
435 OP_ID = "OP_NODE_POWERCYCLE"
436 OP_DSC_FIELD = "node_name"
443 class OpMigrateNode(OpCode):
444 """Migrate all instances from a node."""
445 OP_ID = "OP_NODE_MIGRATE"
446 OP_DSC_FIELD = "node_name"
454 class OpNodeEvacuationStrategy(OpCode):
455 """Compute the evacuation strategy for a list of nodes."""
456 OP_ID = "OP_NODE_EVAC_STRATEGY"
457 OP_DSC_FIELD = "nodes"
458 __slots__ = ["nodes", "iallocator", "remote_node"]
463 class OpCreateInstance(OpCode):
464 """Create an instance.
466 @ivar instance_name: Instance name
467 @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
468 @ivar source_handshake: Signed handshake from source (remote import only)
469 @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
470 @ivar source_instance_name: Previous name of instance (remote import only)
473 OP_ID = "OP_INSTANCE_CREATE"
474 OP_DSC_FIELD = "instance_name"
477 "os_type", "force_variant", "no_install",
478 "pnode", "disk_template", "snode", "mode",
480 "src_node", "src_path", "start", "identify_defaults",
481 "wait_for_sync", "ip_check", "name_check",
482 "file_storage_dir", "file_driver",
484 "hypervisor", "hvparams", "beparams", "osparams",
487 "source_instance_name",
491 class OpReinstallInstance(OpCode):
492 """Reinstall an instance's OS."""
493 OP_ID = "OP_INSTANCE_REINSTALL"
494 OP_DSC_FIELD = "instance_name"
495 __slots__ = ["instance_name", "os_type", "force_variant"]
498 class OpRemoveInstance(OpCode):
499 """Remove an instance."""
500 OP_ID = "OP_INSTANCE_REMOVE"
501 OP_DSC_FIELD = "instance_name"
509 class OpRenameInstance(OpCode):
510 """Rename an instance."""
511 OP_ID = "OP_INSTANCE_RENAME"
513 "instance_name", "ip_check", "new_name", "name_check",
517 class OpStartupInstance(OpCode):
518 """Startup an instance."""
519 OP_ID = "OP_INSTANCE_STARTUP"
520 OP_DSC_FIELD = "instance_name"
522 "instance_name", "force", "hvparams", "beparams",
526 class OpShutdownInstance(OpCode):
527 """Shutdown an instance."""
528 OP_ID = "OP_INSTANCE_SHUTDOWN"
529 OP_DSC_FIELD = "instance_name"
530 __slots__ = ["instance_name", "timeout"]
533 class OpRebootInstance(OpCode):
534 """Reboot an instance."""
535 OP_ID = "OP_INSTANCE_REBOOT"
536 OP_DSC_FIELD = "instance_name"
538 "instance_name", "reboot_type", "ignore_secondaries", "shutdown_timeout",
542 class OpReplaceDisks(OpCode):
543 """Replace the disks of an instance."""
544 OP_ID = "OP_INSTANCE_REPLACE_DISKS"
545 OP_DSC_FIELD = "instance_name"
547 "instance_name", "remote_node", "mode", "disks", "iallocator",
552 class OpFailoverInstance(OpCode):
553 """Failover an instance."""
554 OP_ID = "OP_INSTANCE_FAILOVER"
555 OP_DSC_FIELD = "instance_name"
557 "instance_name", "ignore_consistency", "shutdown_timeout",
561 class OpMigrateInstance(OpCode):
562 """Migrate an instance.
564 This migrates (without shutting down an instance) to its secondary
567 @ivar instance_name: the name of the instance
568 @ivar mode: the migration mode (live, non-live or None for auto)
571 OP_ID = "OP_INSTANCE_MIGRATE"
572 OP_DSC_FIELD = "instance_name"
573 __slots__ = ["instance_name", "mode", "cleanup", "live"]
576 class OpMoveInstance(OpCode):
579 This move (with shutting down an instance and data copying) to an
582 @ivar instance_name: the name of the instance
583 @ivar target_node: the destination node
586 OP_ID = "OP_INSTANCE_MOVE"
587 OP_DSC_FIELD = "instance_name"
589 "instance_name", "target_node", "shutdown_timeout",
593 class OpConnectConsole(OpCode):
594 """Connect to an instance's console."""
595 OP_ID = "OP_INSTANCE_CONSOLE"
596 OP_DSC_FIELD = "instance_name"
597 __slots__ = ["instance_name"]
600 class OpActivateInstanceDisks(OpCode):
601 """Activate an instance's disks."""
602 OP_ID = "OP_INSTANCE_ACTIVATE_DISKS"
603 OP_DSC_FIELD = "instance_name"
604 __slots__ = ["instance_name", "ignore_size"]
607 class OpDeactivateInstanceDisks(OpCode):
608 """Deactivate an instance's disks."""
609 OP_ID = "OP_INSTANCE_DEACTIVATE_DISKS"
610 OP_DSC_FIELD = "instance_name"
611 __slots__ = ["instance_name"]
614 class OpRecreateInstanceDisks(OpCode):
615 """Deactivate an instance's disks."""
616 OP_ID = "OP_INSTANCE_RECREATE_DISKS"
617 OP_DSC_FIELD = "instance_name"
618 __slots__ = ["instance_name", "disks"]
621 class OpQueryInstances(OpCode):
622 """Compute the list of instances."""
623 OP_ID = "OP_INSTANCE_QUERY"
624 __slots__ = ["output_fields", "names", "use_locking"]
627 class OpQueryInstanceData(OpCode):
628 """Compute the run-time status of instances."""
629 OP_ID = "OP_INSTANCE_QUERY_DATA"
630 __slots__ = ["instances", "static"]
633 class OpSetInstanceParams(OpCode):
634 """Change the parameters of an instance."""
635 OP_ID = "OP_INSTANCE_SET_PARAMS"
636 OP_DSC_FIELD = "instance_name"
639 "hvparams", "beparams", "osparams", "force",
640 "nics", "disks", "disk_template",
641 "remote_node", "os_name", "force_variant",
645 class OpGrowDisk(OpCode):
646 """Grow a disk of an instance."""
647 OP_ID = "OP_INSTANCE_GROW_DISK"
648 OP_DSC_FIELD = "instance_name"
650 "instance_name", "disk", "amount", "wait_for_sync",
655 class OpDiagnoseOS(OpCode):
656 """Compute the list of guest operating systems."""
657 OP_ID = "OP_OS_DIAGNOSE"
658 __slots__ = ["output_fields", "names"]
662 class OpQueryExports(OpCode):
663 """Compute the list of exported images."""
664 OP_ID = "OP_BACKUP_QUERY"
665 __slots__ = ["nodes", "use_locking"]
668 class OpPrepareExport(OpCode):
669 """Prepares an instance export.
671 @ivar instance_name: Instance name
672 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
675 OP_ID = "OP_BACKUP_PREPARE"
676 OP_DSC_FIELD = "instance_name"
678 "instance_name", "mode",
682 class OpExportInstance(OpCode):
683 """Export an instance.
685 For local exports, the export destination is the node name. For remote
686 exports, the export destination is a list of tuples, each consisting of
687 hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
688 the cluster domain secret over the value "${index}:${hostname}:${port}". The
689 destination X509 CA must be a signed certificate.
691 @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
692 @ivar target_node: Export destination
693 @ivar x509_key_name: X509 key to use (remote export only)
694 @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
698 OP_ID = "OP_BACKUP_EXPORT"
699 OP_DSC_FIELD = "instance_name"
701 # TODO: Rename target_node as it changes meaning for different export modes
702 # (e.g. "destination")
703 "instance_name", "target_node", "shutdown", "shutdown_timeout",
705 "ignore_remove_failures",
708 "destination_x509_ca",
712 class OpRemoveExport(OpCode):
713 """Remove an instance's export."""
714 OP_ID = "OP_BACKUP_REMOVE"
715 OP_DSC_FIELD = "instance_name"
716 __slots__ = ["instance_name"]
720 class OpGetTags(OpCode):
721 """Returns the tags of the given object."""
722 OP_ID = "OP_TAGS_GET"
723 OP_DSC_FIELD = "name"
724 __slots__ = ["kind", "name"]
727 class OpSearchTags(OpCode):
728 """Searches the tags in the cluster for a given pattern."""
729 OP_ID = "OP_TAGS_SEARCH"
730 OP_DSC_FIELD = "pattern"
731 __slots__ = ["pattern"]
734 class OpAddTags(OpCode):
735 """Add a list of tags on a given object."""
736 OP_ID = "OP_TAGS_SET"
737 __slots__ = ["kind", "name", "tags"]
740 class OpDelTags(OpCode):
741 """Remove a list of tags from a given object."""
742 OP_ID = "OP_TAGS_DEL"
743 __slots__ = ["kind", "name", "tags"]
747 class OpTestDelay(OpCode):
748 """Sleeps for a configured amount of time.
750 This is used just for debugging and testing.
753 - duration: the time to sleep
754 - on_master: if true, sleep on the master
755 - on_nodes: list of nodes in which to sleep
757 If the on_master parameter is true, it will execute a sleep on the
758 master (before any node sleep).
760 If the on_nodes list is not empty, it will sleep on those nodes
761 (after the sleep on the master, if that is enabled).
763 As an additional feature, the case of duration < 0 will be reported
764 as an execution error, so this opcode can be used as a failure
765 generator. The case of duration == 0 will not be treated specially.
768 OP_ID = "OP_TEST_DELAY"
769 OP_DSC_FIELD = "duration"
770 __slots__ = ["duration", "on_master", "on_nodes", "repeat"]
773 class OpTestAllocator(OpCode):
774 """Allocator framework testing.
776 This opcode has two modes:
777 - gather and return allocator input for a given mode (allocate new
778 or replace secondary) and a given instance definition (direction
780 - run a selected allocator for a given operation (as above) and
781 return the allocator output (direction 'out')
784 OP_ID = "OP_TEST_ALLOCATOR"
785 OP_DSC_FIELD = "allocator"
787 "direction", "mode", "allocator", "name",
788 "mem_size", "disks", "disk_template",
789 "os", "tags", "nics", "vcpus", "hypervisor",
794 class OpTestJobqueue(OpCode):
795 """Utility opcode to test some aspects of the job queue.
798 OP_ID = "OP_TEST_JQUEUE"
807 class OpTestDummy(OpCode):
808 """Utility opcode used by unittests.
811 OP_ID = "OP_TEST_DUMMY"
819 OP_MAPPING = dict([(v.OP_ID, v) for v in globals().values()
820 if (isinstance(v, type) and issubclass(v, OpCode) and
821 hasattr(v, "OP_ID"))])