3aed41e0cd75e2bb41958bbfd9b37e8f7fc75da8
[ganeti-local] / lib / opcodes.py
1 #
2 #
3
4 # Copyright (C) 2006, 2007 Google Inc.
5 #
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.
10 #
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.
15 #
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
19 # 02110-1301, USA.
20
21
22 """OpCodes module
23
24 This module implements the data structures which define the cluster
25 operations - the so-called opcodes.
26
27 Every operation which modifies the cluster state is expressed via
28 opcodes.
29
30 """
31
32 # this are practically structures, so disable the message about too
33 # few public methods:
34 # pylint: disable-msg=R0903
35
36
37 class BaseOpCode(object):
38   """A simple serializable object.
39
40   This object serves as a parent class for OpCode without any custom
41   field handling.
42
43   """
44   __slots__ = []
45
46   def __init__(self, **kwargs):
47     """Constructor for BaseOpCode.
48
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.
53
54     """
55     for key in kwargs:
56       if key not in self.__slots__:
57         raise TypeError("Object %s doesn't support the parameter '%s'" %
58                         (self.__class__.__name__, key))
59       setattr(self, key, kwargs[key])
60
61   def __getstate__(self):
62     """Generic serializer.
63
64     This method just returns the contents of the instance as a
65     dictionary.
66
67     @rtype:  C{dict}
68     @return: the instance attributes and their values
69
70     """
71     state = {}
72     for name in self.__slots__:
73       if hasattr(self, name):
74         state[name] = getattr(self, name)
75     return state
76
77   def __setstate__(self, state):
78     """Generic unserializer.
79
80     This method just restores from the serialized state the attributes
81     of the current instance.
82
83     @param state: the serialized opcode data
84     @type state:  C{dict}
85
86     """
87     if not isinstance(state, dict):
88       raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
89                        type(state))
90
91     for name in self.__slots__:
92       if name not in state:
93         delattr(self, name)
94
95     for name in state:
96       setattr(self, name, state[name])
97
98
99 class OpCode(BaseOpCode):
100   """Abstract OpCode.
101
102   This is the root of the actual OpCode hierarchy. All clases derived
103   from this class should override OP_ID.
104
105   @cvar OP_ID: The ID of this opcode. This should be unique amongst all
106                children of this class.
107   @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
108                  the check steps
109
110   """
111   OP_ID = "OP_ABSTRACT"
112   __slots__ = ["dry_run"]
113
114   def __getstate__(self):
115     """Specialized getstate for opcodes.
116
117     This method adds to the state dictionary the OP_ID of the class,
118     so that on unload we can identify the correct class for
119     instantiating the opcode.
120
121     @rtype:   C{dict}
122     @return:  the state as a dictionary
123
124     """
125     data = BaseOpCode.__getstate__(self)
126     data["OP_ID"] = self.OP_ID
127     return data
128
129   @classmethod
130   def LoadOpCode(cls, data):
131     """Generic load opcode method.
132
133     The method identifies the correct opcode class from the dict-form
134     by looking for a OP_ID key, if this is not found, or its value is
135     not available in this module as a child of this class, we fail.
136
137     @type data:  C{dict}
138     @param data: the serialized opcode
139
140     """
141     if not isinstance(data, dict):
142       raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
143     if "OP_ID" not in data:
144       raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
145     op_id = data["OP_ID"]
146     op_class = None
147     if op_id in OP_MAPPING:
148       op_class = OP_MAPPING[op_id]
149     else:
150       raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
151                        op_id)
152     op = op_class()
153     new_data = data.copy()
154     del new_data["OP_ID"]
155     op.__setstate__(new_data)
156     return op
157
158   def Summary(self):
159     """Generates a summary description of this opcode.
160
161     """
162     # all OP_ID start with OP_, we remove that
163     txt = self.OP_ID[3:]
164     field_name = getattr(self, "OP_DSC_FIELD", None)
165     if field_name:
166       field_value = getattr(self, field_name, None)
167       txt = "%s(%s)" % (txt, field_value)
168     return txt
169
170
171 # cluster opcodes
172
173 class OpPostInitCluster(OpCode):
174   """Post cluster initialization.
175
176   This opcode does not touch the cluster at all. Its purpose is to run hooks
177   after the cluster has been initialized.
178
179   """
180   OP_ID = "OP_CLUSTER_POST_INIT"
181   __slots__ = []
182
183
184 class OpDestroyCluster(OpCode):
185   """Destroy the cluster.
186
187   This opcode has no other parameters. All the state is irreversibly
188   lost after the execution of this opcode.
189
190   """
191   OP_ID = "OP_CLUSTER_DESTROY"
192   __slots__ = []
193
194
195 class OpQueryClusterInfo(OpCode):
196   """Query cluster information."""
197   OP_ID = "OP_CLUSTER_QUERY"
198   __slots__ = []
199
200
201 class OpVerifyCluster(OpCode):
202   """Verify the cluster state.
203
204   @type skip_checks: C{list}
205   @ivar skip_checks: steps to be skipped from the verify process; this
206                      needs to be a subset of
207                      L{constants.VERIFY_OPTIONAL_CHECKS}; currently
208                      only L{constants.VERIFY_NPLUSONE_MEM} can be passed
209
210   """
211   OP_ID = "OP_CLUSTER_VERIFY"
212   __slots__ = ["skip_checks", "verbose", "error_codes",
213                "debug_simulate_errors"]
214
215
216 class OpVerifyDisks(OpCode):
217   """Verify the cluster disks.
218
219   Parameters: none
220
221   Result: a tuple of four elements:
222     - list of node names with bad data returned (unreachable, etc.)
223     - dict of node names with broken volume groups (values: error msg)
224     - list of instances with degraded disks (that should be activated)
225     - dict of instances with missing logical volumes (values: (node, vol)
226       pairs with details about the missing volumes)
227
228   In normal operation, all lists should be empty. A non-empty instance
229   list (3rd element of the result) is still ok (errors were fixed) but
230   non-empty node list means some node is down, and probably there are
231   unfixable drbd errors.
232
233   Note that only instances that are drbd-based are taken into
234   consideration. This might need to be revisited in the future.
235
236   """
237   OP_ID = "OP_CLUSTER_VERIFY_DISKS"
238   __slots__ = []
239
240
241 class OpRepairDiskSizes(OpCode):
242   """Verify the disk sizes of the instances and fixes configuration
243   mimatches.
244
245   Parameters: optional instances list, in case we want to restrict the
246   checks to only a subset of the instances.
247
248   Result: a list of tuples, (instance, disk, new-size) for changed
249   configurations.
250
251   In normal operation, the list should be empty.
252
253   @type instances: list
254   @ivar instances: the list of instances to check, or empty for all instances
255
256   """
257   OP_ID = "OP_CLUSTER_REPAIR_DISK_SIZES"
258   __slots__ = ["instances"]
259
260
261 class OpQueryConfigValues(OpCode):
262   """Query cluster configuration values."""
263   OP_ID = "OP_CLUSTER_CONFIG_QUERY"
264   __slots__ = ["output_fields"]
265
266
267 class OpRenameCluster(OpCode):
268   """Rename the cluster.
269
270   @type name: C{str}
271   @ivar name: The new name of the cluster. The name and/or the master IP
272               address will be changed to match the new name and its IP
273               address.
274
275   """
276   OP_ID = "OP_CLUSTER_RENAME"
277   OP_DSC_FIELD = "name"
278   __slots__ = ["name"]
279
280
281 class OpSetClusterParams(OpCode):
282   """Change the parameters of the cluster.
283
284   @type vg_name: C{str} or C{None}
285   @ivar vg_name: The new volume group name or None to disable LVM usage.
286
287   """
288   OP_ID = "OP_CLUSTER_SET_PARAMS"
289   __slots__ = [
290     "vg_name",
291     "enabled_hypervisors",
292     "hvparams",
293     "beparams",
294     "nicparams",
295     "candidate_pool_size",
296     ]
297
298
299 class OpRedistributeConfig(OpCode):
300   """Force a full push of the cluster configuration.
301
302   """
303   OP_ID = "OP_CLUSTER_REDIST_CONF"
304   __slots__ = []
305
306 # node opcodes
307
308 class OpRemoveNode(OpCode):
309   """Remove a node.
310
311   @type node_name: C{str}
312   @ivar node_name: The name of the node to remove. If the node still has
313                    instances on it, the operation will fail.
314
315   """
316   OP_ID = "OP_NODE_REMOVE"
317   OP_DSC_FIELD = "node_name"
318   __slots__ = ["node_name"]
319
320
321 class OpAddNode(OpCode):
322   """Add a node to the cluster.
323
324   @type node_name: C{str}
325   @ivar node_name: The name of the node to add. This can be a short name,
326                    but it will be expanded to the FQDN.
327   @type primary_ip: IP address
328   @ivar primary_ip: The primary IP of the node. This will be ignored when the
329                     opcode is submitted, but will be filled during the node
330                     add (so it will be visible in the job query).
331   @type secondary_ip: IP address
332   @ivar secondary_ip: The secondary IP of the node. This needs to be passed
333                       if the cluster has been initialized in 'dual-network'
334                       mode, otherwise it must not be given.
335   @type readd: C{bool}
336   @ivar readd: Whether to re-add an existing node to the cluster. If
337                this is not passed, then the operation will abort if the node
338                name is already in the cluster; use this parameter to 'repair'
339                a node that had its configuration broken, or was reinstalled
340                without removal from the cluster.
341
342   """
343   OP_ID = "OP_NODE_ADD"
344   OP_DSC_FIELD = "node_name"
345   __slots__ = ["node_name", "primary_ip", "secondary_ip", "readd"]
346
347
348 class OpQueryNodes(OpCode):
349   """Compute the list of nodes."""
350   OP_ID = "OP_NODE_QUERY"
351   __slots__ = ["output_fields", "names", "use_locking"]
352
353
354 class OpQueryNodeVolumes(OpCode):
355   """Get list of volumes on node."""
356   OP_ID = "OP_NODE_QUERYVOLS"
357   __slots__ = ["nodes", "output_fields"]
358
359
360 class OpQueryNodeStorage(OpCode):
361   """Get information on storage for node(s)."""
362   OP_ID = "OP_NODE_QUERY_STORAGE"
363   __slots__ = [
364     "nodes",
365     "storage_type",
366     "name",
367     "output_fields",
368     ]
369
370
371 class OpModifyNodeStorage(OpCode):
372   """Modifies the properies of a storage unit"""
373   OP_ID = "OP_NODE_MODIFY_STORAGE"
374   __slots__ = [
375     "node_name",
376     "storage_type",
377     "name",
378     "changes",
379     ]
380
381
382 class OpRepairNodeStorage(OpCode):
383   """Repairs the volume group on a node."""
384   OP_ID = "OP_REPAIR_NODE_STORAGE"
385   OP_DSC_FIELD = "node_name"
386   __slots__ = [
387     "node_name",
388     "storage_type",
389     "name",
390     "ignore_consistency",
391     ]
392
393
394 class OpSetNodeParams(OpCode):
395   """Change the parameters of a node."""
396   OP_ID = "OP_NODE_SET_PARAMS"
397   OP_DSC_FIELD = "node_name"
398   __slots__ = [
399     "node_name",
400     "force",
401     "master_candidate",
402     "offline",
403     "drained",
404     ]
405
406
407 class OpPowercycleNode(OpCode):
408   """Tries to powercycle a node."""
409   OP_ID = "OP_NODE_POWERCYCLE"
410   OP_DSC_FIELD = "node_name"
411   __slots__ = [
412     "node_name",
413     "force",
414     ]
415
416
417 class OpEvacuateNode(OpCode):
418   """Relocate secondary instances from a node."""
419   OP_ID = "OP_NODE_EVACUATE"
420   OP_DSC_FIELD = "node_name"
421   __slots__ = [
422     "node_name", "remote_node", "iallocator", "early_release",
423     ]
424
425
426 class OpMigrateNode(OpCode):
427   """Migrate all instances from a node."""
428   OP_ID = "OP_NODE_MIGRATE"
429   OP_DSC_FIELD = "node_name"
430   __slots__ = [
431     "node_name",
432     "live",
433     ]
434
435
436 # instance opcodes
437
438 class OpCreateInstance(OpCode):
439   """Create an instance."""
440   OP_ID = "OP_INSTANCE_CREATE"
441   OP_DSC_FIELD = "instance_name"
442   __slots__ = [
443     "instance_name", "os_type", "force_variant",
444     "pnode", "disk_template", "snode", "mode",
445     "disks", "nics",
446     "src_node", "src_path", "start",
447     "wait_for_sync", "ip_check", "name_check",
448     "file_storage_dir", "file_driver",
449     "iallocator",
450     "hypervisor", "hvparams", "beparams",
451     "dry_run",
452     ]
453
454
455 class OpReinstallInstance(OpCode):
456   """Reinstall an instance's OS."""
457   OP_ID = "OP_INSTANCE_REINSTALL"
458   OP_DSC_FIELD = "instance_name"
459   __slots__ = ["instance_name", "os_type", "force_variant"]
460
461
462 class OpRemoveInstance(OpCode):
463   """Remove an instance."""
464   OP_ID = "OP_INSTANCE_REMOVE"
465   OP_DSC_FIELD = "instance_name"
466   __slots__ = [
467     "instance_name",
468     "ignore_failures",
469     "shutdown_timeout",
470     ]
471
472
473 class OpRenameInstance(OpCode):
474   """Rename an instance."""
475   OP_ID = "OP_INSTANCE_RENAME"
476   __slots__ = [
477     "instance_name", "ignore_ip", "new_name",
478     ]
479
480
481 class OpStartupInstance(OpCode):
482   """Startup an instance."""
483   OP_ID = "OP_INSTANCE_STARTUP"
484   OP_DSC_FIELD = "instance_name"
485   __slots__ = [
486     "instance_name", "force", "hvparams", "beparams",
487     ]
488
489
490 class OpShutdownInstance(OpCode):
491   """Shutdown an instance."""
492   OP_ID = "OP_INSTANCE_SHUTDOWN"
493   OP_DSC_FIELD = "instance_name"
494   __slots__ = ["instance_name", "timeout"]
495
496
497 class OpRebootInstance(OpCode):
498   """Reboot an instance."""
499   OP_ID = "OP_INSTANCE_REBOOT"
500   OP_DSC_FIELD = "instance_name"
501   __slots__ = [
502     "instance_name", "reboot_type", "ignore_secondaries", "shutdown_timeout",
503     ]
504
505
506 class OpReplaceDisks(OpCode):
507   """Replace the disks of an instance."""
508   OP_ID = "OP_INSTANCE_REPLACE_DISKS"
509   OP_DSC_FIELD = "instance_name"
510   __slots__ = [
511     "instance_name", "remote_node", "mode", "disks", "iallocator",
512     "early_release",
513     ]
514
515
516 class OpFailoverInstance(OpCode):
517   """Failover an instance."""
518   OP_ID = "OP_INSTANCE_FAILOVER"
519   OP_DSC_FIELD = "instance_name"
520   __slots__ = [
521     "instance_name", "ignore_consistency", "shutdown_timeout",
522     ]
523
524
525 class OpMigrateInstance(OpCode):
526   """Migrate an instance.
527
528   This migrates (without shutting down an instance) to its secondary
529   node.
530
531   @ivar instance_name: the name of the instance
532
533   """
534   OP_ID = "OP_INSTANCE_MIGRATE"
535   OP_DSC_FIELD = "instance_name"
536   __slots__ = ["instance_name", "live", "cleanup"]
537
538
539 class OpMoveInstance(OpCode):
540   """Move an instance.
541
542   This move (with shutting down an instance and data copying) to an
543   arbitrary node.
544
545   @ivar instance_name: the name of the instance
546   @ivar target_node: the destination node
547
548   """
549   OP_ID = "OP_INSTANCE_MOVE"
550   OP_DSC_FIELD = "instance_name"
551   __slots__ = [
552     "instance_name", "target_node", "shutdown_timeout",
553     ]
554
555
556 class OpConnectConsole(OpCode):
557   """Connect to an instance's console."""
558   OP_ID = "OP_INSTANCE_CONSOLE"
559   OP_DSC_FIELD = "instance_name"
560   __slots__ = ["instance_name"]
561
562
563 class OpActivateInstanceDisks(OpCode):
564   """Activate an instance's disks."""
565   OP_ID = "OP_INSTANCE_ACTIVATE_DISKS"
566   OP_DSC_FIELD = "instance_name"
567   __slots__ = ["instance_name", "ignore_size"]
568
569
570 class OpDeactivateInstanceDisks(OpCode):
571   """Deactivate an instance's disks."""
572   OP_ID = "OP_INSTANCE_DEACTIVATE_DISKS"
573   OP_DSC_FIELD = "instance_name"
574   __slots__ = ["instance_name"]
575
576
577 class OpRecreateInstanceDisks(OpCode):
578   """Deactivate an instance's disks."""
579   OP_ID = "OP_INSTANCE_RECREATE_DISKS"
580   OP_DSC_FIELD = "instance_name"
581   __slots__ = ["instance_name", "disks"]
582
583
584 class OpQueryInstances(OpCode):
585   """Compute the list of instances."""
586   OP_ID = "OP_INSTANCE_QUERY"
587   __slots__ = ["output_fields", "names", "use_locking"]
588
589
590 class OpQueryInstanceData(OpCode):
591   """Compute the run-time status of instances."""
592   OP_ID = "OP_INSTANCE_QUERY_DATA"
593   __slots__ = ["instances", "static"]
594
595
596 class OpSetInstanceParams(OpCode):
597   """Change the parameters of an instance."""
598   OP_ID = "OP_INSTANCE_SET_PARAMS"
599   OP_DSC_FIELD = "instance_name"
600   __slots__ = [
601     "instance_name",
602     "hvparams", "beparams", "force",
603     "nics", "disks",
604     ]
605
606
607 class OpGrowDisk(OpCode):
608   """Grow a disk of an instance."""
609   OP_ID = "OP_INSTANCE_GROW_DISK"
610   OP_DSC_FIELD = "instance_name"
611   __slots__ = [
612     "instance_name", "disk", "amount", "wait_for_sync",
613     ]
614
615
616 # OS opcodes
617 class OpDiagnoseOS(OpCode):
618   """Compute the list of guest operating systems."""
619   OP_ID = "OP_OS_DIAGNOSE"
620   __slots__ = ["output_fields", "names"]
621
622
623 # Exports opcodes
624 class OpQueryExports(OpCode):
625   """Compute the list of exported images."""
626   OP_ID = "OP_BACKUP_QUERY"
627   __slots__ = ["nodes", "use_locking"]
628
629
630 class OpExportInstance(OpCode):
631   """Export an instance."""
632   OP_ID = "OP_BACKUP_EXPORT"
633   OP_DSC_FIELD = "instance_name"
634   __slots__ = [
635     "instance_name", "target_node", "shutdown", "shutdown_timeout",
636     ]
637
638
639 class OpRemoveExport(OpCode):
640   """Remove an instance's export."""
641   OP_ID = "OP_BACKUP_REMOVE"
642   OP_DSC_FIELD = "instance_name"
643   __slots__ = ["instance_name"]
644
645
646 # Tags opcodes
647 class OpGetTags(OpCode):
648   """Returns the tags of the given object."""
649   OP_ID = "OP_TAGS_GET"
650   OP_DSC_FIELD = "name"
651   __slots__ = ["kind", "name"]
652
653
654 class OpSearchTags(OpCode):
655   """Searches the tags in the cluster for a given pattern."""
656   OP_ID = "OP_TAGS_SEARCH"
657   OP_DSC_FIELD = "pattern"
658   __slots__ = ["pattern"]
659
660
661 class OpAddTags(OpCode):
662   """Add a list of tags on a given object."""
663   OP_ID = "OP_TAGS_SET"
664   __slots__ = ["kind", "name", "tags"]
665
666
667 class OpDelTags(OpCode):
668   """Remove a list of tags from a given object."""
669   OP_ID = "OP_TAGS_DEL"
670   __slots__ = ["kind", "name", "tags"]
671
672
673 # Test opcodes
674 class OpTestDelay(OpCode):
675   """Sleeps for a configured amount of time.
676
677   This is used just for debugging and testing.
678
679   Parameters:
680     - duration: the time to sleep
681     - on_master: if true, sleep on the master
682     - on_nodes: list of nodes in which to sleep
683
684   If the on_master parameter is true, it will execute a sleep on the
685   master (before any node sleep).
686
687   If the on_nodes list is not empty, it will sleep on those nodes
688   (after the sleep on the master, if that is enabled).
689
690   As an additional feature, the case of duration < 0 will be reported
691   as an execution error, so this opcode can be used as a failure
692   generator. The case of duration == 0 will not be treated specially.
693
694   """
695   OP_ID = "OP_TEST_DELAY"
696   OP_DSC_FIELD = "duration"
697   __slots__ = ["duration", "on_master", "on_nodes"]
698
699
700 class OpTestAllocator(OpCode):
701   """Allocator framework testing.
702
703   This opcode has two modes:
704     - gather and return allocator input for a given mode (allocate new
705       or replace secondary) and a given instance definition (direction
706       'in')
707     - run a selected allocator for a given operation (as above) and
708       return the allocator output (direction 'out')
709
710   """
711   OP_ID = "OP_TEST_ALLOCATOR"
712   OP_DSC_FIELD = "allocator"
713   __slots__ = [
714     "direction", "mode", "allocator", "name",
715     "mem_size", "disks", "disk_template",
716     "os", "tags", "nics", "vcpus", "hypervisor",
717     ]
718
719
720 OP_MAPPING = dict([(v.OP_ID, v) for v in globals().values()
721                    if (isinstance(v, type) and issubclass(v, OpCode) and
722                        hasattr(v, "OP_ID"))])