Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 197b323b

History | View | Annotate | Download (37 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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
import logging
37
import re
38
import operator
39

    
40
from ganeti import constants
41
from ganeti import errors
42
from ganeti import ht
43

    
44

    
45
# Common opcode attributes
46

    
47
#: output fields for a query operation
48
_POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
49
                  None)
50

    
51
#: the shutdown timeout
52
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
53
                     ht.TPositiveInt, None)
54

    
55
#: the force parameter
56
_PForce = ("force", False, ht.TBool, None)
57

    
58
#: a required instance name (for single-instance LUs)
59
_PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString, None)
60

    
61
#: Whether to ignore offline nodes
62
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool, None)
63

    
64
#: a required node name (for single-node LUs)
65
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, None)
66

    
67
#: a required node group name (for single-group LUs)
68
_PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, None)
69

    
70
#: Migration type (live/non-live)
71
_PMigrationMode = ("mode", None,
72
                   ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)),
73
                   None)
74

    
75
#: Obsolete 'live' migration mode (boolean)
76
_PMigrationLive = ("live", None, ht.TMaybeBool, None)
77

    
78
#: Tag type
79
_PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
80

    
81
#: List of tag strings
82
_PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
83

    
84
#: OP_ID conversion regular expression
85
_OPID_RE = re.compile("([a-z])([A-Z])")
86

    
87
#: Utility function for L{OpClusterSetParams}
88
_TestClusterOsList = ht.TOr(ht.TNone,
89
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
90
    ht.TMap(ht.WithDesc("GetFirstItem")(operator.itemgetter(0)),
91
            ht.TElemOf(constants.DDMS_VALUES)))))
92

    
93

    
94
def _NameToId(name):
95
  """Convert an opcode class name to an OP_ID.
96

97
  @type name: string
98
  @param name: the class name, as OpXxxYyy
99
  @rtype: string
100
  @return: the name in the OP_XXXX_YYYY format
101

102
  """
103
  if not name.startswith("Op"):
104
    return None
105
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
106
  # consume any input, and hence we would just have all the elements
107
  # in the list, one by one; but it seems that split doesn't work on
108
  # non-consuming input, hence we have to process the input string a
109
  # bit
110
  name = _OPID_RE.sub(r"\1,\2", name)
111
  elems = name.split(",")
112
  return "_".join(n.upper() for n in elems)
113

    
114

    
115
def RequireFileStorage():
116
  """Checks that file storage is enabled.
117

118
  While it doesn't really fit into this module, L{utils} was deemed too large
119
  of a dependency to be imported for just one or two functions.
120

121
  @raise errors.OpPrereqError: when file storage is disabled
122

123
  """
124
  if not constants.ENABLE_FILE_STORAGE:
125
    raise errors.OpPrereqError("File storage disabled at configure time",
126
                               errors.ECODE_INVAL)
127

    
128

    
129
@ht.WithDesc("CheckFileStorage")
130
def _CheckFileStorage(value):
131
  """Ensures file storage is enabled if used.
132

133
  """
134
  if value == constants.DT_FILE:
135
    RequireFileStorage()
136
  return True
137

    
138

    
139
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
140
                             _CheckFileStorage)
141

    
142

    
143
def _CheckStorageType(storage_type):
144
  """Ensure a given storage type is valid.
145

146
  """
147
  if storage_type not in constants.VALID_STORAGE_TYPES:
148
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
149
                               errors.ECODE_INVAL)
150
  if storage_type == constants.ST_FILE:
151
    RequireFileStorage()
152
  return True
153

    
154

    
155
#: Storage type parameter
156
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType, None)
157

    
158

    
159
class _AutoOpParamSlots(type):
160
  """Meta class for opcode definitions.
161

162
  """
163
  def __new__(mcs, name, bases, attrs):
164
    """Called when a class should be created.
165

166
    @param mcs: The meta class
167
    @param name: Name of created class
168
    @param bases: Base classes
169
    @type attrs: dict
170
    @param attrs: Class attributes
171

172
    """
173
    assert "__slots__" not in attrs, \
174
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
175
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
176

    
177
    attrs["OP_ID"] = _NameToId(name)
178

    
179
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
180
    params = attrs.setdefault("OP_PARAMS", [])
181

    
182
    # Use parameter names as slots
183
    slots = [pname for (pname, _, _, _) in params]
184

    
185
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
186
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
187

    
188
    attrs["__slots__"] = slots
189

    
190
    return type.__new__(mcs, name, bases, attrs)
191

    
192

    
193
class BaseOpCode(object):
194
  """A simple serializable object.
195

196
  This object serves as a parent class for OpCode without any custom
197
  field handling.
198

199
  """
200
  # pylint: disable-msg=E1101
201
  # as OP_ID is dynamically defined
202
  __metaclass__ = _AutoOpParamSlots
203

    
204
  def __init__(self, **kwargs):
205
    """Constructor for BaseOpCode.
206

207
    The constructor takes only keyword arguments and will set
208
    attributes on this object based on the passed arguments. As such,
209
    it means that you should not pass arguments which are not in the
210
    __slots__ attribute for this class.
211

212
    """
