Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ b107fe05

History | View | Annotate | Download (44.7 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
_PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
113
               "Resource(s) to query for")
114

    
115
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
116

    
117
#: OP_ID conversion regular expression
118
_OPID_RE = re.compile("([a-z])([A-Z])")
119

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

    
126

    
127
# TODO: Generate check from constants.INIC_PARAMS_TYPES
128
#: Utility function for testing NIC definitions
129
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
130
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
131

    
132

    
133
def _NameToId(name):
134
  """Convert an opcode class name to an OP_ID.
135

136
  @type name: string
137
  @param name: the class name, as OpXxxYyy
138
  @rtype: string
139
  @return: the name in the OP_XXXX_YYYY format
140

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

    
153

    
154
def RequireFileStorage():
155
  """Checks that file storage is enabled.
156

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

160
  @raise errors.OpPrereqError: when file storage is disabled
161

162
  """
163
  if not constants.ENABLE_FILE_STORAGE:
164
    raise errors.OpPrereqError("File storage disabled at configure time",
165
                               errors.ECODE_INVAL)
166

    
167

    
168
def RequireSharedFileStorage():
169
  """Checks that shared file storage is enabled.
170

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

174
  @raise errors.OpPrereqError: when shared file storage is disabled
175

176
  """
177
  if not constants.ENABLE_SHARED_FILE_STORAGE:
178
    raise errors.OpPrereqError("Shared file storage disabled at"
179
                               " configure time", errors.ECODE_INVAL)
180

    
181

    
182
@ht.WithDesc("CheckFileStorage")
183
def _CheckFileStorage(value):
184
  """Ensures file storage is enabled if used.
185

186
  """
187
  if value == constants.DT_FILE:
188
    RequireFileStorage()
189
  elif value == constants.DT_SHARED_FILE:
190
    RequireSharedFileStorage()
191
  return True
192

    
193

    
194
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
195
                             _CheckFileStorage)
196

    
197

    
198
def _CheckStorageType(storage_type):
199
  """Ensure a given storage type is valid.
200

201
  """
202
  if storage_type not in constants.VALID_STORAGE_TYPES:
203
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
204
                               errors.ECODE_INVAL)
205
  if storage_type == constants.ST_FILE:
206
    RequireFileStorage()
207
  return True
208

    
209

    
210
#: Storage type parameter
211
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
212
                 "Storage type")
213

    
214

    
215
class _AutoOpParamSlots(type):
216
  """Meta class for opcode definitions.
217

218
  """
219
  def __new__(mcs, name, bases, attrs):
220
    """Called when a class should be created.
221

222
    @param mcs: The meta class
223
    @param name: Name of created class
224
    @param bases: Base classes
225
    @type attrs: dict
226
    @param attrs: Class attributes
227

228
    """
229
    assert "__slots__" not in attrs, \
230
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
231
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
232

    
233
    attrs["OP_ID"] = _NameToId(name)
234

    
235
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
236
    params = attrs.setdefault("OP_PARAMS", [])
237

    
238
    # Use parameter names as slots
239
    slots = [pname for (pname, _, _, _) in params]
240

    
241
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
242
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
243

    
244
    attrs["__slots__"] = slots
245

    
246
    return type.__new__(mcs, name, bases, attrs)
247

    
248

    
249
class BaseOpCode(object):
250
  """A simple serializable object.
251

252
  This object serves as a parent class for OpCode without any custom
253
  field handling.
254

255
  """
256
  # pylint: disable-msg=E1101
257
  # as OP_ID is dynamically defined
258
  __metaclass__ = _AutoOpParamSlots
259

    
260
  def __init__(self, **kwargs):
261
    """Constructor for BaseOpCode.
262

263
    The constructor takes only keyword arguments and will set
264
    attributes on this object based on the passed arguments. As such,
265
    it means that you should not pass arguments which are not in the
266
    __slots__ attribute for this class.
267

268
    """
269
    slots = self._all_slots()
270
    for key in kwargs:
271
      if key not in slots:
272
        raise TypeError("Object %s doesn't support the parameter '%s'" %
273
                        (self.__class__.__name__, key))
274
      setattr(self, key, kwargs[key])
275

    
276
  def __getstate__(self):
277
    """Generic serializer.
278

279
    This method just returns the contents of the instance as a
280
    dictionary.
281

282
    @rtype:  C{dict}
283
    @return: the instance attributes and their values
284

285
    """
286
    state = {}
287
    for name in self._all_slots():
288
      if hasattr(self, name):
289
        state[name] = getattr(self, name)
290
    return state
291

    
292
  def __setstate__(self, state):
293
    """Generic unserializer.
294

295
    This method just restores from the serialized state the attributes
296
    of the current instance.
297

298
    @param state: the serialized opcode data
299
    @type state:  C{dict}
300

301
    """
302
    if not isinstance(state, dict):
303
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
304
                       type(state))
305

    
306
    for name in self._all_slots():
307
      if name not in state and hasattr(self, name):
308
        delattr(self, name)
309

    
310
    for name in state:
311
      setattr(self, name, state[name])
312

    
313
  @classmethod
314
  def _all_slots(cls):
315
    """Compute the list of all declared slots for a class.
316

