Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 45d4c81c

History | View | Annotate | Download (42.2 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
                  "Selected output fields")
50

    
51
#: the shutdown timeout
52
_PShutdownTimeout = \
53
  ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
54
   "How long to wait for instance to shut down")
55

    
56
#: the force parameter
57
_PForce = ("force", False, ht.TBool, "Whether to force the operation")
58

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

    
63
#: Whether to ignore offline nodes
64
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool,
65
                        "Whether to ignore offline nodes")
66

    
67
#: a required node name (for single-node LUs)
68
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString, "Node name")
69

    
70
#: a required node group name (for single-group LUs)
71
_PGroupName = ("group_name", ht.NoDefault, ht.TNonEmptyString, "Group name")
72

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

    
78
#: Obsolete 'live' migration mode (boolean)
79
_PMigrationLive = ("live", None, ht.TMaybeBool,
80
                   "Legacy setting for live migration, do not use")
81

    
82
#: Tag type
83
_PTagKind = ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES), None)
84

    
85
#: List of tag strings
86
_PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None)
87

    
88
_PForceVariant = ("force_variant", False, ht.TBool,
89
                  "Whether to force an unknown OS variant")
90

    
91
_PWaitForSync = ("wait_for_sync", True, ht.TBool,
92
                 "Whether to wait for the disk to synchronize")
93

    
94
_PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
95
                       "Whether to ignore disk consistency")
96

    
97
_PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
98

    
99
_PUseLocking = ("use_locking", False, ht.TBool,
100
                "Whether to use synchronization")
101

    
102
_PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
103

    
104
_PNodeGroupAllocPolicy = \
105
  ("alloc_policy", None,
106
   ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
107
   "Instance allocation policy")
108

    
109
_PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
110
                     "Default node parameters for group")
111

    
112
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
113

    
114
#: OP_ID conversion regular expression
115
_OPID_RE = re.compile("([a-z])([A-Z])")
116

    
117
#: Utility function for L{OpClusterSetParams}
118
_TestClusterOsList = ht.TOr(ht.TNone,
119
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
120
    ht.TMap(ht.WithDesc("GetFirstItem")(operator.itemgetter(0)),
121
            ht.TElemOf(constants.DDMS_VALUES)))))
122

    
123

    
124
def _NameToId(name):
125
  """Convert an opcode class name to an OP_ID.
126

127
  @type name: string
128
  @param name: the class name, as OpXxxYyy
129
  @rtype: string
130
  @return: the name in the OP_XXXX_YYYY format
131

132
  """
133
  if not name.startswith("Op"):
134
    return None
135
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
136
  # consume any input, and hence we would just have all the elements
137
  # in the list, one by one; but it seems that split doesn't work on
138
  # non-consuming input, hence we have to process the input string a
139
  # bit
140
  name = _OPID_RE.sub(r"\1,\2", name)
141
  elems = name.split(",")
142
  return "_".join(n.upper() for n in elems)
143

    
144

    
145
def RequireFileStorage():
146
  """Checks that file storage is enabled.
147

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

151
  @raise errors.OpPrereqError: when file storage is disabled
152

153
  """
154
  if not constants.ENABLE_FILE_STORAGE:
155
    raise errors.OpPrereqError("File storage disabled at configure time",
156
                               errors.ECODE_INVAL)
157

    
158

    
159
@ht.WithDesc("CheckFileStorage")
160
def _CheckFileStorage(value):
161
  """Ensures file storage is enabled if used.
162

163
  """
164
  if value == constants.DT_FILE:
165
    RequireFileStorage()
166
  return True
167

    
168

    
169
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
170
                             _CheckFileStorage)
171

    
172

    
173
def _CheckStorageType(storage_type):
174
  """Ensure a given storage type is valid.
175

176
  """
177
  if storage_type not in constants.VALID_STORAGE_TYPES:
178
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
179
                               errors.ECODE_INVAL)
180
  if storage_type == constants.ST_FILE:
181
    RequireFileStorage()
182
  return True
183

    
184

    
185
#: Storage type parameter
186
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
187
                 "Storage type")
188

    
189

    
190
class _AutoOpParamSlots(type):
191
  """Meta class for opcode definitions.
192

193
  """
194
  def __new__(mcs, name, bases, attrs):
195
    """Called when a class should be created.
196

197
    @param mcs: The meta class
198
    @param name: Name of created class
199
    @param bases: Base classes
200
    @type attrs: dict
201
    @param attrs: Class attributes
202

203
    """
204
    assert "__slots__" not in attrs, \
205
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
206
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
207

    
208
    attrs["OP_ID"] = _NameToId(name)
209

    
210
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
211
    params = attrs.setdefault("OP_PARAMS", [])
212

    
213
    # Use parameter names as slots
214
    slots = [pname for (pname, _, _, _) in params]
215

    
216
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
217
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
218

    
219
    attrs["__slots__"] = slots
220

    
221
    return type.__new__(mcs, name, bases, attrs)
222

    
223

    
224
class BaseOpCode(object):
225
  """A simple serializable object.
226

227
  This object serves as a parent class for OpCode without any custom
228
  field handling.
229

230
  """
231
  # pylint: disable-msg=E1101
232
  # as OP_ID is dynamically defined
233
  __metaclass__ = _AutoOpParamSlots