213
    slots = self._all_slots()
214
    for key in kwargs:
215
      if key not in slots:
216
        raise TypeError("Object %s doesn't support the parameter '%s'" %
217
                        (self.__class__.__name__, key))
218
      setattr(self, key, kwargs[key])
219

    
220
  def __getstate__(self):
221
    """Generic serializer.
222

223
    This method just returns the contents of the instance as a
224
    dictionary.
225

226
    @rtype:  C{dict}
227
    @return: the instance attributes and their values
228

229
    """
230
    state = {}
231
    for name in self._all_slots():
232
      if hasattr(self, name):
233
        state[name] = getattr(self, name)
234
    return state
235

    
236
  def __setstate__(self, state):
237
    """Generic unserializer.
238

239
    This method just restores from the serialized state the attributes
240
    of the current instance.
241

242
    @param state: the serialized opcode data
243
    @type state:  C{dict}
244

245
    """
246
    if not isinstance(state, dict):
247
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
248
                       type(state))
249

    
250
    for name in self._all_slots():
251
      if name not in state and hasattr(self, name):
252
        delattr(self, name)
253

    
254
    for name in state:
255
      setattr(self, name, state[name])
256

    
257
  @classmethod
258
  def _all_slots(cls):
259
    """Compute the list of all declared slots for a class.
260

261
    """
262
    slots = []
263
    for parent in cls.__mro__:
264
      slots.extend(getattr(parent, "__slots__", []))
265
    return slots
266

    
267
  @classmethod
268
  def GetAllParams(cls):
269
    """Compute list of all parameters for an opcode.
270

271
    """
272
    slots = []
273
    for parent in cls.__mro__:
274
      slots.extend(getattr(parent, "OP_PARAMS", []))
275
    return slots
276

    
277
  def Validate(self, set_defaults):
278
    """Validate opcode parameters, optionally setting default values.
279

280
    @type set_defaults: bool
281
    @param set_defaults: Whether to set default values
282
    @raise errors.OpPrereqError: When a parameter value doesn't match
283
                                 requirements
284

285
    """
286
    for (attr_name, default, test, _) in self.GetAllParams():
287
      assert test == ht.NoType or callable(test)
288

    
289
      if not hasattr(self, attr_name):
290
        if default == ht.NoDefault:
291
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
292
                                     (self.OP_ID, attr_name),
293
                                     errors.ECODE_INVAL)
294
        elif set_defaults:
295
          if callable(default):
296
            dval = default()
297
          else:
298
            dval = default
299
          setattr(self, attr_name, dval)
300

    
301
      if test == ht.NoType:
302
        # no tests here
303
        continue
304

    
305
      if set_defaults or hasattr(self, attr_name):
306
        attr_val = getattr(self, attr_name)
307
        if not test(attr_val):
308
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
309
                        self.OP_ID, attr_name, type(attr_val), attr_val)
310
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
311
                                     (self.OP_ID, attr_name),
312
                                     errors.ECODE_INVAL)
313

    
314

    
315
class OpCode(BaseOpCode):
316
  """Abstract OpCode.
317

318
  This is the root of the actual OpCode hierarchy. All clases derived
319
  from this class should override OP_ID.
320

321
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
322
               children of this class.
323
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
324
                      string returned by Summary(); see the docstring of that
325
                      method for details).
326
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
327
                   get if not already defined, and types they must match.
328
  @cvar WITH_LU: Boolean that specifies whether this should be included in
329
      mcpu's dispatch table
330
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
331
                 the check steps
332
  @ivar priority: Opcode priority for queue
333

334
  """
335
  # pylint: disable-msg=E1101
336
  # as OP_ID is dynamically defined
337
  WITH_LU = True
338
  OP_PARAMS = [
339
    ("dry_run", None, ht.TMaybeBool, None),
340
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
341
    ("priority", constants.OP_PRIO_DEFAULT,
342
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), None),
343
    ]
344

    
345
  def __getstate__(self):
346
    """Specialized getstate for opcodes.
347

348
    This method adds to the state dictionary the OP_ID of the class,
349
    so that on unload we can identify the correct class for
350
    instantiating the opcode.
351

352
    @rtype:   C{dict}
353
    @return:  the state as a dictionary
354

355
    """
356
    data = BaseOpCode.__getstate__(self)
357
    data["OP_ID"] = self.OP_ID
358
    return data
359

    
360
  @classmethod
361
  def LoadOpCode(cls, data):
362
    """Generic load opcode method.
363

364
    The method identifies the correct opcode class from the dict-form
365
    by looking for a OP_ID key, if this is not found, or its value is
366
    not available in this module as a child of this class, we fail.
367

368
    @type data:  C{dict}
369
    @param data: the serialized opcode
370

371
    """
372
    if not isinstance(data, dict):
373
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
374
    if "OP_ID" not in data:
375
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
376
    op_id = data["OP_ID"]
377
    op_class = None
378
    if op_id in OP_MAPPING:
379
      op_class = OP_MAPPING[op_id]
380
    else:
381
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
382
                       op_id)
383
    op = op_class()
384
    new_data = data.copy()
385
    del new_data["OP_ID"]
386
    op.__setstate__(new_data)
387
    return op
388

    
389
  def Summary(self):
390
    """Generates a summary description of this opcode.
391

392
    The summary is the value of the OP_ID attribute (without the "OP_"
393
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
394
    defined; this field should allow to easily identify the operation
395
    (for an instance creation job, e.g., it would be the instance
396
    name).
397

398
    """
399
    assert self.OP_ID is not None and len(self.OP_ID) > 3
400
    # all OP_ID start with OP_, we remove that
401
    txt = self.OP_ID[3:]
402
    field_name = getattr(self, "OP_DSC_FIELD", None)
403
    if field_name:
404
      field_value = getattr(self, field_name, None)
405
      if isinstance(field_value, (list, tuple)):
406
        field_value = ",".join(str(i) for i in field_value)
407
      txt = "%s(%s)" % (txt, field_value)
408
    return txt
409

    
410

    
411
# cluster opcodes
412

    
413
class OpClusterPostInit(OpCode):
414
  """Post cluster initialization.
415

416
  This opcode does not touch the cluster at all. Its purpose is to run hooks
417
  after the cluster has been initialized.
418

419
  """
420

    
421

    
422
class OpClusterDestroy(OpCode):
423
  """Destroy the cluster.
424

425
  This opcode has no other parameters. All the state is irreversibly
426
  lost after the execution of this opcode.
427

428
  """
429

    
430

    
431
class OpClusterQuery(OpCode):
432
  """Query cluster information."""
433

    
434

    
435
class OpClusterVerify(OpCode):
436
  """Verify the cluster state.
437

438
  @type skip_checks: C{list}
439
  @ivar skip_checks: steps to be skipped from the verify process; this
440
                     needs to be a subset of
441
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
442
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
443

444
  """
445
  OP_PARAMS = [
446
    ("skip_checks", ht.EmptyList,
447
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
448
    ("verbose", False, ht.TBool, None),
449
    ("error_codes", False, ht.TBool, None),
450
    ("debug_simulate_errors", False, ht.TBool, None),
451
    ]
452

    
453

    
454
class OpClusterVerifyDisks(OpCode):
455
  """Verify the cluster disks.
456

457
  Parameters: none
458

459
  Result: a tuple of four elements:
460
    - list of node names with bad data returned (unreachable, etc.)
461
    - dict of node names with broken volume groups (values: error msg)
462
    - list of instances with degraded disks (that should be activated)
463
    - dict of instances with missing logical volumes (values: (node, vol)
464
      pairs with details about the missing volumes)
465

466
  In normal operation, all lists should be empty. A non-empty instance
467
  list (3rd element of the result) is still ok (errors were fixed) but
468
  non-empty node list means some node is down, and probably there are
469
  unfixable drbd errors.
470

471
  Note that only instances that are drbd-based are taken into
472
  consideration. This might need to be revisited in the future.
473

474
  """
475

    
476

    
477
class OpClusterRepairDiskSizes(OpCode):
478
  """Verify the disk sizes of the instances and fixes configuration
479
  mimatches.
480

481
  Parameters: optional instances list, in case we want to restrict the
482
  checks to only a subset of the instances.
483

484
  Result: a list of tuples, (instance, disk, new-size) for changed
485
  configurations.
486

487
  In normal operation, the list should be empty.
488

489
  @type instances: list
490
  @ivar instances: the list of instances to check, or empty for all instances
491

492
  """
493
  OP_PARAMS = [
494
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
495
    ]
496

    
497

    
498
class OpClusterConfigQuery(OpCode):
499
  """Query cluster configuration values."""
500
  OP_PARAMS = [
501
    _POutputFields
502
    ]
503

    
504

    
505
class OpClusterRename(OpCode):
506
  """Rename the cluster.
507

508
  @type name: C{str}
509
  @ivar name: The new name of the cluster. The name and/or the master IP
510
              address will be changed to match the new name and its IP
511
              address.
512

513
  """
514
  OP_DSC_FIELD = "name"
515
  OP_PARAMS = [
516
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
517
    ]
518

    
519

    
520
class OpClusterSetParams(OpCode):
521
  """Change the parameters of the cluster.
522

523
  @type vg_name: C{str} or C{None}
524
  @ivar vg_name: The new volume group name or None to disable LVM usage.
525

526
  """
527
  OP_PARAMS = [
528
    ("vg_name", None, ht.TMaybeString, None),
529
    ("enabled_hypervisors", None,
530
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
531
            ht.TNone), None),
532
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
533
                              ht.TNone), None),
534
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone), None),
535
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
536
                            ht.TNone), None),
537
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
538
                              ht.TNone), None),
539
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
540
     None),
541
    ("uid_pool", None, ht.NoType, None),
542
    ("add_uids", None, ht.NoType, None),
543
    ("remove_uids", None, ht.NoType, None),