317
    """
318
    slots = []
319
    for parent in cls.__mro__:
320
      slots.extend(getattr(parent, "__slots__", []))
321
    return slots
322

    
323
  @classmethod
324
  def GetAllParams(cls):
325
    """Compute list of all parameters for an opcode.
326

327
    """
328
    slots = []
329
    for parent in cls.__mro__:
330
      slots.extend(getattr(parent, "OP_PARAMS", []))
331
    return slots
332

    
333
  def Validate(self, set_defaults):
334
    """Validate opcode parameters, optionally setting default values.
335

336
    @type set_defaults: bool
337
    @param set_defaults: Whether to set default values
338
    @raise errors.OpPrereqError: When a parameter value doesn't match
339
                                 requirements
340

341
    """
342
    for (attr_name, default, test, _) in self.GetAllParams():
343
      assert test == ht.NoType or callable(test)
344

    
345
      if not hasattr(self, attr_name):
346
        if default == ht.NoDefault:
347
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
348
                                     (self.OP_ID, attr_name),
349
                                     errors.ECODE_INVAL)
350
        elif set_defaults:
351
          if callable(default):
352
            dval = default()
353
          else:
354
            dval = default
355
          setattr(self, attr_name, dval)
356

    
357
      if test == ht.NoType:
358
        # no tests here
359
        continue
360

    
361
      if set_defaults or hasattr(self, attr_name):
362
        attr_val = getattr(self, attr_name)
363
        if not test(attr_val):
364
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
365
                        self.OP_ID, attr_name, type(attr_val), attr_val)
366
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
367
                                     (self.OP_ID, attr_name),
368
                                     errors.ECODE_INVAL)
369

    
370

    
371
class OpCode(BaseOpCode):
372
  """Abstract OpCode.
373

374
  This is the root of the actual OpCode hierarchy. All clases derived
375
  from this class should override OP_ID.
376

377
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
378
               children of this class.
379
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
380
                      string returned by Summary(); see the docstring of that
381
                      method for details).
382
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
383
                   get if not already defined, and types they must match.
384
  @cvar WITH_LU: Boolean that specifies whether this should be included in
385
      mcpu's dispatch table
386
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
387
                 the check steps
388
  @ivar priority: Opcode priority for queue
389

390
  """
391
  # pylint: disable-msg=E1101
392
  # as OP_ID is dynamically defined
393
  WITH_LU = True
394
  OP_PARAMS = [
395
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
396
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
397
    ("priority", constants.OP_PRIO_DEFAULT,
398
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
399
    ]
400

    
401
  def __getstate__(self):
402
    """Specialized getstate for opcodes.
403

404
    This method adds to the state dictionary the OP_ID of the class,
405
    so that on unload we can identify the correct class for
406
    instantiating the opcode.
407

408
    @rtype:   C{dict}
409
    @return:  the state as a dictionary
410

411
    """
412
    data = BaseOpCode.__getstate__(self)
413
    data["OP_ID"] = self.OP_ID
414
    return data
415

    
416
  @classmethod
417
  def LoadOpCode(cls, data):
418
    """Generic load opcode method.
419

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

424
    @type data:  C{dict}
425
    @param data: the serialized opcode
426

427
    """
428
    if not isinstance(data, dict):
429
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
430
    if "OP_ID" not in data:
431
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
432
    op_id = data["OP_ID"]
433
    op_class = None
434
    if op_id in OP_MAPPING:
435
      op_class = OP_MAPPING[op_id]
436
    else:
437
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
438
                       op_id)
439
    op = op_class()
440
    new_data = data.copy()
441
    del new_data["OP_ID"]
442
    op.__setstate__(new_data)
443
    return op
444

    
445
  def Summary(self):
446
    """Generates a summary description of this opcode.
447