234

    
235
  def __init__(self, **kwargs):
236
    """Constructor for BaseOpCode.
237

238
    The constructor takes only keyword arguments and will set
239
    attributes on this object based on the passed arguments. As such,
240
    it means that you should not pass arguments which are not in the
241
    __slots__ attribute for this class.
242

243
    """
244
    slots = self._all_slots()
245
    for key in kwargs:
246
      if key not in slots:
247
        raise TypeError("Object %s doesn't support the parameter '%s'" %
248
                        (self.__class__.__name__, key))
249
      setattr(self, key, kwargs[key])
250

    
251
  def __getstate__(self):
252
    """Generic serializer.
253

254
    This method just returns the contents of the instance as a
255
    dictionary.
256

257
    @rtype:  C{dict}
258
    @return: the instance attributes and their values
259

260
    """
261
    state = {}
262
    for name in self._all_slots():
263
      if hasattr(self, name):
264
        state[name] = getattr(self, name)
265
    return state
266

    
267
  def __setstate__(self, state):
268
    """Generic unserializer.
269

270
    This method just restores from the serialized state the attributes
271
    of the current instance.
272

273
    @param state: the serialized opcode data
274
    @type state:  C{dict}
275

276
    """
277
    if not isinstance(state, dict):
278
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
279
                       type(state))
280

    
281
    for name in self._all_slots():
282
      if name not in state and hasattr(self, name):
283
        delattr(self, name)
284

    
285
    for name in state:
286
      setattr(self, name, state[name])
287

    
288
  @classmethod
289
  def _all_slots(cls):
290
    """Compute the list of all declared slots for a class.
291

292
    """
293
    slots = []
294
    for parent in cls.__mro__:
295
      slots.extend(getattr(parent, "__slots__", []))
296
    return slots
297

    
298
  @classmethod
299
  def GetAllParams(cls):
300
    """Compute list of all parameters for an opcode.
301

302
    """
303
    slots = []
304
    for parent in cls.__mro__:
305
      slots.extend(getattr(parent, "OP_PARAMS", []))
306
    return slots
307

    
308
  def Validate(self, set_defaults):
309
    """Validate opcode parameters, optionally setting default values.
310

311
    @type set_defaults: bool
312
    @param set_defaults: Whether to set default values
313
    @raise errors.OpPrereqError: When a parameter value doesn't match
314
                                 requirements
315

316
    """
317
    for (attr_name, default, test, _) in self.GetAllParams():
318
      assert test == ht.NoType or callable(test)
319

    
320
      if not hasattr(self, attr_name):
321
        if default == ht.NoDefault:
322
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
323
                                     (self.OP_ID, attr_name),
324
                                     errors.ECODE_INVAL)
325
        elif set_defaults:
326
          if callable(default):
327
            dval = default()
328
          else:
329
            dval = default
330
          setattr(self, attr_name, dval)
331

    
332
      if test == ht.NoType:
333
        # no tests here
334
        continue
335

    
336
      if set_defaults or hasattr(self, attr_name):
337
        attr_val = getattr(self, attr_name)
338
        if not test(attr_val):
339
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
340
                        self.OP_ID, attr_name, type(attr_val), attr_val)
341
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
342
                                     (self.OP_ID, attr_name),
343
                                     errors.ECODE_INVAL)
344

    
345

    
346
class OpCode(BaseOpCode):
347
  """Abstract OpCode.
348

349
  This is the root of the actual OpCode hierarchy. All clases derived
350
  from this class should override OP_ID.
351

352
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
353
               children of this class.
354
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
355
                      string returned by Summary(); see the docstring of that
356
                      method for details).
357
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
358
                   get if not already defined, and types they must match.
359
  @cvar WITH_LU: Boolean that specifies whether this should be included in
360
      mcpu's dispatch table
361
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
362
                 the check steps
363
  @ivar priority: Opcode priority for queue
364

365
  """
366
  # pylint: disable-msg=E1101
367
  # as OP_ID is dynamically defined
368
  WITH_LU = True
369
  OP_PARAMS = [
370
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
371
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
372
    ("priority", constants.OP_PRIO_DEFAULT,
373
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
374
    ]
375

    
376
  def __getstate__(self):
377
    """Specialized getstate for opcodes.
378

379
    This method adds to the state dictionary the OP_ID of the class,
380
    so that on unload we can identify the correct class for
381
    instantiating the opcode.
382

383
    @rtype:   C{dict}
384
    @return:  the state as a dictionary
385

386
    """
387
    data = BaseOpCode.__getstate__(self)
388
    data["OP_ID"] = self.OP_ID
389
    return data
390

    
391
  @classmethod
392
  def LoadOpCode(cls, data):
393
    """Generic load opcode method.
394

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

399
    @type data:  C{dict}
400
    @param data: the serialized opcode
401

402
    """
403
    if not isinstance(data, dict):
404
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
405
    if "OP_ID" not in data:
406
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
407
    op_id = data["OP_ID"]
408
    op_class = None
409
    if op_id in OP_MAPPING:
410
      op_class = OP_MAPPING[op_id]
411
    else:
412
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
413
                       op_id)
414
    op = op_class()
415
    new_data = data.copy()
416
    del new_data["OP_ID"]
417
    op.__setstate__(new_data)
418
    return op