544
    ("maintain_node_health", None, ht.TMaybeBool, None),
545
    ("prealloc_wipe_disks", None, ht.TMaybeBool, None),
546
    ("nicparams", None, ht.TMaybeDict, None),
547
    ("ndparams", None, ht.TMaybeDict, None),
548
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), None),
549
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone), None),
550
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone), None),
551
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone), None),
552
    ("hidden_os", None, _TestClusterOsList, None),
553
    ("blacklisted_os", None, _TestClusterOsList, None),
554
    ]
555

    
556

    
557
class OpClusterRedistConf(OpCode):
558
  """Force a full push of the cluster configuration.
559

560
  """
561

    
562

    
563
class OpQuery(OpCode):
564
  """Query for resources/items.
565

566
  @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
567
  @ivar fields: List of fields to retrieve
568
  @ivar filter: Query filter
569

570
  """
571
  OP_PARAMS = [
572
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY), None),
573
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
574
    ("filter", None, ht.TOr(ht.TNone,
575
                            ht.TListOf(ht.TOr(ht.TNonEmptyString, ht.TList))), None),
576
    ]
577

    
578

    
579
class OpQueryFields(OpCode):
580
  """Query for available resource/item fields.
581

582
  @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
583
  @ivar fields: List of fields to retrieve
584

585
  """
586
  OP_PARAMS = [
587
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY), None),
588
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)), None),
589
    ]
590

    
591

    
592
class OpOobCommand(OpCode):
593
  """Interact with OOB."""
594
  OP_PARAMS = [
595
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
596
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS), None),
597
    ("timeout", constants.OOB_TIMEOUT, ht.TInt, None),
598
    ("ignore_status", False, ht.TBool, None),
599
    ("force_master", False, ht.TBool, None),
600
    ]
601

    
602

    
603
# node opcodes
604

    
605
class OpNodeRemove(OpCode):
606
  """Remove a node.
607

608
  @type node_name: C{str}
609
  @ivar node_name: The name of the node to remove. If the node still has
610
                   instances on it, the operation will fail.
611

612
  """
613
  OP_DSC_FIELD = "node_name"
614
  OP_PARAMS = [
615
    _PNodeName,
616
    ]
617

    
618

    
619
class OpNodeAdd(OpCode):
620
  """Add a node to the cluster.
621

622
  @type node_name: C{str}
623
  @ivar node_name: The name of the node to add. This can be a short name,
624
                   but it will be expanded to the FQDN.
625
  @type primary_ip: IP address
626
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
627
                    opcode is submitted, but will be filled during the node
628
                    add (so it will be visible in the job query).
629
  @type secondary_ip: IP address
630
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
631
                      if the cluster has been initialized in 'dual-network'
632
                      mode, otherwise it must not be given.
633
  @type readd: C{bool}
634
  @ivar readd: Whether to re-add an existing node to the cluster. If
635
               this is not passed, then the operation will abort if the node
636
               name is already in the cluster; use this parameter to 'repair'
637
               a node that had its configuration broken, or was reinstalled
638
               without removal from the cluster.
639
  @type group: C{str}
640
  @ivar group: The node group to which this node will belong.
641
  @type vm_capable: C{bool}
642
  @ivar vm_capable: The vm_capable node attribute
643
  @type master_capable: C{bool}
644
  @ivar master_capable: The master_capable node attribute
645

646
  """
647
  OP_DSC_FIELD = "node_name"
648
  OP_PARAMS = [
649
    _PNodeName,
650
    ("primary_ip", None, ht.NoType, None),
651
    ("secondary_ip", None, ht.TMaybeString, None),
652
    ("readd", False, ht.TBool, None),
653
    ("group", None, ht.TMaybeString, None),
654
    ("master_capable", None, ht.TMaybeBool, None),
655
    ("vm_capable", None, ht.TMaybeBool, None),
656
    ("ndparams", None, ht.TMaybeDict, None),
657
    ]
658

    
659

    
660
class OpNodeQuery(OpCode):
661
  """Compute the list of nodes."""
662
  OP_PARAMS = [
663
    _POutputFields,
664
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
665
    ("use_locking", False, ht.TBool, None),
666
    ]
667

    
668

    
669
class OpNodeQueryvols(OpCode):
670
  """Get list of volumes on node."""
671
  OP_PARAMS = [
672
    _POutputFields,
673
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
674
    ]
675

    
676

    
677
class OpNodeQueryStorage(OpCode):
678
  """Get information on storage for node(s)."""
679
  OP_PARAMS = [
680
    _POutputFields,
681
    _PStorageType,
682
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
683
    ("name", None, ht.TMaybeString, None),
684
    ]
685

    
686

    
687
class OpNodeModifyStorage(OpCode):
688
  """Modifies the properies of a storage unit"""
689
  OP_PARAMS = [
690
    _PNodeName,
691
    _PStorageType,
692
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
693
    ("changes", ht.NoDefault, ht.TDict, None),
694
    ]
695

    
696

    
697
class OpRepairNodeStorage(OpCode):
698
  """Repairs the volume group on a node."""