448
    The summary is the value of the OP_ID attribute (without the "OP_"
449
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
450
    defined; this field should allow to easily identify the operation
451
    (for an instance creation job, e.g., it would be the instance
452
    name).
453

454
    """
455
    assert self.OP_ID is not None and len(self.OP_ID) > 3
456
    # all OP_ID start with OP_, we remove that
457
    txt = self.OP_ID[3:]
458
    field_name = getattr(self, "OP_DSC_FIELD", None)
459
    if field_name:
460
      field_value = getattr(self, field_name, None)
461
      if isinstance(field_value, (list, tuple)):
462
        field_value = ",".join(str(i) for i in field_value)
463
      txt = "%s(%s)" % (txt, field_value)
464
    return txt
465

    
466

    
467
# cluster opcodes
468

    
469
class OpClusterPostInit(OpCode):
470
  """Post cluster initialization.
471

472
  This opcode does not touch the cluster at all. Its purpose is to run hooks
473
  after the cluster has been initialized.
474

475
  """
476

    
477

    
478
class OpClusterDestroy(OpCode):
479
  """Destroy the cluster.
480

481
  This opcode has no other parameters. All the state is irreversibly
482
  lost after the execution of this opcode.
483

484
  """
485

    
486

    
487
class OpClusterQuery(OpCode):
488
  """Query cluster information."""
489

    
490

    
491
class OpClusterVerify(OpCode):
492
  """Verify the cluster state.
493

494
  @type skip_checks: C{list}
495
  @ivar skip_checks: steps to be skipped from the verify process; this
496
                     needs to be a subset of
497
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
498
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
499

500
  """
501
  OP_PARAMS = [
502
    ("skip_checks", ht.EmptyList,
503
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
504
    ("verbose", False, ht.TBool, None),
505
    ("error_codes", False, ht.TBool, None),
506
    ("debug_simulate_errors", False, ht.TBool, None),
507
    ]
508

    
509

    
510
class OpClusterVerifyDisks(OpCode):
511
  """Verify the cluster disks.
512

513
  Parameters: none
514

515
  Result: a tuple of four elements:
516
    - list of node names with bad data returned (unreachable, etc.)
517
    - dict of node names with broken volume groups (values: error msg)
518
    - list of instances with degraded disks (that should be activated)
519
    - dict of instances with missing logical volumes (values: (node, vol)
520
      pairs with details about the missing volumes)
521

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

527
  Note that only instances that are drbd-based are taken into
528
  consideration. This might need to be revisited in the future.
529

530
  """
531

    
532

    
533
class OpClusterRepairDiskSizes(OpCode):
534
  """Verify the disk sizes of the instances and fixes configuration
535
  mimatches.
536

537
  Parameters: optional instances list, in case we want to restrict the
538
  checks to only a subset of the instances.
539

540
  Result: a list of tuples, (instance, disk, new-size) for changed
541
  configurations.
542

543
  In normal operation, the list should be empty.
544

545
  @type instances: list
546
  @ivar instances: the list of instances to check, or empty for all instances
547

548
  """
549
  OP_PARAMS = [
550
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
551
    ]
552

    
553

    
554
class OpClusterConfigQuery(OpCode):
555
  """Query cluster configuration values."""
556
  OP_PARAMS = [
557
    _POutputFields
558
    ]
559

    
560

    
561
class OpClusterRename(OpCode):
562
  """Rename the cluster.
563

564
  @type name: C{str}
565
  @ivar name: The new name of the cluster. The name and/or the master IP
566
              address will be changed to match the new name and its IP
567
              address.
568

569
  """
570
  OP_DSC_FIELD = "name"
571
  OP_PARAMS = [
572
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
573
    ]
574

    
575

    
576
class OpClusterSetParams(OpCode):
577
  """Change the parameters of the cluster.
578

579
  @type vg_name: C{str} or C{None}
580
  @ivar vg_name: The new volume group name or None to disable LVM usage.
581

582
  """
583
  OP_PARAMS = [
584
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
585
    ("enabled_hypervisors", None,
586
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
587
            ht.TNone),
588
     "List of enabled hypervisors"),
589
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
590
                              ht.TNone),
591
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
592
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
593
     "Cluster-wide backend parameter defaults"),
594
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
595
                            ht.TNone),
596
     "Cluster-wide per-OS hypervisor parameter defaults"),
597
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
598
                              ht.TNone),
599
     "Cluster-wide OS parameter defaults"),
600
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
601
     "Master candidate pool size"),
602
    ("uid_pool", None, ht.NoType,
603
     "Set UID pool, must be list of lists describing UID ranges (two items,"
604
     " start and end inclusive)"),
605
    ("add_uids", None, ht.NoType,
606
     "Extend UID pool, must be list of lists describing UID ranges (two"
607
     " items, start and end inclusive) to be added"),
608
    ("remove_uids", None, ht.NoType,
609
     "Shrink UID pool, must be list of lists describing UID ranges (two"
610
     " items, start and end inclusive) to be removed"),
611
    ("maintain_node_health", None, ht.TMaybeBool,
612
     "Whether to automatically maintain node health"),
613
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
614
     "Whether to wipe disks before allocating them to instances"),
615
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
616
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
617
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
618
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
619
     "Default iallocator for cluster"),
620
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
621
     "Master network device"),
622
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
623
     "List of reserved LVs"),
624
    ("hidden_os", None, _TestClusterOsList,
625
     "Modify list of hidden operating systems. Each modification must have"
626
     " two items, the operation and the OS name. The operation can be"
627
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
628
    ("blacklisted_os", None, _TestClusterOsList,
629
     "Modify list of blacklisted operating systems. Each modification must have"
630
     " two items, the operation and the OS name. The operation can be"
631
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
632
    ]
633

    
634

    
635
class OpClusterRedistConf(OpCode):
636
  """Force a full push of the cluster configuration.
637

638
  """
639

    
640

    
641
class OpQuery(OpCode):
642
  """Query for resources/items.
643

644
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
645
  @ivar fields: List of fields to retrieve
646
  @ivar filter: Query filter
647

648
  """
649
  OP_PARAMS = [
650
    _PQueryWhat,
651
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
652
     "Requested fields"),
653
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
654
     "Query filter"),
655
    ]
656

    
657

    
658
class OpQueryFields(OpCode):
659
  """Query for available resource/item fields.
660

661
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
662
  @ivar fields: List of fields to retrieve
663

664
  """
665
  OP_PARAMS = [
666
    _PQueryWhat,
667
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
668
     "Requested fields; if not given, all are returned"),
669
    ]
670

    
671

    
672
class OpOobCommand(OpCode):
673
  """Interact with OOB."""
674
  OP_PARAMS = [
675
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
676
     "List of nodes to run the OOB command against"),
677
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
678
     "OOB command to be run"),
679
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
680
     "Timeout before the OOB helper will be terminated"),
681
    ("ignore_status", False, ht.TBool,
682
     "Ignores the node offline status for power off"),
683
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
684
     "Time in seconds to wait between powering on nodes"),
685
    ]
686

    
687

    
688
# node opcodes
689

    
690
class OpNodeRemove(OpCode):
691
  """Remove a node.
692

693
  @type node_name: C{str}
694
  @ivar node_name: The name of the node to remove. If the node still has
695
                   instances on it, the operation will fail.
696

697
  """
698
  OP_DSC_FIELD = "node_name"
699
  OP_PARAMS = [
700
    _PNodeName,
701
    ]
702

    
703

    
704
class OpNodeAdd(OpCode):
705
  """Add a node to the cluster.
706

707
  @type node_name: C{str}
708
  @ivar node_name: The name of the node to add. This can be a short name,
709
                   but it will be expanded to the FQDN.
710
  @type primary_ip: IP address
711
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
712
                    opcode is submitted, but will be filled during the node
713
                    add (so it will be visible in the job query).
714
  @type secondary_ip: IP address
715
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
716
                      if the cluster has been initialized in 'dual-network'
717
                      mode, otherwise it must not be given.
718
  @type readd: C{bool}
719
  @ivar readd: Whether to re-add an existing node to the cluster. If
720
               this is not passed, then the operation will abort if the node
721
               name is already in the cluster; use this parameter to 'repair'
722
               a node that had its configuration broken, or was reinstalled
723
               without removal from the cluster.
724
  @type group: C{str}
725
  @ivar group: The node group to which this node will belong.
726
  @type vm_capable: C{bool}
727
  @ivar vm_capable: The vm_capable node attribute
728
  @type master_capable: C{bool}
729
  @ivar master_capable: The master_capable node attribute
730

731
  """
732
  OP_DSC_FIELD = "node_name"
733
  OP_PARAMS = [
734
    _PNodeName,
735
    ("primary_ip", None, ht.NoType, "Primary IP address"),
736
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
737
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
738
    ("group", None, ht.TMaybeString, "Initial node group"),
739
    ("master_capable", None, ht.TMaybeBool,
740
     "Whether node can become master or master candidate"),
741
    ("vm_capable", None, ht.TMaybeBool,
742
     "Whether node can host instances"),
743
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
744
    ]
745

    
746

    
747
class OpNodeQuery(OpCode):
748
  """Compute the list of nodes."""
749
  OP_PARAMS = [
750
    _POutputFields,
751
    _PUseLocking,
752
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
753
     "Empty list to query all nodes, node names otherwise"),
754
    ]
755

    
756

    
757
class OpNodeQueryvols(OpCode):
758
  """Get list of volumes on node."""
759
  OP_PARAMS = [
760
    _POutputFields,
761
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
762
     "Empty list to query all nodes, node names otherwise"),
763
    ]
764

    
765

    
766
class OpNodeQueryStorage(OpCode):
767
  """Get information on storage for node(s)."""
768
  OP_PARAMS = [
769
    _POutputFields,
770
    _PStorageType,
771
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
772
    ("name", None, ht.TMaybeString, "Storage name"),
773
    ]
774

    
775

    
776
class OpNodeModifyStorage(OpCode):
777
  """Modifies the properies of a storage unit"""
778
  OP_PARAMS = [
779
    _PNodeName,
780
    _PStorageType,
781
    _PStorageName,
782
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
783
    ]
784

    
785

    
786
class OpRepairNodeStorage(OpCode):
787
  """Repairs the volume group on a node."""
788
  OP_DSC_FIELD = "node_name"
789
  OP_PARAMS = [
790
    _PNodeName,
791
    _PStorageType,
792
    _PStorageName,
793
    _PIgnoreConsistency,
794
    ]
795

    
796

    
797
class OpNodeSetParams(OpCode):
798
  """Change the parameters of a node."""
799
  OP_DSC_FIELD = "node_name"
800
  OP_PARAMS = [
801
    _PNodeName,
802
    _PForce,
803
    ("master_candidate", None, ht.TMaybeBool,
804
     "Whether the node should become a master candidate"),
805
    ("offline", None, ht.TMaybeBool,
806
     "Whether the node should be marked as offline"),
807
    ("drained", None, ht.TMaybeBool,
808
     "Whether the node should be marked as drained"),
809
    ("auto_promote", False, ht.TBool,
810
     "Whether node(s) should be promoted to master candidate if necessary"),
811
    ("master_capable", None, ht.TMaybeBool,
812
     "Denote whether node can become master or master candidate"),
813
    ("vm_capable", None, ht.TMaybeBool,
814
     "Denote whether node can host instances"),
815
    ("secondary_ip", None, ht.TMaybeString,
816
     "Change node's secondary IP address"),
817
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
818
    ("powered", None, ht.TMaybeBool,
819
     "Whether the node should be marked as powered"),
820
    ]
821

    
822

    
823
class OpNodePowercycle(OpCode):
824
  """Tries to powercycle a node."""
825
  OP_DSC_FIELD = "node_name"
826
  OP_PARAMS = [
827
    _PNodeName,
828
    _PForce,
829
    ]
830

    
831

    
832
class OpNodeMigrate(OpCode):
833
  """Migrate all instances from a node."""
834
  OP_DSC_FIELD = "node_name"
835
  OP_PARAMS = [
836
    _PNodeName,
837
    _PMigrationMode,
838
    _PMigrationLive,
839
    ("iallocator", None, ht.TMaybeString,
840
     "Iallocator for deciding the target node for shared-storage instances"),
841
    ]
842

    
843

    
844
class OpNodeEvacStrategy(OpCode):
845
  """Compute the evacuation strategy for a list of nodes."""
846
  OP_DSC_FIELD = "nodes"
847
  OP_PARAMS = [
848
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString), None),
849
    ("remote_node", None, ht.TMaybeString, None),
850
    ("iallocator", None, ht.TMaybeString, None),
851
    ]
852

    
853

    
854
# instance opcodes
855

    
856
class OpInstanceCreate(OpCode):
857
  """Create an instance.
858

859
  @ivar instance_name: Instance name
860
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
861
  @ivar source_handshake: Signed handshake from source (remote import only)
862
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
863
  @ivar source_instance_name: Previous name of instance (remote import only)
864
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
865
    (remote import only)
866

867
  """
868
  OP_DSC_FIELD = "instance_name"
869
  OP_PARAMS = [
870
    _PInstanceName,
871
    _PForceVariant,
872
    _PWaitForSync,
873
    _PNameCheck,
874
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
875
    ("disks", ht.NoDefault,
876
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
877
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
878
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
879
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
880
     " each disk definition must contain a ``%s`` value and"
881
     " can contain an optional ``%s`` value denoting the disk access mode"
882
     " (%s)" %
883
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
884
      constants.IDISK_MODE,
885
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
886
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
887
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
888
     "Driver for file-backed disks"),
889
    ("file_storage_dir", None, ht.TMaybeString,
890
     "Directory for storing file-backed disks"),
891
    ("hvparams", ht.EmptyDict, ht.TDict,
892
     "Hypervisor parameters for instance, hypervisor-dependent"),
893
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
894
    ("iallocator", None, ht.TMaybeString,
895
     "Iallocator for deciding which node(s) to use"),
896
    ("identify_defaults", False, ht.TBool,
897
     "Reset instance parameters to default if equal"),
898
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
899
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
900
     "Instance creation mode"),
901
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
902
     "List of NIC (network interface) definitions, for example"
903
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
904
     " contain the optional values %s" %
905
     (constants.INIC_IP,
906
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
907
    ("no_install", None, ht.TMaybeBool,
908
     "Do not install the OS (will disable automatic start)"),
909
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
910
    ("os_type", None, ht.TMaybeString, "Operating system"),
911
    ("pnode", None, ht.TMaybeString, "Primary node"),
912
    ("snode", None, ht.TMaybeString, "Secondary node"),
913
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
914
     "Signed handshake from source (remote import only)"),
915
    ("source_instance_name", None, ht.TMaybeString,
916
     "Source instance name (remote import only)"),
917
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
918
     ht.TPositiveInt,
919
     "How long source instance was given to shut down (remote import only)"),
920
    ("source_x509_ca", None, ht.TMaybeString,
921
     "Source X509 CA in PEM format (remote import only)"),
922
    ("src_node", None, ht.TMaybeString, "Source node for import"),
923
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
924
    ("start", True, ht.TBool, "Whether to start instance after creation"),
925
    ]
926

    
927

    
928
class OpInstanceReinstall(OpCode):
929
  """Reinstall an instance's OS."""
930
  OP_DSC_FIELD = "instance_name"
931
  OP_PARAMS = [
932
    _PInstanceName,
933
    _PForceVariant,
934
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
935
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
936
    ]
937

    
938

    
939
class OpInstanceRemove(OpCode):
940
  """Remove an instance."""
941
  OP_DSC_FIELD = "instance_name"
942
  OP_PARAMS = [
943
    _PInstanceName,
944
    _PShutdownTimeout,
945
    ("ignore_failures", False, ht.TBool,
946
     "Whether to ignore failures during removal"),
947
    ]
948

    
949

    
950
class OpInstanceRename(OpCode):
951
  """Rename an instance."""
952
  OP_PARAMS = [
953
    _PInstanceName,
954
    _PNameCheck,
955
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
956
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
957
    ]
958

    
959

    
960
class OpInstanceStartup(OpCode):
961
  """Startup an instance."""
962
  OP_DSC_FIELD = "instance_name"
963
  OP_PARAMS = [
964
    _PInstanceName,
965
    _PForce,
966
    _PIgnoreOfflineNodes,
967
    ("hvparams", ht.EmptyDict, ht.TDict,
968
     "Temporary hypervisor parameters, hypervisor-dependent"),
969
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
970
    ]
971

    
972

    
973
class OpInstanceShutdown(OpCode):
974
  """Shutdown an instance."""
975
  OP_DSC_FIELD = "instance_name"
976
  OP_PARAMS = [
977
    _PInstanceName,
978
    _PIgnoreOfflineNodes,
979
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
980
     "How long to wait for instance to shut down"),
981
    ]