419

    
420
  def Summary(self):
421
    """Generates a summary description of this opcode.
422

423
    The summary is the value of the OP_ID attribute (without the "OP_"
424
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
425
    defined; this field should allow to easily identify the operation
426
    (for an instance creation job, e.g., it would be the instance
427
    name).
428

429
    """
430
    assert self.OP_ID is not None and len(self.OP_ID) > 3
431
    # all OP_ID start with OP_, we remove that
432
    txt = self.OP_ID[3:]
433
    field_name = getattr(self, "OP_DSC_FIELD", None)
434
    if field_name:
435
      field_value = getattr(self, field_name, None)
436
      if isinstance(field_value, (list, tuple)):
437
        field_value = ",".join(str(i) for i in field_value)
438
      txt = "%s(%s)" % (txt, field_value)
439
    return txt
440

    
441

    
442
# cluster opcodes
443

    
444
class OpClusterPostInit(OpCode):
445
  """Post cluster initialization.
446

447
  This opcode does not touch the cluster at all. Its purpose is to run hooks
448
  after the cluster has been initialized.
449

450
  """
451

    
452

    
453
class OpClusterDestroy(OpCode):
454
  """Destroy the cluster.
455

456
  This opcode has no other parameters. All the state is irreversibly
457
  lost after the execution of this opcode.
458

459
  """
460

    
461

    
462
class OpClusterQuery(OpCode):
463
  """Query cluster information."""
464

    
465

    
466
class OpClusterVerify(OpCode):
467
  """Verify the cluster state.
468

469
  @type skip_checks: C{list}
470
  @ivar skip_checks: steps to be skipped from the verify process; this
471
                     needs to be a subset of
472
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
473
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
474

475
  """
476
  OP_PARAMS = [
477
    ("skip_checks", ht.EmptyList,
478
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
479
    ("verbose", False, ht.TBool, None),
480
    ("error_codes", False, ht.TBool, None),
481
    ("debug_simulate_errors", False, ht.TBool, None),
482
    ]
483

    
484

    
485
class OpClusterVerifyDisks(OpCode):
486
  """Verify the cluster disks.
487

488
  Parameters: none
489

490
  Result: a tuple of four elements:
491
    - list of node names with bad data returned (unreachable, etc.)
492
    - dict of node names with broken volume groups (values: error msg)
493
    - list of instances with degraded disks (that should be activated)
494
    - dict of instances with missing logical volumes (values: (node, vol)
495
      pairs with details about the missing volumes)
496

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

502
  Note that only instances that are drbd-based are taken into
503
  consideration. This might need to be revisited in the future.
504

505
  """
506

    
507

    
508
class OpClusterRepairDiskSizes(OpCode):
509
  """Verify the disk sizes of the instances and fixes configuration
510
  mimatches.
511

512
  Parameters: optional instances list, in case we want to restrict the
513
  checks to only a subset of the instances.
514

515
  Result: a list of tuples, (instance, disk, new-size) for changed
516
  configurations.
517

518
  In normal operation, the list should be empty.
519

520
  @type instances: list
521
  @ivar instances: the list of instances to check, or empty for all instances
522

523
  """
524
  OP_PARAMS = [
525
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
526
    ]
527

    
528

    
529
class OpClusterConfigQuery(OpCode):
530
  """Query cluster configuration values."""
531
  OP_PARAMS = [
532
    _POutputFields
533
    ]
534

    
535

    
536
class OpClusterRename(OpCode):
537
  """Rename the cluster.
538

539
  @type name: C{str}
540
  @ivar name: The new name of the cluster. The name and/or the master IP
541
              address will be changed to match the new name and its IP
542
              address.
543

544
  """
545
  OP_DSC_FIELD = "name"
546
  OP_PARAMS = [
547
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
548
    ]
549

    
550

    
551
class OpClusterSetParams(OpCode):
552
  """Change the parameters of the cluster.
553

554
  @type vg_name: C{str} or C{None}
555
  @ivar vg_name: The new volume group name or None to disable LVM usage.
556

557
  """
558
  OP_PARAMS = [
559
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
560
    ("enabled_hypervisors", None,
561
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
562
            ht.TNone),
563
     "List of enabled hypervisors"),
564
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
565
                              ht.TNone),
566
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
567
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
568
     "Cluster-wide backend parameter defaults"),
569
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
570
                            ht.TNone),
571
     "Cluster-wide per-OS hypervisor parameter defaults"),
572
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
573
                              ht.TNone),
574
     "Cluster-wide OS parameter defaults"),
575
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
576
     "Master candidate pool size"),
577
    ("uid_pool", None, ht.NoType,
578
     "Set UID pool, must be list of lists describing UID ranges (two items,"
579
     " start and end inclusive)"),
580
    ("add_uids", None, ht.NoType,
581
     "Extend UID pool, must be list of lists describing UID ranges (two"
582
     " items, start and end inclusive) to be added"),
583
    ("remove_uids", None, ht.NoType,
584
     "Shrink UID pool, must be list of lists describing UID ranges (two"
585
     " items, start and end inclusive) to be removed"),
586
    ("maintain_node_health", None, ht.TMaybeBool,
587
     "Whether to automatically maintain node health"),
588
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
589
     "Whether to wipe disks before allocating them to instances"),