699
  OP_DSC_FIELD = "node_name"
700
  OP_PARAMS = [
701
    _PNodeName,
702
    _PStorageType,
703
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
704
    ("ignore_consistency", False, ht.TBool, None),
705
    ]
706

    
707

    
708
class OpNodeSetParams(OpCode):
709
  """Change the parameters of a node."""
710
  OP_DSC_FIELD = "node_name"
711
  OP_PARAMS = [
712
    _PNodeName,
713
    _PForce,
714
    ("master_candidate", None, ht.TMaybeBool, None),
715
    ("offline", None, ht.TMaybeBool, None),
716
    ("drained", None, ht.TMaybeBool, None),
717
    ("auto_promote", False, ht.TBool, None),
718
    ("master_capable", None, ht.TMaybeBool, None),
719
    ("vm_capable", None, ht.TMaybeBool, None),
720
    ("secondary_ip", None, ht.TMaybeString, None),
721
    ("ndparams", None, ht.TMaybeDict, None),
722
    ("powered", None, ht.TMaybeBool, None),
723
    ]
724

    
725

    
726
class OpNodePowercycle(OpCode):
727
  """Tries to powercycle a node."""
728
  OP_DSC_FIELD = "node_name"
729
  OP_PARAMS = [
730
    _PNodeName,
731
    _PForce,
732
    ]
733

    
734

    
735
class OpNodeMigrate(OpCode):
736
  """Migrate all instances from a node."""
737
  OP_DSC_FIELD = "node_name"
738
  OP_PARAMS = [
739
    _PNodeName,
740
    _PMigrationMode,
741
    _PMigrationLive,
742
    ]
743

    
744

    
745
class OpNodeEvacStrategy(OpCode):
746
  """Compute the evacuation strategy for a list of nodes."""
747
  OP_DSC_FIELD = "nodes"
748
  OP_PARAMS = [
749
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
750
    ("remote_node", None, ht.TMaybeString, None),
751
    ("iallocator", None, ht.TMaybeString, None),
752
    ]
753

    
754

    
755
# instance opcodes
756

    
757
class OpInstanceCreate(OpCode):
758
  """Create an instance.
759

760
  @ivar instance_name: Instance name
761
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
762
  @ivar source_handshake: Signed handshake from source (remote import only)
763
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
764
  @ivar source_instance_name: Previous name of instance (remote import only)
765
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
766
    (remote import only)
767

768
  """
769
  OP_DSC_FIELD = "instance_name"
770
  OP_PARAMS = [
771
    _PInstanceName,
772
    ("beparams", ht.EmptyDict, ht.TDict, None),
773
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict), None),
774
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, None),
775
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)), None),
776
    ("file_storage_dir", None, ht.TMaybeString, None),
777
    ("force_variant", False, ht.TBool, None),
778
    ("hvparams", ht.EmptyDict, ht.TDict, None),
779
    ("hypervisor", None, ht.TMaybeString, None),
780
    ("iallocator", None, ht.TMaybeString, None),
781
    ("identify_defaults", False, ht.TBool, None),
782
    ("ip_check", True, ht.TBool, None),
783
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES), None),
784
    ("name_check", True, ht.TBool, None),
785
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict), None),
786
    ("no_install", None, ht.TMaybeBool, None),
787
    ("osparams", ht.EmptyDict, ht.TDict, None),
788
    ("os_type", None, ht.TMaybeString, None),
789
    ("pnode", None, ht.TMaybeString, None),
790
    ("snode", None, ht.TMaybeString, None),
791
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone), None),
792
    ("source_instance_name", None, ht.TMaybeString, None),
793
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
794
     ht.TPositiveInt, None),
795
    ("source_x509_ca", None, ht.TMaybeString, None),
796
    ("src_node", None, ht.TMaybeString, None),
797
    ("src_path", None, ht.TMaybeString, None),
798
    ("start", True, ht.TBool, None),
799
    ("wait_for_sync", True, ht.TBool, None),
800
    ]
801

    
802

    
803
class OpInstanceReinstall(OpCode):
804
  """Reinstall an instance's OS."""
805
  OP_DSC_FIELD = "instance_name"
806
  OP_PARAMS = [
807
    _PInstanceName,
808
    ("os_type", None, ht.TMaybeString, None),
809
    ("force_variant", False, ht.TBool, None),
810
    ("osparams", None, ht.TMaybeDict, None),
811
    ]
812

    
813

    
814
class OpInstanceRemove(OpCode):
815
  """Remove an instance."""
816
  OP_DSC_FIELD = "instance_name"
817
  OP_PARAMS = [
818
    _PInstanceName,
819
    _PShutdownTimeout,
820
    ("ignore_failures", False, ht.TBool, None),
821
    ]
822

    
823

    
824
class OpInstanceRename(OpCode):
825
  """Rename an instance."""
826
  OP_PARAMS = [
827
    _PInstanceName,
828
    ("new_name", ht.NoDefault, ht.TNonEmptyString, None),
829
    ("ip_check", False, ht.TBool, None),
830
    ("name_check", True, ht.TBool, None),
831
    ]