982

    
983

    
984
class OpInstanceReboot(OpCode):
985
  """Reboot an instance."""
986
  OP_DSC_FIELD = "instance_name"
987
  OP_PARAMS = [
988
    _PInstanceName,
989
    _PShutdownTimeout,
990
    ("ignore_secondaries", False, ht.TBool,
991
     "Whether to start the instance even if secondary disks are failing"),
992
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
993
     "How to reboot instance"),
994
    ]
995

    
996

    
997
class OpInstanceReplaceDisks(OpCode):
998
  """Replace the disks of an instance."""
999
  OP_DSC_FIELD = "instance_name"
1000
  OP_PARAMS = [
1001
    _PInstanceName,
1002
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1003
     "Replacement mode"),
1004
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1005
     "Disk indexes"),
1006
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1007
    ("iallocator", None, ht.TMaybeString,
1008
     "Iallocator for deciding new secondary node"),
1009
    ("early_release", False, ht.TBool,
1010
     "Whether to release locks as soon as possible"),
1011
    ]
1012

    
1013

    
1014
class OpInstanceFailover(OpCode):
1015
  """Failover an instance."""
1016
  OP_DSC_FIELD = "instance_name"
1017
  OP_PARAMS = [
1018
    _PInstanceName,
1019
    _PShutdownTimeout,
1020
    _PIgnoreConsistency,
1021
    ("iallocator", None, ht.TMaybeString,
1022
     "Iallocator for deciding the target node for shared-storage instances"),
1023
    ("target_node", None, ht.TMaybeString,
1024
     "Target node for shared-storage instances"),
1025
    ]