590
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
591
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
592
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
593
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
594
     "Default iallocator for cluster"),
595
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
596
     "Master network device"),
597
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
598
     "List of reserved LVs"),
599
    ("hidden_os", None, _TestClusterOsList,
600
     "Modify list of hidden operating systems. Each modification must have"
601
     " two items, the operation and the OS name. The operation can be"
602
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
603
    ("blacklisted_os", None, _TestClusterOsList,
604
     "Modify list of blacklisted operating systems. Each modification must have"
605
     " two items, the operation and the OS name. The operation can be"
606
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
607
    ]
608

    
609

    
610
class OpClusterRedistConf(OpCode):
611
  """Force a full push of the cluster configuration.
612

613
  """
614

    
615

    
616
class OpQuery(OpCode):
617
  """Query for resources/items.
618

619
  @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
620
  @ivar fields: List of fields to retrieve
621
  @ivar filter: Query filter
622

623
  """
624
  OP_PARAMS = [
625
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY),
626
     "Resource(s) to query for"),
627
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
628
     "Requested fields"),
629
    ("filter", None, ht.TOr(ht.TNone,
630
                            ht.TListOf(ht.TOr(ht.TNonEmptyString, ht.TList))),
631
     "Query filter"),
632
    ]
633

    
634

    
635
class OpQueryFields(OpCode):
636
  """Query for available resource/item fields.
637

638
  @ivar what: Resources to query for, must be one of L{constants.QR_OP_QUERY}
639
  @ivar fields: List of fields to retrieve
640

641
  """
642
  OP_PARAMS = [
643
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY), None),
644
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)), None),
645
    ]
646

    
647

    
648
class OpOobCommand(OpCode):
649
  """Interact with OOB."""
650
  OP_PARAMS = [
651
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
652
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS), None),
653
    ("timeout", constants.OOB_TIMEOUT, ht.TInt, None),
654
    ("ignore_status", False, ht.TBool, None),
655
    ("force_master", False, ht.TBool, None),
656
    ]
657

    
658

    
659
# node opcodes
660

    
661
class OpNodeRemove(OpCode):
662
  """Remove a node.
663

664
  @type node_name: C{str}
665
  @ivar node_name: The name of the node to remove. If the node still has
666
                   instances on it, the operation will fail.
667

668
  """
669
  OP_DSC_FIELD = "node_name"
670
  OP_PARAMS = [
671
    _PNodeName,
672
    ]
673

    
674

    
675
class OpNodeAdd(OpCode):
676
  """Add a node to the cluster.
677

678
  @type node_name: C{str}
679
  @ivar node_name: The name of the node to add. This can be a short name,
680
                   but it will be expanded to the FQDN.
681
  @type primary_ip: IP address
682
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
683
                    opcode is submitted, but will be filled during the node
684
                    add (so it will be visible in the job query).
685
  @type secondary_ip: IP address
686
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
687
                      if the cluster has been initialized in 'dual-network'
688
                      mode, otherwise it must not be given.
689
  @type readd: C{bool}
690
  @ivar readd: Whether to re-add an existing node to the cluster. If
691
               this is not passed, then the operation will abort if the node
692
               name is already in the cluster; use this parameter to 'repair'
693
               a node that had its configuration broken, or was reinstalled
694
               without removal from the cluster.
695
  @type group: C{str}
696
  @ivar group: The node group to which this node will belong.
697
  @type vm_capable: C{bool}
698
  @ivar vm_capable: The vm_capable node attribute
699
  @type master_capable: C{bool}
700
  @ivar master_capable: The master_capable node attribute
701

702
  """
703
  OP_DSC_FIELD = "node_name"
704
  OP_PARAMS = [
705
    _PNodeName,
706
    ("primary_ip", None, ht.NoType, "Primary IP address"),
707
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
708
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
709
    ("group", None, ht.TMaybeString, "Initial node group"),
710
    ("master_capable", None, ht.TMaybeBool,
711
     "Whether node can become master or master candidate"),
712
    ("vm_capable", None, ht.TMaybeBool,
713
     "Whether node can host instances"),
714
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
715
    ]
716

    
717

    
718
class OpNodeQuery(OpCode):
719
  """Compute the list of nodes."""
720
  OP_PARAMS = [
721
    _POutputFields,
722
    _PUseLocking,
723
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
724
     "Empty list to query all nodes, node names otherwise"),
725
    ]
726

    
727

    
728
class OpNodeQueryvols(OpCode):
729
  """Get list of volumes on node."""
730
  OP_PARAMS = [
731
    _POutputFields,
732
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
733
     "Empty list to query all nodes, node names otherwise"),
734
    ]
735

    
736

    
737
class OpNodeQueryStorage(OpCode):
738
  """Get information on storage for node(s)."""
739
  OP_PARAMS = [
740
    _POutputFields,
741
    _PStorageType,
742
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
743
    ("name", None, ht.TMaybeString, "Storage name"),
744
    ]
745

    
746

    
747
class OpNodeModifyStorage(OpCode):
748
  """Modifies the properies of a storage unit"""
749
  OP_PARAMS = [
750
    _PNodeName,
751
    _PStorageType,
752
    _PStorageName,
753
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
754
    ]
755

    
756

    
757
class OpRepairNodeStorage(OpCode):
758
  """Repairs the volume group on a node."""