832

    
833

    
834
class OpInstanceStartup(OpCode):
835
  """Startup an instance."""
836
  OP_DSC_FIELD = "instance_name"
837
  OP_PARAMS = [
838
    _PInstanceName,
839
    _PForce,
840
    _PIgnoreOfflineNodes,
841
    ("hvparams", ht.EmptyDict, ht.TDict, None),
842
    ("beparams", ht.EmptyDict, ht.TDict, None),
843
    ]
844

    
845

    
846
class OpInstanceShutdown(OpCode):
847
  """Shutdown an instance."""
848
  OP_DSC_FIELD = "instance_name"
849
  OP_PARAMS = [
850
    _PInstanceName,
851
    _PIgnoreOfflineNodes,
852
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt, None),
853
    ]
854

    
855

    
856
class OpInstanceReboot(OpCode):
857
  """Reboot an instance."""
858
  OP_DSC_FIELD = "instance_name"
859
  OP_PARAMS = [
860
    _PInstanceName,
861
    _PShutdownTimeout,
862
    ("ignore_secondaries", False, ht.TBool, None),
863
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES), None),
864
    ]
865

    
866

    
867
class OpInstanceReplaceDisks(OpCode):
868
  """Replace the disks of an instance."""
869
  OP_DSC_FIELD = "instance_name"
870
  OP_PARAMS = [
871
    _PInstanceName,
872
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES), None),
873
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt), None),
874
    ("remote_node", None, ht.TMaybeString, None),
875
    ("iallocator", None, ht.TMaybeString, None),
876
    ("early_release", False, ht.TBool, None),
877
    ]
878

    
879

    
880
class OpInstanceFailover(OpCode):
881
  """Failover an instance."""
882
  OP_DSC_FIELD = "instance_name"
883
  OP_PARAMS = [
884
    _PInstanceName,
885
    _PShutdownTimeout,
886
    ("ignore_consistency", False, ht.TBool, None),
887
    ]
888

    
889

    
890
class OpInstanceMigrate(OpCode):
891
  """Migrate an instance.
892

893
  This migrates (without shutting down an instance) to its secondary
894
  node.
895

896
  @ivar instance_name: the name of the instance
897
  @ivar mode: the migration mode (live, non-live or None for auto)
898

899
  """
900
  OP_DSC_FIELD = "instance_name"
901
  OP_PARAMS = [
902
    _PInstanceName,
903
    _PMigrationMode,
904
    _PMigrationLive,
905
    ("cleanup", False, ht.TBool, None),
906
    ]
907

    
908

    
909
class OpInstanceMove(OpCode):
910
  """Move an instance.
911

912
  This move (with shutting down an instance and data copying) to an
913
  arbitrary node.
914

915
  @ivar instance_name: the name of the instance
916
  @ivar target_node: the destination node
917

918
  """
919
  OP_DSC_FIELD = "instance_name"
920
  OP_PARAMS = [
921
    _PInstanceName,
922
    _PShutdownTimeout,
923
    ("target_node", ht.NoDefault, ht.TNonEmptyString, None),
924
    ]
925

    
926

    
927
class OpInstanceConsole(OpCode):
928
  """Connect to an instance's console."""
929
  OP_DSC_FIELD = "instance_name"
930
  OP_PARAMS = [
931
    _PInstanceName
932
    ]
933

    
934

    
935
class OpInstanceActivateDisks(OpCode):
936
  """Activate an instance's disks."""
937
  OP_DSC_FIELD = "instance_name"
938
  OP_PARAMS = [
939
    _PInstanceName,
940
    ("ignore_size", False, ht.TBool, None),
941
    ]
942

    
943

    
944
class OpInstanceDeactivateDisks(OpCode):
945
  """Deactivate an instance's disks."""
946
  OP_DSC_FIELD = "instance_name"
947
  OP_PARAMS = [
948
    _PInstanceName,
949
    _PForce,
950
    ]
951

    
952

    
953
class OpInstanceRecreateDisks(OpCode):
954
  """Deactivate an instance's disks."""
955
  OP_DSC_FIELD = "instance_name"
956
  OP_PARAMS = [
957
    _PInstanceName,
958
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt), None),
959
    ]
960

    
961

    
962
class OpInstanceQuery(OpCode):
963
  """Compute the list of instances."""
964
  OP_PARAMS = [
965
    _POutputFields,
966
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
967
    ("use_locking", False, ht.TBool, None),
968
    ]
969

    
970

    
971
class OpInstanceQueryData(OpCode):
972
  """Compute the run-time status of instances."""
973
  OP_PARAMS = [
974
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
975
    ("static", False, ht.TBool, None),
976
    ]
977

    
978

    
979
class OpInstanceSetParams(OpCode):
980
  """Change the parameters of an instance."""
981
  OP_DSC_FIELD = "instance_name"