1026

    
1027

    
1028
class OpInstanceMigrate(OpCode):
1029
  """Migrate an instance.
1030

1031
  This migrates (without shutting down an instance) to its secondary
1032
  node.
1033

1034
  @ivar instance_name: the name of the instance
1035
  @ivar mode: the migration mode (live, non-live or None for auto)
1036

1037
  """
1038
  OP_DSC_FIELD = "instance_name"
1039
  OP_PARAMS = [
1040
    _PInstanceName,
1041
    _PMigrationMode,
1042
    _PMigrationLive,
1043
    ("cleanup", False, ht.TBool,
1044
     "Whether a previously failed migration should be cleaned up"),
1045
    ("iallocator", None, ht.TMaybeString,
1046
     "Iallocator for deciding the target node for shared-storage instances"),
1047
    ("target_node", None, ht.TMaybeString,
1048
     "Target node for shared-storage instances"),
1049
    ("allow_failover", False, ht.TBool,
1050
     "Whether we can fallback to failover if migration is not possible"),
1051
    ]
1052

    
1053

    
1054
class OpInstanceMove(OpCode):
1055
  """Move an instance.
1056

1057
  This move (with shutting down an instance and data copying) to an
1058
  arbitrary node.
1059

1060
  @ivar instance_name: the name of the instance
1061
  @ivar target_node: the destination node
1062

1063
  """
