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