982
  OP_PARAMS = [
983
    _PInstanceName,
984
    _PForce,
985
    ("nics", ht.EmptyList, ht.TList, None),
986
    ("disks", ht.EmptyList, ht.TList, None),
987
    ("beparams", ht.EmptyDict, ht.TDict, None),
988
    ("hvparams", ht.EmptyDict, ht.TDict, None),
989
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate), None),
990
    ("remote_node", None, ht.TMaybeString, None),
991
    ("os_name", None, ht.TMaybeString, None),
992
    ("force_variant", False, ht.TBool, None),
993
    ("osparams", None, ht.TMaybeDict, None),
994
    ]
995

    
996

    
997
class OpInstanceGrowDisk(OpCode):
998
  """Grow a disk of an instance."""
999
  OP_DSC_FIELD = "instance_name"
1000
  OP_PARAMS = [
1001
    _PInstanceName,
1002
    ("disk", ht.NoDefault, ht.TInt, None),
1003
    ("amount", ht.NoDefault, ht.TInt, None),
1004
    ("wait_for_sync", True, ht.TBool, None),
1005
    ]
1006

    
1007

    
1008
# Node group opcodes
1009

    
1010
class OpGroupAdd(OpCode):
1011
  """Add a node group to the cluster."""
1012
  OP_DSC_FIELD = "group_name"
1013
  OP_PARAMS = [
1014
    _PGroupName,
1015
    ("ndparams", None, ht.TMaybeDict, None),
1016
    ("alloc_policy", None,
1017
     ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)), None),
1018
    ]
1019

    
1020

    
1021
class OpGroupAssignNodes(OpCode):
1022
  """Assign nodes to a node group."""
1023
  OP_DSC_FIELD = "group_name"
1024
  OP_PARAMS = [
1025
    _PGroupName,
1026
    _PForce,
1027
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
1028
    ]
1029

    
1030

    
1031
class OpGroupQuery(OpCode):
1032
  """Compute the list of node groups."""
1033
  OP_PARAMS = [
1034
    _POutputFields,
1035
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1036
    ]
1037

    
1038

    
1039
class OpGroupSetParams(OpCode):
1040
  """Change the parameters of a node group."""
1041
  OP_DSC_FIELD = "group_name"
1042
  OP_PARAMS = [
1043
    _PGroupName,
1044
    ("ndparams", None, ht.TMaybeDict, None),
1045
    ("alloc_policy", None, ht.TOr(ht.TNone,
1046
                                  ht.TElemOf(constants.VALID_ALLOC_POLICIES)), None),
1047
    ]
1048

    
1049

    
1050
class OpGroupRemove(OpCode):
1051
  """Remove a node group from the cluster."""
1052
  OP_DSC_FIELD = "group_name"
1053
  OP_PARAMS = [
1054
    _PGroupName,
1055
    ]
1056

    
1057

    
1058
class OpGroupRename(OpCode):
1059
  """Rename a node group in the cluster."""
1060
  OP_DSC_FIELD = "old_name"
1061
  OP_PARAMS = [
1062
    ("old_name", ht.NoDefault, ht.TNonEmptyString, None),
1063
    ("new_name", ht.NoDefault, ht.TNonEmptyString, None),
1064
    ]
1065

    
1066

    
1067
# OS opcodes
1068
class OpOsDiagnose(OpCode):
1069
  """Compute the list of guest operating systems."""
1070
  OP_PARAMS = [
1071
    _POutputFields,
1072
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1073
    ]
1074

    
1075

    
1076
# Exports opcodes
1077
class OpBackupQuery(OpCode):
1078
  """Compute the list of exported images."""
1079
  OP_PARAMS = [
1080
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1081
    ("use_locking", False, ht.TBool, None),
1082
    ]
1083

    
1084

    
1085
class OpBackupPrepare(OpCode):
1086
  """Prepares an instance export.
1087

1088
  @ivar instance_name: Instance name
1089
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1090

1091
  """
1092
  OP_DSC_FIELD = "instance_name"
1093
  OP_PARAMS = [
1094
    _PInstanceName,
1095
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES), None),
1096
    ]
1097

    
1098

    
1099
class OpBackupExport(OpCode):
1100
  """Export an instance.
1101

1102
  For local exports, the export destination is the node name. For remote
1103
  exports, the export destination is a list of tuples, each consisting of
1104
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1105
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1106
  destination X509 CA must be a signed certificate.
1107

1108
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1109
  @ivar target_node: Export destination
1110
  @ivar x509_key_name: X509 key to use (remote export only)
1111
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1112
                             only)
1113

1114
  """
1115
  OP_DSC_FIELD = "instance_name"
1116
  OP_PARAMS = [
1117
    _PInstanceName,
1118
    _PShutdownTimeout,
1119
    # TODO: Rename target_node as it changes meaning for different export modes
1120
    # (e.g. "destination")
1121
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList), None),
1122
    ("shutdown", True, ht.TBool, None),
1123
    ("remove_instance", False, ht.TBool, None),
1124
    ("ignore_remove_failures", False, ht.TBool, None),
1125
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES), None),
1126
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone), None),
1127
    ("destination_x509_ca", None, ht.TMaybeString, None),
1128
    ]