1064
  OP_DSC_FIELD = "instance_name"
1065
  OP_PARAMS = [
1066
    _PInstanceName,
1067
    _PShutdownTimeout,
1068
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1069
    ]
1070

    
1071

    
1072
class OpInstanceConsole(OpCode):
1073
  """Connect to an instance's console."""
1074
  OP_DSC_FIELD = "instance_name"
1075
  OP_PARAMS = [
1076
    _PInstanceName
1077
    ]
1078

    
1079

    
1080
class OpInstanceActivateDisks(OpCode):
1081
  """Activate an instance's disks."""
1082
  OP_DSC_FIELD = "instance_name"
1083
  OP_PARAMS = [
1084
    _PInstanceName,
1085
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1086
    ]
1087

    
1088

    
1089
class OpInstanceDeactivateDisks(OpCode):
1090
  """Deactivate an instance's disks."""
1091
  OP_DSC_FIELD = "instance_name"
1092
  OP_PARAMS = [
1093
    _PInstanceName,
1094
    _PForce,
1095
    ]
1096

    
1097

    
1098
class OpInstanceRecreateDisks(OpCode):
1099
  """Deactivate an instance's disks."""
1100
  OP_DSC_FIELD = "instance_name"
1101
  OP_PARAMS = [
1102
    _PInstanceName,
1103
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1104
     "List of disk indexes"),
1105
    ]
1106

    
1107

    
1108
class OpInstanceQuery(OpCode):
1109
  """Compute the list of instances."""
1110
  OP_PARAMS = [
1111
    _POutputFields,
1112
    _PUseLocking,
1113
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1114
     "Empty list to query all instances, instance names otherwise"),
1115
    ]
1116

    
1117

    
1118
class OpInstanceQueryData(OpCode):
1119
  """Compute the run-time status of instances."""
1120
  OP_PARAMS = [
1121
    _PUseLocking,
1122
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1123
     "Instance names"),
1124
    ("static", False, ht.TBool,
1125
     "Whether to only return configuration data without querying"
1126
     " nodes"),
1127
    ]
1128

    
1129

    
1130
class OpInstanceSetParams(OpCode):
1131
  """Change the parameters of an instance."""