759
  OP_DSC_FIELD = "node_name"
760
  OP_PARAMS = [
761
    _PNodeName,
762
    _PStorageType,
763
    _PStorageName,
764
    _PIgnoreConsistency,
765
    ]
766

    
767

    
768
class OpNodeSetParams(OpCode):
769
  """Change the parameters of a node."""
770
  OP_DSC_FIELD = "node_name"
771
  OP_PARAMS = [
772
    _PNodeName,
773
    _PForce,
774
    ("master_candidate", None, ht.TMaybeBool,
775
     "Whether the node should become a master candidate"),
776
    ("offline", None, ht.TMaybeBool,
777
     "Whether the node should be marked as offline"),
778
    ("drained", None, ht.TMaybeBool,
779
     "Whether the node should be marked as drained"),
780
    ("auto_promote", False, ht.TBool,
781
     "Whether node(s) should be promoted to master candidate if necessary"),
782
    ("master_capable", None, ht.TMaybeBool,
783
     "Denote whether node can become master or master candidate"),
784
    ("vm_capable", None, ht.TMaybeBool,
785
     "Denote whether node can host instances"),
786
    ("secondary_ip", None, ht.TMaybeString,
787
     "Change node's secondary IP address"),
788
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
789
    ("powered", None, ht.TMaybeBool,
790
     "Whether the node should be marked as powered"),
791
    ]
792

    
793

    
794
class OpNodePowercycle(OpCode):
795
  """Tries to powercycle a node."""
796
  OP_DSC_FIELD = "node_name"
797
  OP_PARAMS = [
798
    _PNodeName,
799
    _PForce,
800
    ]
801

    
802

    
803
class OpNodeMigrate(OpCode):
804
  """Migrate all instances from a node."""
805
  OP_DSC_FIELD = "node_name"
806
  OP_PARAMS = [
807
    _PNodeName,
808
    _PMigrationMode,
809
    _PMigrationLive,
810
    ]
811

    
812

    
813
class OpNodeEvacStrategy(OpCode):
814
  """Compute the evacuation strategy for a list of nodes."""
815
  OP_DSC_FIELD = "nodes"
816
  OP_PARAMS = [
817
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
818
    ("remote_node", None, ht.TMaybeString, None),
819
    ("iallocator", None, ht.TMaybeString, None),
820
    ]
821

    
822

    
823
# instance opcodes
824

    
825
class OpInstanceCreate(OpCode):
826
  """Create an instance.
827

828
  @ivar instance_name: Instance name
829
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
830
  @ivar source_handshake: Signed handshake from source (remote import only)
831
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
832
  @ivar source_instance_name: Previous name of instance (remote import only)
833
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
834
    (remote import only)
835

836
  """
837
  OP_DSC_FIELD = "instance_name"
838
  OP_PARAMS = [
839
    _PInstanceName,
840
    _PForceVariant,
841
    _PWaitForSync,
842
    _PNameCheck,
843
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
844
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict), "Disk descriptions"),
845
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
846
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
847
     "Driver for file-backed disks"),
848
    ("file_storage_dir", None, ht.TMaybeString,
849
     "Directory for storing file-backed disks"),
850
    ("hvparams", ht.EmptyDict, ht.TDict,
851
     "Hypervisor parameters for instance, hypervisor-dependent"),
852
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
853
    ("iallocator", None, ht.TMaybeString,
854
     "Iallocator for deciding which node(s) to use"),
855
    ("identify_defaults", False, ht.TBool,
856
     "Reset instance parameters to default if equal"),
857
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
858
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
859
     "Instance creation mode"),
860
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict),
861
     "List of NIC (network interface) definitions"),
862
    ("no_install", None, ht.TMaybeBool,
863
     "Do not install the OS (will disable automatic start)"),
864
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
865
    ("os_type", None, ht.TMaybeString, "Operating system"),
866
    ("pnode", None, ht.TMaybeString, "Primary node"),
867
    ("snode", None, ht.TMaybeString, "Secondary node"),
868
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
869
     "Signed handshake from source (remote import only)"),
870
    ("source_instance_name", None, ht.TMaybeString,
871
     "Source instance name (remote import only)"),
872
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
873
     ht.TPositiveInt, "How long source instance was given to shut down"),
874
    ("source_x509_ca", None, ht.TMaybeString,
875
     "Source X509 CA in PEM format (remote import only)"),
876
    ("src_node", None, ht.TMaybeString, "Source node for import"),
877
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
878
    ("start", True, ht.TBool, "Whether to start instance after creation"),
879
    ]
880

    
881

    
882
class OpInstanceReinstall(OpCode):
883
  """Reinstall an instance's OS."""
884
  OP_DSC_FIELD = "instance_name"
885
  OP_PARAMS = [
886
    _PInstanceName,
887
    _PForceVariant,
888
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
889
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
890
    ]
891

    
892

    
893
class OpInstanceRemove(OpCode):
894
  """Remove an instance."""
895
  OP_DSC_FIELD = "instance_name"
896
  OP_PARAMS = [
897
    _PInstanceName,
898
    _PShutdownTimeout,
899
    ("ignore_failures", False, ht.TBool,
900
     "Whether to ignore failures during removal"),
901
    ]