1129

    
1130

    
1131
class OpBackupRemove(OpCode):
1132
  """Remove an instance's export."""
1133
  OP_DSC_FIELD = "instance_name"
1134
  OP_PARAMS = [
1135
    _PInstanceName,
1136
    ]
1137

    
1138

    
1139
# Tags opcodes
1140
class OpTagsGet(OpCode):
1141
  """Returns the tags of the given object."""
1142
  OP_DSC_FIELD = "name"
1143
  OP_PARAMS = [
1144
    _PTagKind,
1145
    # Name is only meaningful for nodes and instances
1146
    ("name", ht.NoDefault, ht.TMaybeString, None),
1147
    ]
1148

    
1149

    
1150
class OpTagsSearch(OpCode):
1151
  """Searches the tags in the cluster for a given pattern."""
1152
  OP_DSC_FIELD = "pattern"
1153
  OP_PARAMS = [
1154
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1155
    ]
1156

    
1157

    
1158
class OpTagsSet(OpCode):
1159
  """Add a list of tags on a given object."""
1160
  OP_PARAMS = [
1161
    _PTagKind,
1162
    _PTags,
1163
    # Name is only meaningful for nodes and instances
1164
    ("name", ht.NoDefault, ht.TMaybeString, None),
1165
    ]
1166

    
1167

    
1168
class OpTagsDel(OpCode):
1169
  """Remove a list of tags from a given object."""
1170
  OP_PARAMS = [
1171
    _PTagKind,
1172
    _PTags,
1173
    # Name is only meaningful for nodes and instances
1174
    ("name", ht.NoDefault, ht.TMaybeString, None),
1175
    ]
1176

    
1177
# Test opcodes
1178
class OpTestDelay(OpCode):
1179
  """Sleeps for a configured amount of time.
1180

1181
  This is used just for debugging and testing.
1182

1183
  Parameters:
1184
    - duration: the time to sleep
1185
    - on_master: if true, sleep on the master
1186
    - on_nodes: list of nodes in which to sleep
1187

1188
  If the on_master parameter is true, it will execute a sleep on the
1189
  master (before any node sleep).
1190

1191
  If the on_nodes list is not empty, it will sleep on those nodes
1192
  (after the sleep on the master, if that is enabled).
1193

1194
  As an additional feature, the case of duration < 0 will be reported
1195
  as an execution error, so this opcode can be used as a failure
1196
  generator. The case of duration == 0 will not be treated specially.
1197

1198
  """
1199
  OP_DSC_FIELD = "duration"
1200
  OP_PARAMS = [
1201
    ("duration", ht.NoDefault, ht.TFloat, None),
1202
    ("on_master", True, ht.TBool, None),
1203
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1204
    ("repeat", 0, ht.TPositiveInt, None),
1205
    ]
1206

    
1207

    
1208
class OpTestAllocator(OpCode):
1209
  """Allocator framework testing.
1210

1211
  This opcode has two modes:
1212
    - gather and return allocator input for a given mode (allocate new
1213
      or replace secondary) and a given instance definition (direction
1214
      'in')
1215
    - run a selected allocator for a given operation (as above) and
1216
      return the allocator output (direction 'out')
1217

1218
  """
1219
  OP_DSC_FIELD = "allocator"
1220
  OP_PARAMS = [
1221
    ("direction", ht.NoDefault,
1222
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1223
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1224
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1225
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1226
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
1227
               ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1228
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1229
    ("hypervisor", None, ht.TMaybeString, None),
1230
    ("allocator", None, ht.TMaybeString, None),
1231
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1232
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1233
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1234
    ("os", None, ht.TMaybeString, None),
1235
    ("disk_template", None, ht.TMaybeString, None),
1236
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)), None),
1237
    ]
1238

    
1239

    
1240
class OpTestJqueue(OpCode):
1241
  """Utility opcode to test some aspects of the job queue.
1242

1243
  """
1244
  OP_PARAMS = [
1245
    ("notify_waitlock", False, ht.TBool, None),
1246
    ("notify_exec", False, ht.TBool, None),
1247
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1248
    ("fail", False, ht.TBool, None),
1249
    ]
1250

    
1251

    
1252
class OpTestDummy(OpCode):
1253
  """Utility opcode used by unittests.
1254

1255
  """
1256
  OP_PARAMS = [
1257
    ("result", ht.NoDefault, ht.NoType, None),
1258
    ("messages", ht.NoDefault, ht.NoType, None),
1259
    ("fail", ht.NoDefault, ht.NoType, None),
1260
    ]
1261
  WITH_LU = False
1262

    
1263

    
1264
def _GetOpList():
1265
  """Returns list of all defined opcodes.
1266

1267
  Does not eliminate duplicates by C{OP_ID}.
1268

1269
  """
1270
  return [v for v in globals().values()
1271
          if (isinstance(v, type) and issubclass(v, OpCode) and
1272
              hasattr(v, "OP_ID") and v is not OpCode)]
1273

    
1274

    
1275
OP_MAPPING = dict((v.OP_ID, v) for v in _GetOpList())