1132
  OP_DSC_FIELD = "instance_name"
1133
  OP_PARAMS = [
1134
    _PInstanceName,
1135
    _PForce,
1136
    _PForceVariant,
1137
    # TODO: Use _TestNicDef
1138
    ("nics", ht.EmptyList, ht.TList,
1139
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1140
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1141
     " ``%s`` to remove the last NIC or a number to modify the settings"
1142
     " of the NIC with that index." %
1143
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1144
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1145
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1146
    ("hvparams", ht.EmptyDict, ht.TDict,
1147
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1148
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1149
     "Disk template for instance"),
1150
    ("remote_node", None, ht.TMaybeString,
1151
     "Secondary node (used when changing disk template)"),
1152
    ("os_name", None, ht.TMaybeString,
1153
     "Change instance's OS name. Does not reinstall the instance."),
1154
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1155
    ]
1156

    
1157

    
1158
class OpInstanceGrowDisk(OpCode):
1159
  """Grow a disk of an instance."""
1160
  OP_DSC_FIELD = "instance_name"
1161
  OP_PARAMS = [
1162
    _PInstanceName,
1163
    _PWaitForSync,
1164
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1165
    ("amount", ht.NoDefault, ht.TInt,
1166
     "Amount of disk space to add (megabytes)"),
1167
    ]
1168

    
1169

    
1170
# Node group opcodes
1171

    
1172
class OpGroupAdd(OpCode):
1173
  """Add a node group to the cluster."""
1174
  OP_DSC_FIELD = "group_name"
1175
  OP_PARAMS = [
1176
    _PGroupName,
1177
    _PNodeGroupAllocPolicy,
1178
    _PGroupNodeParams,
1179
    ]
1180

    
1181

    
1182
class OpGroupAssignNodes(OpCode):
1183
  """Assign nodes to a node group."""
1184
  OP_DSC_FIELD = "group_name"
1185
  OP_PARAMS = [
1186
    _PGroupName,
1187
    _PForce,
1188
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1189
     "List of nodes to assign"),
1190
    ]
1191

    
1192

    
1193
class OpGroupQuery(OpCode):
1194
  """Compute the list of node groups."""
1195
  OP_PARAMS = [
1196
    _POutputFields,
1197
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1198
     "Empty list to query all groups, group names otherwise"),
1199
    ]
1200

    
1201

    
1202
class OpGroupSetParams(OpCode):
1203
  """Change the parameters of a node group."""
1204
  OP_DSC_FIELD = "group_name"
1205
  OP_PARAMS = [
1206
    _PGroupName,
1207
    _PNodeGroupAllocPolicy,
1208
    _PGroupNodeParams,
1209
    ]
1210

    
1211

    
1212
class OpGroupRemove(OpCode):
1213
  """Remove a node group from the cluster."""
1214
  OP_DSC_FIELD = "group_name"
1215
  OP_PARAMS = [
1216
    _PGroupName,
1217
    ]
1218

    
1219

    
1220
class OpGroupRename(OpCode):
1221
  """Rename a node group in the cluster."""
1222
  OP_PARAMS = [
1223
    _PGroupName,
1224
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1225
    ]
1226

    
1227

    
1228
# OS opcodes
1229
class OpOsDiagnose(OpCode):
1230
  """Compute the list of guest operating systems."""
1231
  OP_PARAMS = [
1232
    _POutputFields,
1233
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1234
     "Which operating systems to diagnose"),
1235
    ]
1236

    
1237

    
1238
# Exports opcodes
1239
class OpBackupQuery(OpCode):
1240
  """Compute the list of exported images."""
1241
  OP_PARAMS = [
1242
    _PUseLocking,
1243
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1244
     "Empty list to query all nodes, node names otherwise"),
1245
    ]
1246

    
1247

    
1248
class OpBackupPrepare(OpCode):
1249
  """Prepares an instance export.
1250

1251
  @ivar instance_name: Instance name
1252
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1253

1254
  """
1255
  OP_DSC_FIELD = "instance_name"
1256
  OP_PARAMS = [
1257
    _PInstanceName,
1258
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1259
     "Export mode"),
1260
    ]
1261

    
1262

    
1263
class OpBackupExport(OpCode):
1264
  """Export an instance.
1265

1266
  For local exports, the export destination is the node name. For remote
1267
  exports, the export destination is a list of tuples, each consisting of
1268
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1269
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1270
  destination X509 CA must be a signed certificate.
1271

1272
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1273
  @ivar target_node: Export destination
1274
  @ivar x509_key_name: X509 key to use (remote export only)
1275
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1276
                             only)
1277

1278
  """
1279
  OP_DSC_FIELD = "instance_name"
1280
  OP_PARAMS = [
1281
    _PInstanceName,
1282
    _PShutdownTimeout,
1283
    # TODO: Rename target_node as it changes meaning for different export modes
1284
    # (e.g. "destination")
1285
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1286
     "Destination information, depends on export mode"),
1287
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1288
    ("remove_instance", False, ht.TBool,
1289
     "Whether to remove instance after export"),
1290
    ("ignore_remove_failures", False, ht.TBool,
1291
     "Whether to ignore failures while removing instances"),
1292
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1293
     "Export mode"),