902

    
903

    
904
class OpInstanceRename(OpCode):
905
  """Rename an instance."""
906
  OP_PARAMS = [
907
    _PInstanceName,
908
    _PNameCheck,
909
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
910
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
911
    ]
912

    
913

    
914
class OpInstanceStartup(OpCode):
915
  """Startup an instance."""
916
  OP_DSC_FIELD = "instance_name"
917
  OP_PARAMS = [
918
    _PInstanceName,
919
    _PForce,
920
    _PIgnoreOfflineNodes,
921
    ("hvparams", ht.EmptyDict, ht.TDict,
922
     "Temporary hypervisor parameters, hypervisor-dependent"),
923
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
924
    ]
925

    
926

    
927
class OpInstanceShutdown(OpCode):
928
  """Shutdown an instance."""
929
  OP_DSC_FIELD = "instance_name"
930
  OP_PARAMS = [
931
    _PInstanceName,
932
    _PIgnoreOfflineNodes,
933
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
934
     "How long to wait for instance to shut down"),
935
    ]
936

    
937

    
938
class OpInstanceReboot(OpCode):
939
  """Reboot an instance."""
940
  OP_DSC_FIELD = "instance_name"
941
  OP_PARAMS = [
942
    _PInstanceName,
943
    _PShutdownTimeout,
944
    ("ignore_secondaries", False, ht.TBool,
945
     "Whether to start the instance even if secondary disks are failing"),
946
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
947
     "How to reboot instance"),
948
    ]
949

    
950

    
951
class OpInstanceReplaceDisks(OpCode):
952
  """Replace the disks of an instance."""
953
  OP_DSC_FIELD = "instance_name"
954
  OP_PARAMS = [
955
    _PInstanceName,
956
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
957
     "Replacement mode"),
958
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
959
     "Disk indexes"),
960
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
961
    ("iallocator", None, ht.TMaybeString,
962
     "Iallocator for deciding new secondary node"),
963
    ("early_release", False, ht.TBool,
964
     "Whether to release locks as soon as possible"),
965
    ]
966

    
967

    
968
class OpInstanceFailover(OpCode):
969
  """Failover an instance."""
970
  OP_DSC_FIELD = "instance_name"
971
  OP_PARAMS = [
972
    _PInstanceName,
973
    _PShutdownTimeout,
974
    _PIgnoreConsistency,
975
    ]
976

    
977

    
978
class OpInstanceMigrate(OpCode):
979
  """Migrate an instance.
980

981
  This migrates (without shutting down an instance) to its secondary
982
  node.
983

984
  @ivar instance_name: the name of the instance
985
  @ivar mode: the migration mode (live, non-live or None for auto)
986

987
  """
988
  OP_DSC_FIELD = "instance_name"
989
  OP_PARAMS = [
990
    _PInstanceName,
991
    _PMigrationMode,
992
    _PMigrationLive,
993
    ("cleanup", False, ht.TBool,
994
     "Whether a previously failed migration should be cleaned up"),
995
    ]
996

    
997

    
998
class OpInstanceMove(OpCode):
999
  """Move an instance.
1000

1001
  This move (with shutting down an instance and data copying) to an
1002
  arbitrary node.
1003

1004
  @ivar instance_name: the name of the instance
1005
  @ivar target_node: the destination node
1006

1007
  """
1008
  OP_DSC_FIELD = "instance_name"
1009
  OP_PARAMS = [
1010
    _PInstanceName,
1011
    _PShutdownTimeout,
1012
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1013
    ]
1014

    
1015

    
1016
class OpInstanceConsole(OpCode):
1017
  """Connect to an instance's console."""
1018
  OP_DSC_FIELD = "instance_name"
1019
  OP_PARAMS = [
1020
    _PInstanceName
1021
    ]
1022

    
1023

    
1024
class OpInstanceActivateDisks(OpCode):
1025
  """Activate an instance's disks."""
1026
  OP_DSC_FIELD = "instance_name"
1027
  OP_PARAMS = [
1028
    _PInstanceName,
1029
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1030
    ]
1031

    
1032

    
1033
class OpInstanceDeactivateDisks(OpCode):
1034
  """Deactivate an instance's disks."""
1035
  OP_DSC_FIELD = "instance_name"
1036
  OP_PARAMS = [
1037
    _PInstanceName,
1038
    _PForce,
1039
    ]
1040

    
1041

    
1042
class OpInstanceRecreateDisks(OpCode):
1043
  """Deactivate an instance's disks."""
1044
  OP_DSC_FIELD = "instance_name"
1045
  OP_PARAMS = [
1046
    _PInstanceName,
1047
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1048
     "List of disk indexes"),
1049
    ]
1050

    
1051

    
1052
class OpInstanceQuery(OpCode):
1053
  """Compute the list of instances."""
1054
  OP_PARAMS = [
1055
    _POutputFields,
1056
    _PUseLocking,
1057
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1058
     "Empty list to query all instances, instance names otherwise"),
1059
    ]
1060

    
1061

    
1062
class OpInstanceQueryData(OpCode):
1063
  """Compute the run-time status of instances."""
1064
  OP_PARAMS = [
1065
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1066
    ("static", False, ht.TBool, None),
1067
    ]
1068

    
1069

    
1070
class OpInstanceSetParams(OpCode):
1071
  """Change the parameters of an instance."""
