objects: add configuration upgrade system
[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                childre of this class.
107
108   """
109   OP_ID = "OP_ABSTRACT"
110   __slots__ = []
111
112   def __getstate__(self):
113     """Specialized getstate for opcodes.
114
115     This method adds to the state dictionary the OP_ID of the class,
116     so that on unload we can identify the correct class for
117     instantiating the opcode.
118
119     @rtype:   C{dict}
120     @return:  the state as a dictionary
121
122     """
123     data = BaseOpCode.__getstate__(self)
124     data["OP_ID"] = self.OP_ID
125     return data
126
127   @classmethod
128   def LoadOpCode(cls, data):
129     """Generic load opcode method.
130
131     The method identifies the correct opcode class from the dict-form
132     by looking for a OP_ID key, if this is not found, or its value is
133     not available in this module as a child of this class, we fail.
134
135     @type data:  C{dict}
136     @param data: the serialized opcode
137
138     """
139     if not isinstance(data, dict):
140       raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
141     if "OP_ID" not in data:
142       raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
143     op_id = data["OP_ID"]
144     op_class = None
145     if op_id in OP_MAPPING:
146       op_class = OP_MAPPING[op_id]
147     else:
148       raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
149                        op_id)
150     op = op_class()
151     new_data = data.copy()
152     del new_data["OP_ID"]
153     op.__setstate__(new_data)
154     return op
155
156   def Summary(self):
157     """Generates a summary description of this opcode.
158
159     """
160     # all OP_ID start with OP_, we remove that
161     txt = self.OP_ID[3:]
162     field_name = getattr(self, "OP_DSC_FIELD", None)
163     if field_name:
164       field_value = getattr(self, field_name, None)
165       txt = "%s(%s)" % (txt, field_value)
166     return txt
167
168
169 # cluster opcodes
170
171 class OpDestroyCluster(OpCode):
172   """Destroy the cluster.
173
174   This opcode has no other parameters. All the state is irreversibly
175   lost after the execution of this opcode.
176
177   """
178   OP_ID = "OP_CLUSTER_DESTROY"
179   __slots__ = []
180
181
182 class OpQueryClusterInfo(OpCode):
183   """Query cluster information."""
184   OP_ID = "OP_CLUSTER_QUERY"
185   __slots__ = []
186
187
188 class OpVerifyCluster(OpCode):
189   """Verify the cluster state.
190
191   @type skip_checks: C{list}
192   @ivar skip_checks: steps to be skipped from the verify process; this
193                      needs to be a subset of
194                      L{constants.VERIFY_OPTIONAL_CHECKS}; currently
195                      only L{constants.VERIFY_NPLUSONE_MEM} can be passed
196
197   """
198   OP_ID = "OP_CLUSTER_VERIFY"
199   __slots__ = ["skip_checks"]
200
201
202 class OpVerifyDisks(OpCode):
203   """Verify the cluster disks.
204
205   Parameters: none
206
207   Result: a tuple of four elements:
208     - list of node names with bad data returned (unreachable, etc.)
209     - dict of node names with broken volume groups (values: error msg)
210     - list of instances with degraded disks (that should be activated)
211     - dict of instances with missing logical volumes (values: (node, vol)
212       pairs with details about the missing volumes)
213
214   In normal operation, all lists should be empty. A non-empty instance
215   list (3rd element of the result) is still ok (errors were fixed) but
216   non-empty node list means some node is down, and probably there are
217   unfixable drbd errors.
218
219   Note that only instances that are drbd-based are taken into
220   consideration. This might need to be revisited in the future.
221
222   """
223   OP_ID = "OP_CLUSTER_VERIFY_DISKS"
224   __slots__ = []
225
226
227 class OpRepairDiskSizes(OpCode):
228   """Verify the disk sizes of the instances and fixes configuration
229   mimatches.
230
231   Parameters: optional instances list, in case we want to restrict the
232   checks to only a subset of the instances.
233
234   Result: a list of tuples, (instance, disk, new-size) for changed
235   configurations.
236
237   In normal operation, the list should be empty.
238
239   @type instances: list
240   @ivar instances: the list of instances to check, or empty for all instances
241
242   """
243   OP_ID = "OP_CLUSTER_REPAIR_DISK_SIZES"
244   __slots__ = ["instances"]
245
246
247 class OpQueryConfigValues(OpCode):
248   """Query cluster configuration values."""
249   OP_ID = "OP_CLUSTER_CONFIG_QUERY"
250   __slots__ = ["output_fields"]
251
252
253 class OpRenameCluster(OpCode):
254   """Rename the cluster.
255
256   @type name: C{str}
257   @ivar name: The new name of the cluster. The name and/or the master IP
258               address will be changed to match the new name and its IP
259               address.
260
261   """
262   OP_ID = "OP_CLUSTER_RENAME"
263   OP_DSC_FIELD = "name"
264   __slots__ = ["name"]
265
266
267 class OpSetClusterParams(OpCode):
268   """Change the parameters of the cluster.
269
270   @type vg_name: C{str} or C{None}
271   @ivar vg_name: The new volume group name or None to disable LVM usage.
272
273   """
274   OP_ID = "OP_CLUSTER_SET_PARAMS"
275   __slots__ = [
276     "vg_name",
277     "enabled_hypervisors",
278     "hvparams",
279     "beparams",
280     "candidate_pool_size",
281     ]
282
283
284 class OpRedistributeConfig(OpCode):
285   """Force a full push of the cluster configuration.
286
287   """
288   OP_ID = "OP_CLUSTER_REDIST_CONF"
289   __slots__ = [
290     ]
291
292 # node opcodes
293
294 class OpRemoveNode(OpCode):
295   """Remove a node.
296
297   @type node_name: C{str}
298   @ivar node_name: The name of the node to remove. If the node still has
299                    instances on it, the operation will fail.
300
301   """
302   OP_ID = "OP_NODE_REMOVE"
303   OP_DSC_FIELD = "node_name"
304   __slots__ = ["node_name"]
305
306
307 class OpAddNode(OpCode):
308   """Add a node to the cluster.
309
310   @type node_name: C{str}
311   @ivar node_name: The name of the node to add. This can be a short name,
312                    but it will be expanded to the FQDN.
313   @type primary_ip: IP address
314   @ivar primary_ip: The primary IP of the node. This will be ignored when the
315                     opcode is submitted, but will be filled during the node
316                     add (so it will be visible in the job query).
317   @type secondary_ip: IP address
318   @ivar secondary_ip: The secondary IP of the node. This needs to be passed
319                       if the cluster has been initialized in 'dual-network'
320                       mode, otherwise it must not be given.
321   @type readd: C{bool}
322   @ivar readd: Whether to re-add an existing node to the cluster. If
323                this is not passed, then the operation will abort if the node
324                name is already in the cluster; use this parameter to 'repair'
325                a node that had its configuration broken, or was reinstalled
326                without removal from the cluster.
327
328   """
329   OP_ID = "OP_NODE_ADD"
330   OP_DSC_FIELD = "node_name"
331   __slots__ = ["node_name", "primary_ip", "secondary_ip", "readd"]
332
333
334 class OpQueryNodes(OpCode):
335   """Compute the list of nodes."""
336   OP_ID = "OP_NODE_QUERY"
337   __slots__ = ["output_fields", "names", "use_locking"]
338
339
340 class OpQueryNodeVolumes(OpCode):
341   """Get list of volumes on node."""
342   OP_ID = "OP_NODE_QUERYVOLS"
343   __slots__ = ["nodes", "output_fields"]
344
345
346 class OpSetNodeParams(OpCode):
347   """Change the parameters of a node."""
348   OP_ID = "OP_NODE_SET_PARAMS"
349   OP_DSC_FIELD = "node_name"
350   __slots__ = [
351     "node_name",
352     "force",
353     "master_candidate",
354     "offline",
355     "drained",
356     ]
357
358 # instance opcodes
359
360 class OpCreateInstance(OpCode):
361   """Create an instance."""
362   OP_ID = "OP_INSTANCE_CREATE"
363   OP_DSC_FIELD = "instance_name"
364   __slots__ = [
365     "instance_name", "os_type", "pnode",
366     "disk_template", "snode", "mode",
367     "disks", "nics",
368     "src_node", "src_path", "start",
369     "wait_for_sync", "ip_check",
370     "file_storage_dir", "file_driver",
371     "iallocator",
372     "hypervisor", "hvparams", "beparams",
373     ]
374
375
376 class OpReinstallInstance(OpCode):
377   """Reinstall an instance's OS."""
378   OP_ID = "OP_INSTANCE_REINSTALL"
379   OP_DSC_FIELD = "instance_name"
380   __slots__ = ["instance_name", "os_type"]
381
382
383 class OpRemoveInstance(OpCode):
384   """Remove an instance."""
385   OP_ID = "OP_INSTANCE_REMOVE"
386   OP_DSC_FIELD = "instance_name"
387   __slots__ = ["instance_name", "ignore_failures"]
388
389
390 class OpRenameInstance(OpCode):
391   """Rename an instance."""
392   OP_ID = "OP_INSTANCE_RENAME"
393   __slots__ = ["instance_name", "ignore_ip", "new_name"]
394
395
396 class OpStartupInstance(OpCode):
397   """Startup an instance."""
398   OP_ID = "OP_INSTANCE_STARTUP"
399   OP_DSC_FIELD = "instance_name"
400   __slots__ = ["instance_name", "force", "hvparams", "beparams"]
401
402
403 class OpShutdownInstance(OpCode):
404   """Shutdown an instance."""
405   OP_ID = "OP_INSTANCE_SHUTDOWN"
406   OP_DSC_FIELD = "instance_name"
407   __slots__ = ["instance_name"]
408
409
410 class OpRebootInstance(OpCode):
411   """Reboot an instance."""
412   OP_ID = "OP_INSTANCE_REBOOT"
413   OP_DSC_FIELD = "instance_name"
414   __slots__ = ["instance_name", "reboot_type", "ignore_secondaries" ]
415
416
417 class OpReplaceDisks(OpCode):
418   """Replace the disks of an instance."""
419   OP_ID = "OP_INSTANCE_REPLACE_DISKS"
420   OP_DSC_FIELD = "instance_name"
421   __slots__ = ["instance_name", "remote_node", "mode", "disks", "iallocator"]
422
423
424 class OpFailoverInstance(OpCode):
425   """Failover an instance."""
426   OP_ID = "OP_INSTANCE_FAILOVER"
427   OP_DSC_FIELD = "instance_name"
428   __slots__ = ["instance_name", "ignore_consistency"]
429
430
431 class OpMigrateInstance(OpCode):
432   """Migrate an instance.
433
434   This migrates (without shutting down an instance) to its secondary
435   node.
436
437   @ivar instance_name: the name of the instance
438
439   """
440   OP_ID = "OP_INSTANCE_MIGRATE"
441   OP_DSC_FIELD = "instance_name"
442   __slots__ = ["instance_name", "live", "cleanup"]
443
444
445 class OpConnectConsole(OpCode):
446   """Connect to an instance's console."""
447   OP_ID = "OP_INSTANCE_CONSOLE"
448   OP_DSC_FIELD = "instance_name"
449   __slots__ = ["instance_name"]
450
451
452 class OpActivateInstanceDisks(OpCode):
453   """Activate an instance's disks."""
454   OP_ID = "OP_INSTANCE_ACTIVATE_DISKS"
455   OP_DSC_FIELD = "instance_name"
456   __slots__ = ["instance_name", "ignore_size"]
457
458
459 class OpDeactivateInstanceDisks(OpCode):
460   """Deactivate an instance's disks."""
461   OP_ID = "OP_INSTANCE_DEACTIVATE_DISKS"
462   OP_DSC_FIELD = "instance_name"
463   __slots__ = ["instance_name"]
464
465
466 class OpQueryInstances(OpCode):
467   """Compute the list of instances."""
468   OP_ID = "OP_INSTANCE_QUERY"
469   __slots__ = ["output_fields", "names", "use_locking"]
470
471
472 class OpQueryInstanceData(OpCode):
473   """Compute the run-time status of instances."""
474   OP_ID = "OP_INSTANCE_QUERY_DATA"
475   __slots__ = ["instances", "static"]
476
477
478 class OpSetInstanceParams(OpCode):
479   """Change the parameters of an instance."""
480   OP_ID = "OP_INSTANCE_SET_PARAMS"
481   OP_DSC_FIELD = "instance_name"
482   __slots__ = [
483     "instance_name",
484     "hvparams", "beparams", "force",
485     "nics", "disks",
486     ]
487
488
489 class OpGrowDisk(OpCode):
490   """Grow a disk of an instance."""
491   OP_ID = "OP_INSTANCE_GROW_DISK"
492   OP_DSC_FIELD = "instance_name"
493   __slots__ = ["instance_name", "disk", "amount", "wait_for_sync"]
494
495
496 # OS opcodes
497 class OpDiagnoseOS(OpCode):
498   """Compute the list of guest operating systems."""
499   OP_ID = "OP_OS_DIAGNOSE"
500   __slots__ = ["output_fields", "names"]
501
502
503 # Exports opcodes
504 class OpQueryExports(OpCode):
505   """Compute the list of exported images."""
506   OP_ID = "OP_BACKUP_QUERY"
507   __slots__ = ["nodes", "use_locking"]
508
509
510 class OpExportInstance(OpCode):
511   """Export an instance."""
512   OP_ID = "OP_BACKUP_EXPORT"
513   OP_DSC_FIELD = "instance_name"
514   __slots__ = ["instance_name", "target_node", "shutdown"]
515
516
517 class OpRemoveExport(OpCode):
518   """Remove an instance's export."""
519   OP_ID = "OP_BACKUP_REMOVE"
520   OP_DSC_FIELD = "instance_name"
521   __slots__ = ["instance_name"]
522
523
524 # Tags opcodes
525 class OpGetTags(OpCode):
526   """Returns the tags of the given object."""
527   OP_ID = "OP_TAGS_GET"
528   OP_DSC_FIELD = "name"
529   __slots__ = ["kind", "name"]
530
531
532 class OpSearchTags(OpCode):
533   """Searches the tags in the cluster for a given pattern."""
534   OP_ID = "OP_TAGS_SEARCH"
535   OP_DSC_FIELD = "pattern"
536   __slots__ = ["pattern"]
537
538
539 class OpAddTags(OpCode):
540   """Add a list of tags on a given object."""
541   OP_ID = "OP_TAGS_SET"
542   __slots__ = ["kind", "name", "tags"]
543
544
545 class OpDelTags(OpCode):
546   """Remove a list of tags from a given object."""
547   OP_ID = "OP_TAGS_DEL"
548   __slots__ = ["kind", "name", "tags"]
549
550
551 # Test opcodes
552 class OpTestDelay(OpCode):
553   """Sleeps for a configured amount of time.
554
555   This is used just for debugging and testing.
556
557   Parameters:
558     - duration: the time to sleep
559     - on_master: if true, sleep on the master
560     - on_nodes: list of nodes in which to sleep
561
562   If the on_master parameter is true, it will execute a sleep on the
563   master (before any node sleep).
564
565   If the on_nodes list is not empty, it will sleep on those nodes
566   (after the sleep on the master, if that is enabled).
567
568   As an additional feature, the case of duration < 0 will be reported
569   as an execution error, so this opcode can be used as a failure
570   generator. The case of duration == 0 will not be treated specially.
571
572   """
573   OP_ID = "OP_TEST_DELAY"
574   OP_DSC_FIELD = "duration"
575   __slots__ = ["duration", "on_master", "on_nodes"]
576
577
578 class OpTestAllocator(OpCode):
579   """Allocator framework testing.
580
581   This opcode has two modes:
582     - gather and return allocator input for a given mode (allocate new
583       or replace secondary) and a given instance definition (direction
584       'in')
585     - run a selected allocator for a given operation (as above) and
586       return the allocator output (direction 'out')
587
588   """
589   OP_ID = "OP_TEST_ALLOCATOR"
590   OP_DSC_FIELD = "allocator"
591   __slots__ = [
592     "direction", "mode", "allocator", "name",
593     "mem_size", "disks", "disk_template",
594     "os", "tags", "nics", "vcpus", "hypervisor",
595     ]
596
597 OP_MAPPING = dict([(v.OP_ID, v) for v in globals().values()
598                    if (isinstance(v, type) and issubclass(v, OpCode) and
599                        hasattr(v, "OP_ID"))])