1294
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1295
     "Name of X509 key (remote export only)"),
1296
    ("destination_x509_ca", None, ht.TMaybeString,
1297
     "Destination X509 CA (remote export only)"),
1298
    ]
1299

    
1300

    
1301
class OpBackupRemove(OpCode):
1302
  """Remove an instance's export."""
1303
  OP_DSC_FIELD = "instance_name"
1304
  OP_PARAMS = [
1305
    _PInstanceName,
1306
    ]
1307

    
1308

    
1309
# Tags opcodes
1310
class OpTagsGet(OpCode):
1311
  """Returns the tags of the given object."""
1312
  OP_DSC_FIELD = "name"
1313
  OP_PARAMS = [
1314
    _PTagKind,
1315
    # Name is only meaningful for nodes and instances
1316
    ("name", ht.NoDefault, ht.TMaybeString, None),
1317
    ]
1318

    
1319

    
1320
class OpTagsSearch(OpCode):
1321
  """Searches the tags in the cluster for a given pattern."""
1322
  OP_DSC_FIELD = "pattern"
1323
  OP_PARAMS = [
1324
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1325
    ]
1326

    
1327

    
1328
class OpTagsSet(OpCode):
1329
  """Add a list of tags on a given object."""
1330
  OP_PARAMS = [
1331
    _PTagKind,
1332
    _PTags,
1333
    # Name is only meaningful for nodes and instances
1334
    ("name", ht.NoDefault, ht.TMaybeString, None),
1335
    ]
1336

    
1337

    
1338
class OpTagsDel(OpCode):
1339
  """Remove a list of tags from a given object."""
1340
  OP_PARAMS = [
1341
    _PTagKind,
1342
    _PTags,
1343
    # Name is only meaningful for nodes and instances
1344
    ("name", ht.NoDefault, ht.TMaybeString, None),
1345
    ]
1346

    
1347
# Test opcodes
1348
class OpTestDelay(OpCode):
1349
  """Sleeps for a configured amount of time.
1350

1351
  This is used just for debugging and testing.
1352

1353
  Parameters:
1354
    - duration: the time to sleep
1355
    - on_master: if true, sleep on the master
1356
    - on_nodes: list of nodes in which to sleep
1357

1358
  If the on_master parameter is true, it will execute a sleep on the
1359
  master (before any node sleep).
1360

1361
  If the on_nodes list is not empty, it will sleep on those nodes
1362
  (after the sleep on the master, if that is enabled).
1363

1364
  As an additional feature, the case of duration < 0 will be reported
1365
  as an execution error, so this opcode can be used as a failure
1366
  generator. The case of duration == 0 will not be treated specially.
1367

1368
  """
1369
  OP_DSC_FIELD = "duration"
1370
  OP_PARAMS = [
1371
    ("duration", ht.NoDefault, ht.TFloat, None),
1372
    ("on_master", True, ht.TBool, None),
1373
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1374
    ("repeat", 0, ht.TPositiveInt, None),
1375
    ]
1376

    
1377

    
1378
class OpTestAllocator(OpCode):
1379
  """Allocator framework testing.
1380

1381
  This opcode has two modes:
1382
    - gather and return allocator input for a given mode (allocate new
1383
      or replace secondary) and a given instance definition (direction
1384
      'in')
1385
    - run a selected allocator for a given operation (as above) and
1386
      return the allocator output (direction 'out')
1387

1388
  """
1389
  OP_DSC_FIELD = "allocator"
1390
  OP_PARAMS = [
1391
    ("direction", ht.NoDefault,
1392
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1393
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1394
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1395
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1396
     ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
1397
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1398
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1399
    ("hypervisor", None, ht.TMaybeString, None),
1400
    ("allocator", None, ht.TMaybeString, None),
1401
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1402
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1403
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1404
    ("os", None, ht.TMaybeString, None),
1405
    ("disk_template", None, ht.TMaybeString, None),
1406
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1407
     None),
1408
    ]
1409

    
1410

    
1411
class OpTestJqueue(OpCode):
1412
  """Utility opcode to test some aspects of the job queue.
1413

1414
  """
1415
  OP_PARAMS = [
1416
    ("notify_waitlock", False, ht.TBool, None),
1417
    ("notify_exec", False, ht.TBool, None),
1418
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1419
    ("fail", False, ht.TBool, None),
1420
    ]
1421

    
1422

    
1423
class OpTestDummy(OpCode):
1424
  """Utility opcode used by unittests.
1425

1426
  """
1427
  OP_PARAMS = [
1428
    ("result", ht.NoDefault, ht.NoType, None),
1429
    ("messages", ht.NoDefault, ht.NoType, None),
1430
    ("fail", ht.NoDefault, ht.NoType, None),
1431
    ("submit_jobs", None, ht.NoType, None),
1432
    ]
1433
  WITH_LU = False
1434

    
1435

    
1436
def _GetOpList():
1437
  """Returns list of all defined opcodes.
1438

1439
  Does not eliminate duplicates by C{OP_ID}.
1440

1441
  """
1442
  return [v for v in globals().values()
1443
          if (isinstance(v, type) and issubclass(v, OpCode) and
1444
              hasattr(v, "OP_ID") and v is not OpCode)]
1445

    
1446

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