1072
  OP_DSC_FIELD = "instance_name"
1073
  OP_PARAMS = [
1074
    _PInstanceName,
1075
    _PForce,
1076
    _PForceVariant,
1077
    ("nics", ht.EmptyList, ht.TList,
1078
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1079
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1080
     " ``%s`` to remove the last NIC or a number to modify the settings"
1081
     " of the NIC with that index." %
1082
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1083
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1084
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1085
    ("hvparams", ht.EmptyDict, ht.TDict,
1086
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1087
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1088
     "Disk template for instance"),
1089
    ("remote_node", None, ht.TMaybeString,
1090
     "Secondary node (used when changing disk template)"),
1091
    ("os_name", None, ht.TMaybeString,
1092
     "Change instance's OS name. Does not reinstall the instance."),
1093
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1094
    ]
1095

    
1096

    
1097
class OpInstanceGrowDisk(OpCode):
1098
  """Grow a disk of an instance."""
1099
  OP_DSC_FIELD = "instance_name"
1100
  OP_PARAMS = [
1101
    _PInstanceName,
1102
    _PWaitForSync,
1103
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1104
    ("amount", ht.NoDefault, ht.TInt,
1105
     "Amount of disk space to add (megabytes)"),
1106
    ]
1107

    
1108

    
1109
# Node group opcodes
1110

    
1111
class OpGroupAdd(OpCode):
1112
  """Add a node group to the cluster."""
1113
  OP_DSC_FIELD = "group_name"
1114
  OP_PARAMS = [
1115
    _PGroupName,
1116
    _PNodeGroupAllocPolicy,
1117
    _PGroupNodeParams,
1118
    ]
1119

    
1120

    
1121
class OpGroupAssignNodes(OpCode):
1122
  """Assign nodes to a node group."""
1123
  OP_DSC_FIELD = "group_name"
1124
  OP_PARAMS = [
1125
    _PGroupName,
1126
    _PForce,
1127
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1128
     "List of nodes to assign"),
1129
    ]
1130

    
1131

    
1132
class OpGroupQuery(OpCode):
1133
  """Compute the list of node groups."""
1134
  OP_PARAMS = [
1135
    _POutputFields,
1136
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1137
     "Empty list to query all groups, group names otherwise"),
1138
    ]
1139

    
1140

    
1141
class OpGroupSetParams(OpCode):
1142
  """Change the parameters of a node group."""
1143
  OP_DSC_FIELD = "group_name"
1144
  OP_PARAMS = [
1145
    _PGroupName,
1146
    _PNodeGroupAllocPolicy,
1147
    _PGroupNodeParams,
1148
    ]
1149

    
1150

    
1151
class OpGroupRemove(OpCode):
1152
  """Remove a node group from the cluster."""
1153
  OP_DSC_FIELD = "group_name"
1154
  OP_PARAMS = [
1155
    _PGroupName,
1156
    ]
1157

    
1158

    
1159
class OpGroupRename(OpCode):
1160
  """Rename a node group in the cluster."""
1161
  OP_DSC_FIELD = "old_name"
1162
  OP_PARAMS = [
1163
    ("old_name", ht.NoDefault, ht.TNonEmptyString, None),
1164
    ("new_name", ht.NoDefault, ht.TNonEmptyString, None),
1165
    ]
1166

    
1167

    
1168
# OS opcodes
1169
class OpOsDiagnose(OpCode):
1170
  """Compute the list of guest operating systems."""
1171
  OP_PARAMS = [
1172
    _POutputFields,
1173
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1174
     "Which operating systems to diagnose"),
1175
    ]
1176

    
1177

    
1178
# Exports opcodes
1179
class OpBackupQuery(OpCode):
1180
  """Compute the list of exported images."""
1181
  OP_PARAMS = [
1182
    _PUseLocking,
1183
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1184
     "Empty list to query all nodes, node names otherwise"),
1185
    ]
1186

    
1187

    
1188
class OpBackupPrepare(OpCode):
1189
  """Prepares an instance export.
1190

1191
  @ivar instance_name: Instance name
1192
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1193

1194
  """
1195
  OP_DSC_FIELD = "instance_name"
1196
  OP_PARAMS = [
1197
    _PInstanceName,
1198
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1199
     "Export mode"),
1200
    ]
1201

    
1202

    
1203
class OpBackupExport(OpCode):
1204
  """Export an instance.
1205

1206
  For local exports, the export destination is the node name. For remote
1207
  exports, the export destination is a list of tuples, each consisting of
1208
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1209
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1210
  destination X509 CA must be a signed certificate.
1211

1212
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1213
  @ivar target_node: Export destination
1214
  @ivar x509_key_name: X509 key to use (remote export only)
1215
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1216
                             only)
1217

1218
  """
1219
  OP_DSC_FIELD = "instance_name"
1220
  OP_PARAMS = [
1221
    _PInstanceName,
1222
    _PShutdownTimeout,
1223
    # TODO: Rename target_node as it changes meaning for different export modes
1224
    # (e.g. "destination")
1225
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1226
     "Destination information, depends on export mode"),
1227
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1228
    ("remove_instance", False, ht.TBool,
1229
     "Whether to remove instance after export"),
1230
    ("ignore_remove_failures", False, ht.TBool,
1231
     "Whether to ignore failures while removing instances"),
1232
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1233
     "Export mode"),
1234
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1235
     "Name of X509 key (remote export only)"),
1236
    ("destination_x509_ca", None, ht.TMaybeString,
1237
     "Destination X509 CA (remote export only)"),
1238
    ]
1239

    
1240

    
1241
class OpBackupRemove(OpCode):
1242
  """Remove an instance's export."""
1243
  OP_DSC_FIELD = "instance_name"
1244
  OP_PARAMS = [
1245
    _PInstanceName,
1246
    ]
1247

    
1248

    
1249
# Tags opcodes
1250
class OpTagsGet(OpCode):
1251
  """Returns the tags of the given object."""
1252
  OP_DSC_FIELD = "name"
1253
  OP_PARAMS = [
1254
    _PTagKind,
1255
    # Name is only meaningful for nodes and instances
1256
    ("name", ht.NoDefault, ht.TMaybeString, None),
1257
    ]
1258

    
1259

    
1260
class OpTagsSearch(OpCode):
1261
  """Searches the tags in the cluster for a given pattern."""
1262
  OP_DSC_FIELD = "pattern"
1263
  OP_PARAMS = [
1264
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1265
    ]
1266

    
1267

    
1268
class OpTagsSet(OpCode):
1269
  """Add a list of tags on a given object."""
1270
  OP_PARAMS = [
1271
    _PTagKind,
1272
    _PTags,
1273
    # Name is only meaningful for nodes and instances
1274
    ("name", ht.NoDefault, ht.TMaybeString, None),
1275
    ]
1276

    
1277

    
1278
class OpTagsDel(OpCode):
1279
  """Remove a list of tags from a given object."""
1280
  OP_PARAMS = [
1281
    _PTagKind,
1282
    _PTags,
1283
    # Name is only meaningful for nodes and instances
1284
    ("name", ht.NoDefault, ht.TMaybeString, None),
1285
    ]
1286

    
1287
# Test opcodes
1288
class OpTestDelay(OpCode):
1289
  """Sleeps for a configured amount of time.
1290

1291
  This is used just for debugging and testing.
1292

1293
  Parameters:
1294
    - duration: the time to sleep
1295
    - on_master: if true, sleep on the master
1296
    - on_nodes: list of nodes in which to sleep
1297

1298
  If the on_master parameter is true, it will execute a sleep on the
1299
  master (before any node sleep).
1300

1301
  If the on_nodes list is not empty, it will sleep on those nodes
1302
  (after the sleep on the master, if that is enabled).
1303

1304
  As an additional feature, the case of duration < 0 will be reported
1305
  as an execution error, so this opcode can be used as a failure
1306
  generator. The case of duration == 0 will not be treated specially.
1307

1308
  """
1309
  OP_DSC_FIELD = "duration"
1310
  OP_PARAMS = [
1311
    ("duration", ht.NoDefault, ht.TFloat, None),
1312
    ("on_master", True, ht.TBool, None),
1313
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1314
    ("repeat", 0, ht.TPositiveInt, None),
1315
    ]
1316

    
1317

    
1318
class OpTestAllocator(OpCode):
1319
  """Allocator framework testing.
1320

1321
  This opcode has two modes:
1322
    - gather and return allocator input for a given mode (allocate new
1323
      or replace secondary) and a given instance definition (direction
1324
      'in')
1325
    - run a selected allocator for a given operation (as above) and
1326
      return the allocator output (direction 'out')
1327

1328
  """
1329
  OP_DSC_FIELD = "allocator"
1330
  OP_PARAMS = [
1331
    ("direction", ht.NoDefault,
1332
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1333
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1334
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1335
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1336
     ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
1337
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1338
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1339
    ("hypervisor", None, ht.TMaybeString, None),
1340
    ("allocator", None, ht.TMaybeString, None),
1341
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1342
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1343
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1344
    ("os", None, ht.TMaybeString, None),
1345
    ("disk_template", None, ht.TMaybeString, None),
1346
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1347
     None),
1348
    ]
1349

    
1350

    
1351
class OpTestJqueue(OpCode):
1352
  """Utility opcode to test some aspects of the job queue.
1353

1354
  """
1355
  OP_PARAMS = [
1356
    ("notify_waitlock", False, ht.TBool, None),
1357
    ("notify_exec", False, ht.TBool, None),
1358
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1359
    ("fail", False, ht.TBool, None),
1360
    ]
1361

    
1362

    
1363
class OpTestDummy(OpCode):
1364
  """Utility opcode used by unittests.
1365

1366
  """
1367
  OP_PARAMS = [
1368
    ("result", ht.NoDefault, ht.NoType, None),
1369
    ("messages", ht.NoDefault, ht.NoType, None),
1370
    ("fail", ht.NoDefault, ht.NoType, None),
1371
    ]
1372
  WITH_LU = False
1373

    
1374

    
1375
def _GetOpList():
1376
  """Returns list of all defined opcodes.
1377

1378
  Does not eliminate duplicates by C{OP_ID}.
1379

1380
  """
1381
  return [v for v in globals().values()
1382
          if (isinstance(v, type) and issubclass(v, OpCode) and
1383
              hasattr(v, "OP_ID") and v is not OpCode)]
1384

    
1385

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